-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathwin32_helpers.h
More file actions
1427 lines (1274 loc) · 64.7 KB
/
Copy pathwin32_helpers.h
File metadata and controls
1427 lines (1274 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT.
//
//*********************************************************
//! @file
//! Various types and helpers for interfacing with various Win32 APIs
#ifndef __WIL_WIN32_HELPERS_INCLUDED
#define __WIL_WIN32_HELPERS_INCLUDED
#include <minwindef.h> // FILETIME, HINSTANCE
#include <sysinfoapi.h> // GetSystemTimeAsFileTime
#include <libloaderapi.h> // GetProcAddress
#include <Psapi.h> // GetModuleFileNameExW (macro), K32GetModuleFileNameExW
#include <winreg.h>
#include <objbase.h>
#include "common.h"
#if WIL_USE_STL
#include <string>
#if (__WI_LIBCPP_STD_VER >= 17) && WI_HAS_INCLUDE(<string_view>, 1) // Assume present if C++17
#include <string_view>
#endif
#if (__WI_LIBCPP_STD_VER >= 20)
#if WI_HAS_INCLUDE(<bit>, 1) // Assume present if C++20
#include <bit>
#endif
#if WI_HAS_INCLUDE(<compare>, 1) // Assume present if C++20
#include <compare>
#endif
#endif
#endif
/// @cond
#if WIL_USE_STL && (__cpp_lib_bit_cast >= 201806L)
#define __WI_CONSTEXPR_BIT_CAST constexpr
#else
#define __WI_CONSTEXPR_BIT_CAST // All uses are templates, which is implicitly inline
#endif
/// @endcond
#include "result.h"
#include "resource.h"
#include "wistd_functional.h"
#include "wistd_type_traits.h"
/// @cond
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
/// @endcond
/// @cond
namespace wistd
{
#if WIL_USE_STL && (__cpp_lib_three_way_comparison >= 201907L)
using weak_ordering = std::weak_ordering;
#else
struct weak_ordering
{
static const weak_ordering less;
static const weak_ordering equivalent;
static const weak_ordering greater;
[[nodiscard]] friend constexpr bool operator==(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value == 0;
}
[[nodiscard]] friend constexpr bool operator!=(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value != 0;
}
[[nodiscard]] friend constexpr bool operator<(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value < 0;
}
[[nodiscard]] friend constexpr bool operator>(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value > 0;
}
[[nodiscard]] friend constexpr bool operator<=(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value <= 0;
}
[[nodiscard]] friend constexpr bool operator>=(const weak_ordering left, std::nullptr_t) noexcept
{
return left.m_value >= 0;
}
[[nodiscard]] friend constexpr bool operator==(std::nullptr_t, const weak_ordering right) noexcept
{
return right == 0;
}
[[nodiscard]] friend constexpr bool operator!=(std::nullptr_t, const weak_ordering right) noexcept
{
return right != 0;
}
[[nodiscard]] friend constexpr bool operator<(std::nullptr_t, const weak_ordering right) noexcept
{
return right > 0;
}
[[nodiscard]] friend constexpr bool operator>(std::nullptr_t, const weak_ordering right) noexcept
{
return right < 0;
}
[[nodiscard]] friend constexpr bool operator<=(std::nullptr_t, const weak_ordering right) noexcept
{
return right >= 0;
}
[[nodiscard]] friend constexpr bool operator>=(std::nullptr_t, const weak_ordering right) noexcept
{
return right <= 0;
}
signed char m_value;
};
__WI_LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::less{static_cast<signed char>(-1)};
__WI_LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::equivalent{static_cast<signed char>(0)};
__WI_LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::greater{static_cast<signed char>(1)};
#endif
} // namespace wistd
/// @endcond
namespace wil
{
//! Strictly a function of the file system but this is the value for all known file system, NTFS, FAT.
//! CDFs has a limit of 254.
constexpr size_t max_path_segment_length = 255;
//! Character length not including the null, MAX_PATH (260) includes the null.
constexpr size_t max_path_length = 259;
//! 32743 Character length not including the null. This is a system defined limit.
//! The 24 is for the expansion of the roots from "C:" to "\Device\HarddiskVolume4"
//! It will be 25 when there are more than 9 disks.
constexpr size_t max_extended_path_length = 0x7FFF - 24;
//! For {guid} string form. Includes space for the null terminator.
constexpr size_t guid_string_buffer_length = 39;
//! For {guid} string form. Not including the null terminator.
constexpr size_t guid_string_length = 38;
#pragma region String and identifier comparisons
// Using CompareStringOrdinal functions:
//
// Identifiers require a locale-less (ordinal), and often case-insensitive, comparison (filenames, registry keys, XML node names,
// etc). DO NOT use locale-sensitive (lexical) comparisons for resource identifiers (e.g. wcs*() functions in the CRT).
#if WIL_USE_STL && (__cpp_lib_string_view >= 201606L)
/// @cond
namespace details
{
[[nodiscard]] inline int CompareStringOrdinal(std::wstring_view left, std::wstring_view right, bool caseInsensitive) WI_NOEXCEPT
{
// Casting from size_t (unsigned) to int (signed) should be safe from overrun to a negative,
// merely truncating the string. CompareStringOrdinal should be resilient to negatives.
return ::CompareStringOrdinal(
left.data(), static_cast<int>(left.size()), right.data(), static_cast<int>(right.size()), caseInsensitive);
}
} // namespace details
/// @endcond
/** Performs an ordinal (locale-independent) comparison of two strings and returns their relative order.
Use ordinal comparisons for resource identifiers such as filenames, registry keys, and XML node names, where a locale-sensitive
(lexical) comparison would be incorrect. Wraps `CompareStringOrdinal`.
@param left The first string to compare.
@param right The second string to compare.
@param caseInsensitive `true` to compare without regard to case; `false` for a case-sensitive comparison.
@return A `wistd::weak_ordering` that is `less`, `equivalent`, or `greater` for `left` relative to `right`. */
[[nodiscard]] inline wistd::weak_ordering compare_string_ordinal(std::wstring_view left, std::wstring_view right, bool caseInsensitive) WI_NOEXCEPT
{
switch (wil::details::CompareStringOrdinal(left, right, caseInsensitive))
{
case CSTR_LESS_THAN:
return wistd::weak_ordering::less;
case CSTR_GREATER_THAN:
return wistd::weak_ordering::greater;
default:
return wistd::weak_ordering::equivalent;
}
}
#endif
#pragma endregion
#pragma region FILETIME helpers
//! Common FILETIME durations, expressed in the 100-nanosecond units that `FILETIME` uses.
namespace filetime_duration
{
//! One millisecond, in 100-nanosecond units.
long long const one_millisecond = 10000LL;
//! One second, in 100-nanosecond units.
long long const one_second = 10000000LL;
//! One minute, in 100-nanosecond units.
long long const one_minute = 10000000LL * 60; // 600000000 or 600000000LL
//! One hour, in 100-nanosecond units.
long long const one_hour = 10000000LL * 60 * 60; // 36000000000 or 36000000000LL
//! One day, in 100-nanosecond units.
long long const one_day = 10000000LL * 60 * 60 * 24; // 864000000000 or 864000000000LL
}; // namespace filetime_duration
namespace filetime
{
/// Reinterprets a `FILETIME` as a 64-bit integer count of 100-nanosecond units.
/// @tparam Int64 A 64-bit integral type to return the value as; defaults to `unsigned long long`.
/// @param val The `FILETIME` to convert.
/// @return The `FILETIME` reinterpreted as a single 64-bit integer.
template <typename Int64 = unsigned long long, wistd::enable_if_t<wistd::is_integral_v<Int64> && (sizeof(Int64) == sizeof(FILETIME)), int> = 0>
constexpr Int64 to_int64(const FILETIME& val) WI_NOEXCEPT
{
#if WIL_USE_STL && (__cpp_lib_bit_cast >= 201806L)
return std::bit_cast<Int64>(val);
#else
// Cannot reinterpret_cast FILETIME* to Int64* due to alignment differences.
return (static_cast<Int64>(val.dwHighDateTime) << 32) + val.dwLowDateTime;
#endif
}
/// @cond
namespace details
{
template <typename Int>
using select_int64 =
wistd::conditional_t<sizeof(Int) == 8, Int, wistd::conditional_t<wistd::is_signed_v<Int>, long long, unsigned long long>>;
}
/// @endcond
/// Converts an integer count of 100-nanosecond units into a `FILETIME`.
/// @tparam Int An integral type no larger than `FILETIME` (8 bytes).
/// @param val The 100-nanosecond count to convert.
/// @return A `FILETIME` representing the given count.
template <typename Int, wistd::enable_if_t<wistd::is_integral_v<Int> && (sizeof(Int) <= sizeof(FILETIME)), int> = 0>
__WI_CONSTEXPR_BIT_CAST FILETIME from_int64(Int val) WI_NOEXCEPT
{
using Int64 = details::select_int64<Int>;
auto i64 = static_cast<Int64>(val);
#if WIL_USE_STL && (__cpp_lib_bit_cast >= 201806L)
return std::bit_cast<FILETIME>(i64);
#else
static_assert(sizeof(i64) == sizeof(FILETIME), "sizes don't match");
static_assert(__alignof(Int64) >= __alignof(FILETIME), "alignment not compatible with type pun");
return *reinterpret_cast<FILETIME*>(&i64);
#endif
}
/// Adds a 100-nanosecond delta to a `FILETIME` and returns the resulting time.
/// @tparam Int An integral type no larger than `FILETIME` (8 bytes).
/// @param baseTime The starting time.
/// @param delta100ns The number of 100-nanosecond units to add (negative values move backwards in time).
/// @return `baseTime` advanced by `delta100ns`, as a new `FILETIME`.
template <typename Int, wistd::enable_if_t<wistd::is_integral_v<Int> && (sizeof(Int) <= sizeof(FILETIME)), int> = 0>
__WI_CONSTEXPR_BIT_CAST FILETIME add(FILETIME const& baseTime, Int delta100ns) WI_NOEXCEPT
{
using Int64 = details::select_int64<Int>;
return from_int64(to_int64<Int64>(baseTime) + delta100ns);
}
/// Returns whether a `FILETIME` is zero (both `dwHighDateTime` and `dwLowDateTime` are 0).
/// @param val The `FILETIME` to test.
/// @return `true` if `val` is all zero, `false` otherwise.
constexpr bool is_empty(const FILETIME& val) WI_NOEXCEPT
{
return (val.dwHighDateTime == 0) && (val.dwLowDateTime == 0);
}
/// Returns the current system time (UTC) as a `FILETIME`, via `GetSystemTimeAsFileTime`.
/// @return The current system time.
inline FILETIME get_system_time() WI_NOEXCEPT
{
FILETIME now;
GetSystemTimeAsFileTime(&now);
return now;
}
/// Convert time as units of 100 nanoseconds to milliseconds. Fractional milliseconds are truncated.
constexpr unsigned long long convert_100ns_to_msec(unsigned long long time100ns) WI_NOEXCEPT
{
return time100ns / filetime_duration::one_millisecond;
}
/// Convert time as milliseconds to units of 100 nanoseconds.
constexpr unsigned long long convert_msec_to_100ns(unsigned long long timeMsec) WI_NOEXCEPT
{
return timeMsec * filetime_duration::one_millisecond;
}
#if (defined(_APISETREALTIME_) && (_WIN32_WINNT >= _WIN32_WINNT_WIN7)) || defined(WIL_DOXYGEN)
/// Returns the current unbiased interrupt-time count, in units of 100 nanoseconds. The unbiased interrupt-time count does not
/// include time the system spends in sleep or hibernation.
///
/// This API avoids prematurely shortcircuiting timing loops due to system sleep/hibernation.
///
/// This is equivalent to GetTickCount64() except it returns units of 100 nanoseconds instead of milliseconds, and it doesn't
/// include time the system spends in sleep or hibernation.
/// For example
///
/// start = GetTickCount64();
/// hibernate();
/// ...wake from hibernation 30 minutes later...;
/// elapsed = GetTickCount64() - start;
/// // elapsed = 30min
///
/// Do the same using unbiased interrupt-time and elapsed is 0 (or nearly so).
///
/// @note This is identical to QueryUnbiasedInterruptTime() but returns the value as a return value (rather than an out
/// parameter).
/// @see https://msdn.microsoft.com/en-us/library/windows/desktop/ee662307(v=vs.85).aspx
inline unsigned long long QueryUnbiasedInterruptTimeAs100ns() WI_NOEXCEPT
{
ULONGLONG now{};
QueryUnbiasedInterruptTime(&now);
return now;
}
/// Returns the current unbiased interrupt-time count, in units of milliseconds. The unbiased interrupt-time count does not
/// include time the system spends in sleep or hibernation.
/// @see QueryUnbiasedInterruptTimeAs100ns
inline unsigned long long QueryUnbiasedInterruptTimeAsMSec() WI_NOEXCEPT
{
return convert_100ns_to_msec(QueryUnbiasedInterruptTimeAs100ns());
}
#endif // _APISETREALTIME_
} // namespace filetime
#pragma endregion
#pragma region RECT helpers
/** Returns the width of a rectangle (its `right` minus `left`).
@tparam rect_type A rectangle type with `left` and `right` members (e.g. `RECT`).
@param rect The rectangle to measure.
@return The width, computed as `rect.right - rect.left`. */
template <typename rect_type>
constexpr auto rect_width(rect_type const& rect)
{
return rect.right - rect.left;
}
/** Returns the height of a rectangle (its `bottom` minus `top`).
@tparam rect_type A rectangle type with `top` and `bottom` members (e.g. `RECT`).
@param rect The rectangle to measure.
@return The height, computed as `rect.bottom - rect.top`. */
template <typename rect_type>
constexpr auto rect_height(rect_type const& rect)
{
return rect.bottom - rect.top;
}
/** Returns whether a rectangle is empty (encloses no area).
@tparam rect_type A rectangle type with `left`, `top`, `right`, and `bottom` members (e.g. `RECT`).
@param rect The rectangle to test.
@return `true` if the rectangle is empty (`left >= right` or `top >= bottom`), `false` otherwise. */
template <typename rect_type>
constexpr auto rect_is_empty(rect_type const& rect)
{
return (rect.left >= rect.right) || (rect.top >= rect.bottom);
}
/** Returns whether a point lies within a rectangle, treating the rectangle as half-open.
The `left` and `top` edges are inclusive while the `right` and `bottom` edges are exclusive.
@tparam rect_type A rectangle type with `left`, `top`, `right`, and `bottom` members (e.g. `RECT`).
@tparam point_type A point type with `x` and `y` members (e.g. `POINT`).
@param rect The rectangle to test against.
@param point The point to test.
@return `true` if `point` is inside `rect`, `false` otherwise. */
template <typename rect_type, typename point_type>
constexpr auto rect_contains_point(rect_type const& rect, point_type const& point)
{
return (point.x >= rect.left) && (point.x < rect.right) && (point.y >= rect.top) && (point.y < rect.bottom);
}
/** Builds a rectangle from an origin and a size.
@tparam rect_type A rectangle type with `left`, `top`, `right`, and `bottom` members (e.g. `RECT`).
@tparam length_type The integral type of the coordinate and size values.
@param x The left coordinate of the rectangle.
@param y The top coordinate of the rectangle.
@param width The width of the rectangle; `right` is set to `x + width`.
@param height The height of the rectangle; `bottom` is set to `y + height`.
@return A `rect_type` with the given origin and size. */
template <typename rect_type, typename length_type>
constexpr rect_type rect_from_size(length_type x, length_type y, length_type width, length_type height)
{
rect_type rect;
rect.left = x;
rect.top = y;
rect.right = x + width;
rect.bottom = y + height;
return rect;
}
#pragma endregion
/** Adapts a Win32 API that fills a fixed-size, caller-provided buffer into one that returns an allocated string.
Many Win32 APIs write into a fixed-size buffer and report how much space is required. This helper first tries a stack buffer of
`stackBufferLength` characters and, if that is too small, allocates a buffer of the required size, retrying if the required size
changes between calls. Supports any `string_type` understood by the internal `string_maker` (e.g. `wil::unique_cotaskmem_string`
or `std::wstring`).
~~~
// Wrap a fixed-size Win32 API (here ::GetSystemDirectoryW) into one that returns an allocated string.
wil::unique_cotaskmem_string dir;
RETURN_IF_FAILED(wil::AdaptFixedSizeToAllocatedResult(dir,
[](PWSTR value, size_t valueLength, size_t* valueLengthNeededWithNul) -> HRESULT
{
*valueLengthNeededWithNul = ::GetSystemDirectoryW(value, static_cast<DWORD>(valueLength));
RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0);
if (*valueLengthNeededWithNul < valueLength)
{
(*valueLengthNeededWithNul)++; // it fit; account for the null
}
return S_OK;
}));
~~~
@tparam string_type The string type to produce the result in.
@tparam stackBufferLength The size, in characters, of the initial stack buffer; tune it to typical result sizes.
@param result Receives the resulting string on success.
@param callback Invoked to fill the buffer. It is passed the buffer, the buffer length in characters, and an out pointer that it
must set to the number of characters needed including the null terminator. It returns an `HRESULT`, and any failure is
propagated to the caller.
@return `S_OK` on success, or a failure `HRESULT` from `callback` or from allocation. */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT AdaptFixedSizeToAllocatedResult(string_type& result, const wistd::function<HRESULT(PWSTR, size_t, size_t*)>& callback) WI_NOEXCEPT
{
details::string_maker<string_type> maker;
wchar_t value[stackBufferLength]{};
size_t valueLengthNeededWithNull{}; // callback returns the number of characters needed including the null terminator.
RETURN_IF_FAILED_EXPECTED(callback(value, ARRAYSIZE(value), &valueLengthNeededWithNull));
WI_ASSERT(valueLengthNeededWithNull > 0);
if (valueLengthNeededWithNull <= ARRAYSIZE(value))
{
// Success case as described above, make() adds the space for the null.
RETURN_IF_FAILED(maker.make(value, valueLengthNeededWithNull - 1));
}
else
{
// Did not fit in the stack allocated buffer, need to do 2 phase construction.
// May need to loop more than once if external conditions cause the value to change.
size_t bufferLength;
do
{
bufferLength = valueLengthNeededWithNull;
// bufferLength includes the null so subtract that as make() will add space for it.
RETURN_IF_FAILED(maker.make(nullptr, bufferLength - 1));
RETURN_IF_FAILED_EXPECTED(callback(maker.buffer(), bufferLength, &valueLengthNeededWithNull));
WI_ASSERT(valueLengthNeededWithNull > 0);
// If the value shrunk, then adjust the string to trim off the excess buffer.
if (valueLengthNeededWithNull < bufferLength)
{
RETURN_IF_FAILED(maker.trim_at_existing_null(valueLengthNeededWithNull - 1));
}
} while (valueLengthNeededWithNull > bufferLength);
}
result = maker.release();
return S_OK;
}
/** Expands the '%' quoted environment variables in 'input' using ExpandEnvironmentStringsW(); */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT ExpandEnvironmentStringsW(_In_ PCWSTR input, string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, stackBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
*valueLengthNeededWithNul = ::ExpandEnvironmentStringsW(input, value, static_cast<DWORD>(valueLength));
RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0);
return S_OK;
});
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES)
/** Searches for a specified file in a specified path using SearchPathW(). */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT SearchPathW(_In_opt_ PCWSTR path, _In_ PCWSTR fileName, _In_opt_ PCWSTR extension, string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, stackBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
*valueLengthNeededWithNul = ::SearchPathW(path, fileName, extension, static_cast<DWORD>(valueLength), value, nullptr);
if (*valueLengthNeededWithNul == 0)
{
// ERROR_FILE_NOT_FOUND is an expected return value for SearchPathW
const HRESULT searchResult = HRESULT_FROM_WIN32(::GetLastError());
RETURN_HR_IF_EXPECTED(searchResult, searchResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
RETURN_IF_FAILED(searchResult);
}
// AdaptFixedSizeToAllocatedResult expects that the length will always include the NUL.
// If the result is copied to the buffer, SearchPathW returns the length of copied string, WITHOUT the NUL.
// If the buffer is too small to hold the result, SearchPathW returns the length of the required buffer WITH the nul.
if (*valueLengthNeededWithNul < valueLength)
{
(*valueLengthNeededWithNul)++; // It fit, account for the null.
}
return S_OK;
});
}
/** Retrieves the full path of the executable image for the specified process, using `QueryFullProcessImageNameW`.
@tparam string_type The string type to produce the result in.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@param processHandle A handle to the process, opened with `PROCESS_QUERY_INFORMATION` or `PROCESS_QUERY_LIMITED_INFORMATION`
access.
@param flags Passed through to `QueryFullProcessImageNameW`; `0` for the Win32 path form or `PROCESS_NAME_NATIVE` for the native
path form.
@param result Receives the image path on success.
@return `S_OK` on success, or a failure `HRESULT`. */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT QueryFullProcessImageNameW(HANDLE processHandle, _In_ DWORD flags, string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, stackBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
DWORD lengthToUse = static_cast<DWORD>(valueLength);
BOOL const success = ::QueryFullProcessImageNameW(processHandle, flags, value, &lengthToUse);
RETURN_LAST_ERROR_IF((success == FALSE) && (::GetLastError() != ERROR_INSUFFICIENT_BUFFER));
// On success, return the amount used; on failure, try doubling
*valueLengthNeededWithNul = success ? (static_cast<size_t>(lengthToUse) + 1) : (static_cast<size_t>(lengthToUse) * 2);
return S_OK;
});
}
/** Expands environment strings and checks path existence with SearchPathW */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT ExpandEnvAndSearchPath(_In_ PCWSTR input, string_type& result) WI_NOEXCEPT
{
wil::unique_cotaskmem_string expandedName;
RETURN_IF_FAILED((wil::ExpandEnvironmentStringsW<string_type, stackBufferLength>(input, expandedName)));
// ERROR_FILE_NOT_FOUND is an expected return value for SearchPathW
const HRESULT searchResult = (wil::SearchPathW<string_type, stackBufferLength>(nullptr, expandedName.get(), nullptr, result));
RETURN_HR_IF_EXPECTED(searchResult, searchResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND));
RETURN_IF_FAILED(searchResult);
return S_OK;
}
#endif
/** Looks up the environment variable 'key' and fails if it is not found. */
template <typename string_type, size_t initialBufferLength = 128>
inline HRESULT GetEnvironmentVariableW(_In_ PCWSTR key, string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, initialBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
// If the function succeeds, the return value is the number of characters stored in the buffer
// pointed to by lpBuffer, not including the terminating null character.
//
// If lpBuffer is not large enough to hold the data, the return value is the buffer size, in
// characters, required to hold the string and its terminating null character and the contents of
// lpBuffer are undefined.
//
// If the function fails, the return value is zero. If the specified environment variable was not
// found in the environment block, GetLastError returns ERROR_ENVVAR_NOT_FOUND.
::SetLastError(ERROR_SUCCESS);
*valueLengthNeededWithNul = ::GetEnvironmentVariableW(key, value, static_cast<DWORD>(valueLength));
RETURN_LAST_ERROR_IF_EXPECTED((*valueLengthNeededWithNul == 0) && (::GetLastError() != ERROR_SUCCESS));
if (*valueLengthNeededWithNul < valueLength)
{
(*valueLengthNeededWithNul)++; // It fit, account for the null.
}
return S_OK;
});
}
/** Looks up the environment variable 'key' and returns null if it is not found. */
template <typename string_type, size_t initialBufferLength = 128>
HRESULT TryGetEnvironmentVariableW(_In_ PCWSTR key, string_type& result) WI_NOEXCEPT
{
const auto hr = wil::GetEnvironmentVariableW<string_type, initialBufferLength>(key, result);
RETURN_HR_IF(hr, FAILED(hr) && (hr != HRESULT_FROM_WIN32(ERROR_ENVVAR_NOT_FOUND)));
return S_OK;
}
/** Retrieves the fully qualified path for the file containing the specified module loaded by a given process.
Note GetModuleFileNameExW is a macro. */
template <typename string_type, size_t initialBufferLength = 128>
HRESULT GetModuleFileNameExW(_In_opt_ HANDLE process, _In_opt_ HMODULE module, string_type& path) WI_NOEXCEPT
{
auto adapter = [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
DWORD copiedCount{};
size_t valueUsedWithNul{};
bool copyFailed{};
bool copySucceededWithNoTruncation{};
if (process != nullptr)
{
// GetModuleFileNameExW truncates and provides no error or other indication it has done so.
// The only way to be sure it didn't truncate is if it didn't need the whole buffer. The
// count copied to the buffer includes the nul-character as well.
copiedCount = ::GetModuleFileNameExW(process, module, value, static_cast<DWORD>(valueLength));
valueUsedWithNul = static_cast<size_t>(copiedCount) + 1;
copyFailed = (0 == copiedCount);
copySucceededWithNoTruncation = !copyFailed && (copiedCount < valueLength - 1);
}
else
{
// In cases of insufficient buffer, GetModuleFileNameW will return a value equal to lengthWithNull
// and set the last error to ERROR_INSUFFICIENT_BUFFER. The count returned does not include
// the nul-character
copiedCount = ::GetModuleFileNameW(module, value, static_cast<DWORD>(valueLength));
valueUsedWithNul = static_cast<size_t>(copiedCount) + 1;
copyFailed = (0 == copiedCount);
copySucceededWithNoTruncation = !copyFailed && (copiedCount < valueLength);
}
RETURN_LAST_ERROR_IF(copyFailed);
// When the copy truncated, request another try with more space.
*valueLengthNeededWithNul = copySucceededWithNoTruncation ? valueUsedWithNul : (valueLength * 2);
return S_OK;
};
return wil::AdaptFixedSizeToAllocatedResult<string_type, initialBufferLength>(path, wistd::move(adapter));
}
/** Retrieves the fully qualified path for the file that contains the specified module.
The module must have been loaded by the current process. The path returned will use the same format that was specified when the
module was loaded. Therefore, the path can be a long or short file name, and can have the prefix '\\?\'. */
template <typename string_type, size_t initialBufferLength = 128>
HRESULT GetModuleFileNameW(HMODULE module, string_type& path) WI_NOEXCEPT
{
return wil::GetModuleFileNameExW<string_type, initialBufferLength>(nullptr, module, path);
}
/** Retrieves the path of the Windows system directory, using `GetSystemDirectoryW`.
@tparam string_type The string type to produce the result in.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@param result Receives the system directory path on success.
@return `S_OK` on success, or a failure `HRESULT`. */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT GetSystemDirectoryW(string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, stackBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
*valueLengthNeededWithNul = ::GetSystemDirectoryW(value, static_cast<DWORD>(valueLength));
RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0);
if (*valueLengthNeededWithNul < valueLength)
{
(*valueLengthNeededWithNul)++; // it fit, account for the null
}
return S_OK;
});
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES)
/** Retrieves the path of the Windows directory, using `GetWindowsDirectoryW`.
@tparam string_type The string type to produce the result in.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@param result Receives the Windows directory path on success.
@return `S_OK` on success, or a failure `HRESULT`. */
template <typename string_type, size_t stackBufferLength = 256>
HRESULT GetWindowsDirectoryW(string_type& result) WI_NOEXCEPT
{
return wil::AdaptFixedSizeToAllocatedResult<string_type, stackBufferLength>(
result, [&](_Out_writes_(valueLength) PWSTR value, size_t valueLength, _Out_ size_t* valueLengthNeededWithNul) -> HRESULT {
*valueLengthNeededWithNul = ::GetWindowsDirectoryW(value, static_cast<DWORD>(valueLength));
RETURN_LAST_ERROR_IF(*valueLengthNeededWithNul == 0);
if (*valueLengthNeededWithNul < valueLength)
{
(*valueLengthNeededWithNul)++; // it fit, account for the null
}
return S_OK;
});
}
#endif
#ifdef WIL_ENABLE_EXCEPTIONS
/** Expands the '%' quoted environment variables in 'input' using ExpandEnvironmentStringsW(); */
template <typename string_type = wil::unique_cotaskmem_string, size_t stackBufferLength = 256>
string_type ExpandEnvironmentStringsW(_In_ PCWSTR input)
{
string_type result{};
THROW_IF_FAILED((wil::ExpandEnvironmentStringsW<string_type, stackBufferLength>(input, result)));
return result;
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES)
/** Searches for a specified file in a specified path using SearchPathW. */
template <typename string_type = wil::unique_cotaskmem_string, size_t stackBufferLength = 256>
string_type TrySearchPathW(_In_opt_ PCWSTR path, _In_ PCWSTR fileName, PCWSTR _In_opt_ extension)
{
string_type result{};
HRESULT searchHR = wil::SearchPathW<string_type, stackBufferLength>(path, fileName, extension, result);
THROW_HR_IF(searchHR, FAILED(searchHR) && (searchHR != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)));
return result;
}
#endif
/** Looks up the environment variable 'key' and fails if it is not found. */
template <typename string_type = wil::unique_cotaskmem_string, size_t initialBufferLength = 128>
string_type GetEnvironmentVariableW(_In_ PCWSTR key)
{
string_type result{};
THROW_IF_FAILED((wil::GetEnvironmentVariableW<string_type, initialBufferLength>(key, result)));
return result;
}
/** Looks up the environment variable 'key' and returns null if it is not found. */
template <typename string_type = wil::unique_cotaskmem_string, size_t initialBufferLength = 128>
string_type TryGetEnvironmentVariableW(_In_ PCWSTR key)
{
string_type result{};
THROW_IF_FAILED((wil::TryGetEnvironmentVariableW<string_type, initialBufferLength>(key, result)));
return result;
}
/** Retrieves the fully qualified path for the file that contains the specified module.
Throws on failure. The module must have been loaded by the current process.
@tparam string_type The string type to return; defaults to `wil::unique_cotaskmem_string`.
@tparam initialBufferLength The size, in characters, of the initial stack buffer.
@param module The module to query, or `nullptr` for the current process's executable.
@return The module's fully qualified path. */
template <typename string_type = wil::unique_cotaskmem_string, size_t initialBufferLength = 128>
string_type GetModuleFileNameW(HMODULE module = nullptr /* current process module */)
{
string_type result{};
THROW_IF_FAILED((wil::GetModuleFileNameW<string_type, initialBufferLength>(module, result)));
return result;
}
/** Retrieves the fully qualified path for the file containing the specified module loaded by a given process.
Throws on failure. Note `GetModuleFileNameExW` is a macro.
@tparam string_type The string type to return; defaults to `wil::unique_cotaskmem_string`.
@tparam initialBufferLength The size, in characters, of the initial stack buffer.
@param process The process that loaded the module, or `nullptr` to use the current process.
@param module The module to query, or `nullptr` for the process's executable.
@return The module's fully qualified path. */
template <typename string_type = wil::unique_cotaskmem_string, size_t initialBufferLength = 128>
string_type GetModuleFileNameExW(HANDLE process, HMODULE module)
{
string_type result{};
THROW_IF_FAILED((wil::GetModuleFileNameExW<string_type, initialBufferLength>(process, module, result)));
return result;
}
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES)
/** Retrieves the path of the Windows directory, using `GetWindowsDirectoryW`.
Throws on failure.
@tparam string_type The string type to return; defaults to `wil::unique_cotaskmem_string`.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@return The Windows directory path. */
template <typename string_type = wil::unique_cotaskmem_string, size_t stackBufferLength = 256>
string_type GetWindowsDirectoryW()
{
string_type result;
THROW_IF_FAILED((wil::GetWindowsDirectoryW<string_type, stackBufferLength>(result)));
return result;
}
#endif
/** Retrieves the path of the Windows system directory, using `GetSystemDirectoryW`.
Throws on failure.
@tparam string_type The string type to return; defaults to `wil::unique_cotaskmem_string`.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@return The system directory path. */
template <typename string_type = wil::unique_cotaskmem_string, size_t stackBufferLength = 256>
string_type GetSystemDirectoryW()
{
string_type result;
THROW_IF_FAILED((wil::GetSystemDirectoryW<string_type, stackBufferLength>(result)));
return result;
}
/** Retrieves the full path of the executable image for the specified process, using `QueryFullProcessImageNameW`.
Throws on failure.
@tparam string_type The string type to return; defaults to `wil::unique_cotaskmem_string`.
@tparam stackBufferLength The size, in characters, of the initial stack buffer.
@param processHandle A handle to the process; defaults to the current process.
@param flags Passed through to `QueryFullProcessImageNameW`; `0` for the Win32 path form or `PROCESS_NAME_NATIVE`.
@return The process image path. */
template <typename string_type = wil::unique_cotaskmem_string, size_t stackBufferLength = 256>
string_type QueryFullProcessImageNameW(HANDLE processHandle = GetCurrentProcess(), DWORD flags = 0)
{
string_type result{};
THROW_IF_FAILED((wil::QueryFullProcessImageNameW<string_type, stackBufferLength>(processHandle, flags, result)));
return result;
}
#endif // WIL_ENABLE_EXCEPTIONS
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
/// @cond
namespace details
{
// Lookup a DWORD value under HKLM\...\Image File Execution Options\<current process name>
inline HRESULT GetCurrentProcessExecutionOptionNoThrow(PCWSTR valueName, DWORD defaultValue, DWORD* result)
{
*result = defaultValue;
wil::unique_cotaskmem_string filePath;
RETURN_IF_FAILED(wil::GetModuleFileNameW<wil::unique_cotaskmem_string>(nullptr, filePath));
if (auto lastSlash = wcsrchr(filePath.get(), L'\\'))
{
const auto fileName = lastSlash + 1;
wil::unique_cotaskmem_string keyPath;
RETURN_IF_FAILED(wil::str_concat_nothrow<wil::unique_cotaskmem_string>(
keyPath, LR"(SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\)", fileName));
DWORD value{};
DWORD sizeofValue = sizeof(value);
if (::RegGetValueW(
HKEY_LOCAL_MACHINE,
keyPath.get(),
valueName,
#ifdef RRF_SUBKEY_WOW6464KEY
RRF_RT_REG_DWORD | RRF_SUBKEY_WOW6464KEY,
#else
RRF_RT_REG_DWORD,
#endif
nullptr,
&value,
&sizeofValue) == ERROR_SUCCESS)
{
*result = value;
}
}
return S_OK;
}
} // namespace details
/// @endcond
#ifdef WIL_ENABLE_EXCEPTIONS
/** Reads a DWORD "Image File Execution Options" value for the current process.
Throws on failure. Looks up `valueName` under `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution
Options\<exe>`.
@param valueName The name of the `REG_DWORD` value to read.
@param defaultValue The value to return when the value is not present.
@return The configured value, or `defaultValue` if it is not set. */
inline DWORD GetCurrentProcessExecutionOption(PCWSTR valueName, DWORD defaultValue = 0)
{
DWORD result{};
THROW_IF_FAILED(details::GetCurrentProcessExecutionOptionNoThrow(valueName, defaultValue, &result));
return result;
}
#endif // WIL_ENABLE_EXCEPTIONS
/** Reads a DWORD "Image File Execution Options" value for the current process, returning `defaultValue` on any failure (including
when the value is not set).
@param valueName The name of the `REG_DWORD` value to read.
@param defaultValue The value to return on failure or when the value is not present.
@return The configured value, or `defaultValue`. */
inline DWORD GetCurrentProcessExecutionOptionNoThrow(PCWSTR valueName, DWORD defaultValue = 0)
{
DWORD result{};
if (FAILED(details::GetCurrentProcessExecutionOptionNoThrow(valueName, defaultValue, &result)))
{
return defaultValue;
}
return result;
}
/** Reads a DWORD "Image File Execution Options" value for the current process, fail-fasting on failure.
@param valueName The name of the `REG_DWORD` value to read.
@param defaultValue The value to return when the value is not present.
@return The configured value, or `defaultValue` if it is not set. */
inline DWORD GetCurrentProcessExecutionOptionFailFast(PCWSTR valueName, DWORD defaultValue = 0)
{
DWORD result{};
FAIL_FAST_IF_FAILED(details::GetCurrentProcessExecutionOptionNoThrow(valueName, defaultValue, &result));
return result;
}
#ifndef DebugBreak // Some code defines 'DebugBreak' to garbage to force build breaks in release builds
// Waits for a debugger to attach to the current process based on registry configuration.
//
// Example:
// HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\explorer.exe
// WaitForDebuggerPresent=1
//
// REG_DWORD value of
// missing or 0 -> don't break
// 1 -> wait for the debugger, continue execution once it is attached
// 2 -> wait for the debugger, break here once attached.
/// @cond
namespace details
{
template <typename error_policy>
inline void WaitForDebuggerPresent(bool checkRegistryConfig)
{
for (;;)
{
DWORD configValue{1};
if (checkRegistryConfig)
{
// err_returncode_policy will continue running after this line on failure. The default value of zero
// will apply in that case so we will still behave reasonably.
error_policy::HResult(details::GetCurrentProcessExecutionOptionNoThrow(L"WaitForDebuggerPresent", 0, &configValue));
}
if (configValue == 0)
{
return; // not configured, don't wait
}
if (IsDebuggerPresent())
{
if (configValue == 2)
{
DebugBreak(); // debugger attached, SHIFT+F11 to return to the caller
}
return; // debugger now attached, continue executing
}
Sleep(500);
}
}
} // namespace details
/// @endcond
#ifdef WIL_ENABLE_EXCEPTIONS
/** Waits for a debugger to attach to the current process, based on registry configuration.
Throws on failure. When `checkRegistryConfig` is `true`, the `WaitForDebuggerPresent` `REG_DWORD` value under this process's Image
File Execution Options key controls the behavior: missing or `0` returns immediately, `1` waits and then continues, and `2` waits
and then breaks into the debugger. When `false`, it unconditionally waits for a debugger to attach.
@param checkRegistryConfig `true` to honor the registry configuration, `false` to always wait. */
inline void WaitForDebuggerPresent(bool checkRegistryConfig = true)
{
details::WaitForDebuggerPresent<err_exception_policy>(checkRegistryConfig);
}
#endif // WIL_ENABLE_EXCEPTIONS
/** Like `WaitForDebuggerPresent`, but never throws (uses the error-code policy internally).
@param checkRegistryConfig `true` to honor the registry configuration, `false` to always wait. */
inline void WaitForDebuggerPresentNoThrow(bool checkRegistryConfig = true)
{
details::WaitForDebuggerPresent<err_returncode_policy>(checkRegistryConfig);
}
/** Like `WaitForDebuggerPresent`, but fail-fasts instead of throwing on failure.
@param checkRegistryConfig `true` to honor the registry configuration, `false` to always wait. */
inline void WaitForDebuggerPresentFailFast(bool checkRegistryConfig = true)
{
details::WaitForDebuggerPresent<err_failfast_policy>(checkRegistryConfig);
}
#endif // DebugBreak
#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
/** Retrieve the HINSTANCE for the current DLL or EXE using this symbol that the linker provides for every module.
This avoids the need for a global HINSTANCE variable and provides access to this value for static libraries. */
inline HINSTANCE GetModuleInstanceHandle() WI_NOEXCEPT
{
return reinterpret_cast<HINSTANCE>(&__ImageBase);
}
// GetModuleHandleExW was added to the app partition in version 22000 of the SDK
#if defined(NTDDI_WIN10_CO) ? WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES) \
: WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES)
/** Keeps the current module loaded for the lifetime of a thread that may outlive the code that created it.
Call this at the very start of a thread procedure when the thread can outlive the object or API call that created it (for
example a thread started from a DLL that may be unloaded): without it, COM or the API caller can unload the DLL while the thread
is still running, resulting in a crash. It must be the first object created in the thread proc so that it is destroyed last; its
destructor calls `FreeLibraryAndExitThread`, which exits the thread and would otherwise skip the destructors of any objects
created before it.
~~~
DWORD WINAPI MyThreadProc(void*)
{
// Must be the first object created in the thread proc.
auto moduleRef = wil::get_module_reference_for_thread();
DoWorkThatMayOutliveTheCaller();
return 0; // moduleRef's destructor releases the module reference and exits the thread via FreeLibraryAndExitThread.
}
// The DLL that starts the thread may be unloaded before MyThreadProc finishes; the reference above keeps it loaded.
wil::unique_handle thread{::CreateThread(nullptr, 0, MyThreadProc, nullptr, 0, nullptr)};
~~~
@return A `wil::scope_exit` object that, when destroyed, calls `FreeLibraryAndExitThread` to release the module reference and
exit the thread. */
[[nodiscard]] inline auto get_module_reference_for_thread() noexcept
{
HMODULE thisModule{};
FAIL_FAST_IF(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, L"", &thisModule));
return wil::scope_exit([thisModule] {
FreeLibraryAndExitThread(thisModule, 0);
});
}
#endif
/// @cond
namespace details
{