Debian Codegraph @

source/unix/odesrc/ousrc/threadlocalstorage.cpp

raw
1 /*************************************************************************
2 * *
3 * ODER's Utilities Library. Copyright (C) 2008 Oleh Derevenko. *
4 * All rights reserved. e-mail: [email protected] (change all "a" to "e") *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of EITHER: *
8 * (1) The GNU Lesser General Public License as published by the Free *
9 * Software Foundation; either version 3 of the License, or (at *
10 * your option) any later version. The text of the GNU Lesser *
11 * General Public License is included with this library in the *
12 * file LICENSE-LESSER.TXT. Since LGPL is the extension of GPL *
13 * the text of GNU General Public License is also provided for *
14 * your information in file LICENSE.TXT. *
15 * (2) The BSD-style license that is included with this library in *
16 * the file LICENSE-BSD.TXT. *
17 * (3) The zlib/libpng license that is included with this library in *
18 * the file LICENSE-ZLIB.TXT *
19 * *
20 * This library is distributed WITHOUT ANY WARRANTY, including implied *
21 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
22 * See the files LICENSE.TXT and LICENSE-LESSER.TXT or LICENSE-BSD.TXT *
23 * or LICENSE-ZLIB.TXT for more details. *
24 * *
25 *************************************************************************/
26
27 #include <ou/features.h>
28
29
30 #if _OU_FEATURE_SET >= _OU_FEATURE_SET_TLS
31
32 #include <ou/threadlocalstorage.h>
33 #include <ou/atomicflags.h>
34 #include <ou/atomic.h>
35 #include <ou/simpleflags.h>
36 #include <ou/malloc.h>
37 #include <ou/templates.h>
38 #include <ou/inttypes.h>
39
40 #include <string.h>
41 #include <errno.h>
42 #include <new>
43
44 #if !defined(EOK)
45
46 #define EOK 0
47
48
49 #endif
50
51
52 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
53
54 #include <windows.h>
55
56
57 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
58
59
60 BEGIN_NAMESPACE_OU();
61
62
63 class CTLSStorageInstance;
64
65 enum ESTORAGEINSTANCEKIND
66 {
67 SIK__MIN,
68
69 SIK_AUTOCLEANUP = SIK__MIN,
70 SIK_MANUALCLEANUP,
71
72 SIK__MAX,
73 };
74
75
76 static unsigned int g_uiThreadLocalStorageInitializationCount = 0;
77 static CTLSStorageInstance *g_apsiStorageGlobalInstances[SIK__MAX] = { NULL };
78 static HTLSKEYVALUE g_ahkvStorageGlobalKeyValues[SIK__MAX] = { NULL };
79
80
81 static inline size_t DecodeInstanceKindFromKeySelector(const HTLSKEYSELECTOR &hksKeySelector)
82 {
83 return (HTLSKEYSELECTOR::value_type)hksKeySelector - g_ahkvStorageGlobalKeyValues;
84 }
85
86 static inline HTLSKEYSELECTOR EncodeKeySelectorFromStorageKind(ESTORAGEINSTANCEKIND ikInstanceKind)
87 {
88 return g_ahkvStorageGlobalKeyValues + ikInstanceKind;
89 }
90
91
92 #if !defined(_OU_TLS_ARRAY_ELEMENT_COUNT)
93
94 // Default TLS array element count
95 #define _OU_TLS_ARRAY_ELEMENT_COUNT 8
96
97
98 #endif // #if !defined(_OU_TLS_ARRAY_ELEMENT_COUNT)
99
100
101 // Few bits must be reserved for additional purposes (currently 1)
102 #if (_OU_TLS_ARRAY_ELEMENT_COUNT < 1) || (_OU_TLS_ARRAY_ELEMENT_COUNT > 30)
103
104 #error Please specify TLS array element count in range from 1 to 30
105
106
107 #endif // #if (_OU_TLS_ARRAY_ELEMENT_COUNT < 1) || (_OU_TLS_ARRAY_ELEMENT_COUNT > 30)
108
109
110 enum
111 {
112 TLS_ARRAY_ELEMENT__MAX = _OU_TLS_ARRAY_ELEMENT_COUNT, // 16 threads with 8 values each using 4 + 4 bytes is ~1 kb of memory
113 };
114
115
116 struct CTLSStorageArray
117 {
118 private:
119 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
120
121 typedef HANDLE CClientHandleArray[TLS_ARRAY_ELEMENT__MAX];
122 typedef unsigned int CHandleTranslationMap[TLS_ARRAY_ELEMENT__MAX];
123
124
125 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
126
127 public:
128 static inline size_t GetHeaderSize() { return OU_ALIGNED_SIZE(sizeof(CTLSStorageArray), CTLSStorageBlock::TSB_LARGEST_ALIGNMENT); }
129
130 public:
131 static CTLSStorageArray *AllocateInstance(tlsindextype iValueCount);
132 void FreeInstance(tlsindextype iValueCount);
133
134 protected:
135 inline CTLSStorageArray(); // Use AllocateInstance()
136 inline ~CTLSStorageArray(); // Use FreeInstance()
137
138 public:
139 void FreeStorageBlockOnThreadExit(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount);
140
141 public:
142 bool FindFreeStorageBlock(CTLSStorageBlock *&psbOutFreeStorageBlock,
143 tlsindextype iValueCount, bool bIsManualCleanup);
144
145 private:
146 bool FindFreeStorageBlockIndex(unsigned int &nOutFreeBlockIndex, tlsindextype iValueCount, bool bIsManualCleanup);
147 bool FindFreeStorageBlockIndexWithPossibilityVerified(unsigned int &nOutFreeBlockIndex, bool bIsManualCleanup);
148 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
149
150 bool FindAbandonedStorageBlockIndex(unsigned int &nOutFreeBlockIndex, tlsindextype iValueCount);
151 unsigned int TranslateClientHandles(CClientHandleArray haTranslatedHandlesStorage, CHandleTranslationMap tmTranslationMapStorage,
152 const HANDLE *&ph_OutTranslatedHandles, const unsigned int *&puiOutTranslationMap) const;
153
154 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
155
156 private:
157 void FreeStorageAllBlocks(tlsindextype iValueCount);
158 void ReinitializeStorageSingleBlock(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount);
159 static void FinalizeStorageSingleBlock(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount);
160
161 void AssignAllBlocksHostArray(tlsindextype iValueCount);
162 inline void AssignSingleBlockHostArray(CTLSStorageBlock *psbStorageBlock);
163
164 private:
165 inline CTLSStorageBlock *GetStorageBlockPointer(unsigned int nBlockIndex, tlsindextype iValueCount) const;
166 inline unsigned int GetStorageBlockIndex(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount) const;
167 inline static void ZeroStorageBlockMemory(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount);
168
169 private:
170 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
171
172 void AllocateBlockThreadHandle(unsigned int nBlockIndex);
173 void FreeStorageThreadHandle(unsigned int nBlockIndex);
174
175 void AssignAllBlocksInvalidThreads();
176 bool CheckIfAllBlocksHaveInvalidThreads();
177
178 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
179
180 private:
181 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
182
183 inline void SetBlockThreadHandle(unsigned int nBlockIndex, HANDLE hValue)
184 {
185 m_haBlockThreads[nBlockIndex] = hValue;
186 }
187
188 inline HANDLE GetBlockThreadHandle(unsigned int nBlockIndex) const
189 {
190 return m_haBlockThreads[nBlockIndex];
191 }
192
193 inline const HANDLE *GetBlockThreadHandlesStorage() const
194 {
195 return m_haBlockThreads;
196 }
197
198 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
199
200 public:
201 inline void SetNextArray(CTLSStorageArray *psaInstance)
202 {
203 m_psaNextArray = (atomicptr)psaInstance;
204 }
205
206 inline CTLSStorageArray *GetNextArray() const
207 {
208 return (CTLSStorageArray *)m_psaNextArray;
209 }
210
211 private:
212 enum
213 {
214 FL_OCCUPANCY_FLAGS__START = 0x00000001,
215 FL_OCCUPANCY_FLAGS__END = FL_OCCUPANCY_FLAGS__START << TLS_ARRAY_ELEMENT__MAX,
216
217 FL_ARRAY_LOCKED = FL_OCCUPANCY_FLAGS__END,
218 };
219
220 inline bool GetAreAllBlocksOccupied() const
221 {
222 return m_afOccupancyFlags.EnumAllQueryEnumeratedFlags(FL_OCCUPANCY_FLAGS__START, TLS_ARRAY_ELEMENT__MAX) == OU_FLAGS_ENUMFLAGS_MASK(COccupancyFlagsType::value_type, FL_OCCUPANCY_FLAGS__START, TLS_ARRAY_ELEMENT__MAX);
223 }
224
225 inline bool GetIsAnyBlockOccupied() const
226 {
227 return m_afOccupancyFlags.EnumAnyGetEnumeratedFlagValue(FL_OCCUPANCY_FLAGS__START, TLS_ARRAY_ELEMENT__MAX);
228 }
229
230 inline bool SetBlockOccupiedFlag(unsigned int nBlockIndex)
231 {
232 return m_afOccupancyFlags.EnumModifyEnumeratedFlagValue(FL_OCCUPANCY_FLAGS__START, nBlockIndex, TLS_ARRAY_ELEMENT__MAX, true);
233 }
234
235 inline void ResetBlockOccupiedFlag(unsigned int nBlockIndex)
236 {
237 m_afOccupancyFlags.EnumDropEnumeratedFlagValue(FL_OCCUPANCY_FLAGS__START, nBlockIndex, TLS_ARRAY_ELEMENT__MAX);
238 }
239
240 inline bool GetBlockOccupiedFlag(unsigned int nBlockIndex) const
241 {
242 return m_afOccupancyFlags.EnumGetEnumeratedFlagValue(FL_OCCUPANCY_FLAGS__START, nBlockIndex, TLS_ARRAY_ELEMENT__MAX);
243 }
244
245 inline bool SetArrayLockedFlag()
246 {
247 return m_afOccupancyFlags.ModifySingleFlagValue(FL_ARRAY_LOCKED, true);
248 }
249
250 inline void ResetArrayLockedFlag()
251 {
252 m_afOccupancyFlags.DropFlagsMaskValue(FL_ARRAY_LOCKED);
253 }
254
255 private:
256 typedef CAtomicFlags COccupancyFlagsType;
257
258 volatile atomicptr m_psaNextArray; // CTLSStorageArray *
259 COccupancyFlagsType m_afOccupancyFlags;
260
261 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
262
263 CClientHandleArray m_haBlockThreads;
264
265
266 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
267
268 // CTLSStorageBlock m_asbStorageBlocks[];
269 };
270
271 class CTLSStorageInstance
272 {
273 public:
274 static CTLSStorageInstance *AllocateInstance(tlsindextype iValueCount, unsigned int uiInitializationFlags);
275 void FreeInstance();
276
277 protected:
278 CTLSStorageInstance(tlsindextype iValueCount, unsigned int uiInitializationFlags);
279 ~CTLSStorageInstance();
280
281 public:
282 bool Init(ESTORAGEINSTANCEKIND ikInstanceKind);
283
284 private:
285 void Finit();
286
287 public:
288 inline const HTLSKEYVALUE &RetrieveStorageKey() const { return GetStorageKey(); }
289 inline tlsindextype RetrieveValueCount() const { return GetValueCount(); }
290 inline unsigned int RetrieveInitializationFlags() const { return GetInitializationFlags(); }
291
292 inline bool GetIsThreadManualCleanup() const { return GetThreadManualCleanupFlag(); }
293
294 public:
295 void FreeStorageBlockOnThreadExit(CTLSStorageBlock *psbStorageBlock);
296
297 public:
298 bool FindFreeStorageBlock(CTLSStorageBlock *&psbOutStorageBlock);
299
300 private:
301 bool FindFreeStorageBlockInArrayList(CTLSStorageBlock *&psbOutStorageBlock);
302 bool FindFreeStorageBlockInArrayListSegment(CTLSStorageBlock *&psbOutStorageBlock,
303 CTLSStorageArray *psaListSegmentBegin, CTLSStorageArray *psaListSegmentEnd);
304 bool FindFreeStorageBlockFromArray(CTLSStorageBlock *&psbOutStorageBlock,
305 CTLSStorageArray *psaArrayInstance);
306
307 void AddStorageArrayToArrayList(CTLSStorageArray *psaStorageArray);
308
309 private:
310 static bool AllocateStorageKey(HTLSKEYVALUE &hkvOutStorageKey, ESTORAGEINSTANCEKIND ikInstanceKind);
311 static void FreeStorageKey(const HTLSKEYVALUE &hkvStorageKey);
312
313 #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
314
315 static void FreeStorageBlock_Callback_Automatic(void *pv_DataValue);
316 static void FreeStorageBlock_Callback_Manual(void *pv_DataValue);
317
318
319 #endif // #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
320
321 void FreeStorageBlock(CTLSStorageBlock *psbStorageBlock);
322
323 CTLSStorageArray *AllocateStorageArray();
324 void FreeStorageArrayList(CTLSStorageArray *psaStorageArrayList);
325
326 private:
327 inline bool TrySettingStorageArrayList(CTLSStorageArray *psaInstance, CTLSStorageArray *psaCurrentList)
328 {
329 return AtomicCompareExchangePointer(&m_psaStorageList, (atomicptr)psaCurrentList, (atomicptr)psaInstance);
330 }
331
332 inline CTLSStorageArray *GetStorageArrayList() const
333 {
334 return (CTLSStorageArray *)m_psaStorageList;
335 }
336
337 inline void SetStorageKey(const HTLSKEYVALUE &hskValue) { m_hskStorageKey = hskValue; }
338 inline const HTLSKEYVALUE &GetStorageKey() const { return m_hskStorageKey; }
339
340 inline tlsindextype GetValueCount() const { return m_iValueCount; }
341
342 private:
343 enum
344 {
345 FL_STORAGE_KEY_VALID = 0x00000001,
346
347 FLM_INITIALIZATION_FLAGS_MASK = 0x0000FFFF,
348 FLS_INITIALIZATION_FLAGS_SHIFT = 16,
349
350 FL_INITIALIZATION_THREAD_MANUAL_CLEANUP = CTLSInitialization::SIF_MANUAL_CLEANUP_ON_THREAD_EXIT << FLS_INITIALIZATION_FLAGS_SHIFT,
351 };
352
353 inline void SetStorageKeyValidFlag() { m_sfInstanceFlags.SignalFlagsMaskValue(FL_STORAGE_KEY_VALID); }
354 inline void ResetStorageKeyValidFlag() { m_sfInstanceFlags.DropFlagsMaskValue(FL_STORAGE_KEY_VALID); }
355 inline bool GetStorageKeyValidFlag() const { return m_sfInstanceFlags.GetFlagsMaskValue(FL_STORAGE_KEY_VALID); }
356
357 inline void SetInitializationFlags(unsigned int uiValue) { m_sfInstanceFlags.StoreFlagsEnumeratedValue(FLM_INITIALIZATION_FLAGS_MASK, FLS_INITIALIZATION_FLAGS_SHIFT, uiValue); }
358 inline unsigned int GetInitializationFlags() const { return m_sfInstanceFlags.RetrieveFlagsEnumeratedValue(FLM_INITIALIZATION_FLAGS_MASK, FLS_INITIALIZATION_FLAGS_SHIFT); }
359
360 inline bool GetThreadManualCleanupFlag() const { return m_sfInstanceFlags.GetFlagsMaskValue(FL_INITIALIZATION_THREAD_MANUAL_CLEANUP); }
361
362 private:
363 volatile atomicptr m_psaStorageList; // CTLSStorageArray *
364 HTLSKEYVALUE m_hskStorageKey;
365 CSimpleFlags m_sfInstanceFlags;
366 tlsindextype m_iValueCount;
367 };
368
369
370 //////////////////////////////////////////////////////////////////////////
371 // CTLSStorageArray methods
372
373 CTLSStorageArray *CTLSStorageArray::AllocateInstance(tlsindextype iValueCount)
374 {
375 const size_t nHeaderSize = CTLSStorageArray::GetHeaderSize();
376 const size_t nBlockSize = CTLSStorageBlock::GetRequiredSize(iValueCount);
377 size_t nRequiredSize = nHeaderSize + nBlockSize * TLS_ARRAY_ELEMENT__MAX;
378
379 CTLSStorageArray *psaNewInstance = (CTLSStorageArray *)AllocateMemoryBlock(nRequiredSize);
380
381 if (psaNewInstance)
382 {
383 memset(psaNewInstance, 0, nRequiredSize);
384 new((CTLSStorageArray *)psaNewInstance) CTLSStorageArray();
385
386 psaNewInstance->AssignAllBlocksHostArray(iValueCount);
387 }
388
389 return psaNewInstance;
390 }
391
392 void CTLSStorageArray::FreeInstance(tlsindextype iValueCount)
393 {
394 if (GetIsAnyBlockOccupied())
395 {
396 FreeStorageAllBlocks(iValueCount);
397 }
398
399 this->CTLSStorageArray::~CTLSStorageArray();
400 FreeMemoryBlock((void *)this);
401 }
402
403 CTLSStorageArray::CTLSStorageArray()
404 {
405 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
406
407 AssignAllBlocksInvalidThreads();
408
409
410 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
411 }
412
413 CTLSStorageArray::~CTLSStorageArray()
414 {
415 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
416
417 OU_ASSERT(CheckIfAllBlocksHaveInvalidThreads());
418
419
420 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
421 }
422
423
424 void CTLSStorageArray::FreeStorageBlockOnThreadExit(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount)
425 {
426 ReinitializeStorageSingleBlock(psbStorageBlock, iValueCount);
427 // OU_ASSERT(GetBlockThreadHandle(nBlockIndex) == INVALID_HANDLE_VALUE) -- assertion further in the code
428
429 unsigned int nBlockIndex = GetStorageBlockIndex(psbStorageBlock, iValueCount);
430 OU_ASSERT(GetBlockOccupiedFlag(nBlockIndex));
431 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
432
433 OU_ASSERT(GetBlockThreadHandle(nBlockIndex) == INVALID_HANDLE_VALUE); // The method is not to be called if automatic cleanup is enabled
434
435
436 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
437
438 ResetBlockOccupiedFlag(nBlockIndex);
439 }
440
441
442 bool CTLSStorageArray::FindFreeStorageBlock(CTLSStorageBlock *&psbOutFreeStorageBlock,
443 tlsindextype iValueCount, bool bIsManualCleanup)
444 {
445 bool bResult = false;
446
447 unsigned int nFreeBlockIndex;
448
449 if (FindFreeStorageBlockIndex(nFreeBlockIndex, iValueCount, bIsManualCleanup))
450 {
451 CTLSStorageBlock *psbFreeStorageBlock = GetStorageBlockPointer(nFreeBlockIndex, iValueCount);
452
453 psbOutFreeStorageBlock = psbFreeStorageBlock;
454 bResult = true;
455 }
456
457 return bResult;
458 }
459
460
461 bool CTLSStorageArray::FindFreeStorageBlockIndex(unsigned int &nOutFreeBlockIndex,
462 tlsindextype iValueCount, bool bIsManualCleanup)
463 {
464 bool bResult = false;
465
466 if (!GetAreAllBlocksOccupied() && FindFreeStorageBlockIndexWithPossibilityVerified(nOutFreeBlockIndex, bIsManualCleanup))
467 {
468 bResult = true;
469 }
470 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
471
472 else if (!bIsManualCleanup)
473 {
474 // Execution gets here is all slots were already occupied or
475 // they become occupied during search (otherwise why
476 // FindFreeStorageBlockIndexWithPossibilityVerified call failed???).
477 // In Automatic cleanup mode a block can't become free by itself -
478 // it is just re-allocated for new thread and remains busy.
479 OU_ASSERT(GetAreAllBlocksOccupied());
480
481 // The locking is performed to avoid more than one threads checking
482 // for abandoned handles simultaneously.
483 // If locking fails, execution just proceeds to next array in the chain
484 if (SetArrayLockedFlag())
485 {
486 bResult = FindAbandonedStorageBlockIndex(nOutFreeBlockIndex, iValueCount);
487
488 ResetArrayLockedFlag();
489 }
490 }
491
492
493 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
494
495 return bResult;
496 }
497
498 bool CTLSStorageArray::FindFreeStorageBlockIndexWithPossibilityVerified(unsigned int &nOutFreeBlockIndex,
499 bool bIsManualCleanup)
500 {
501 unsigned int nBlockIndex = 0;
502
503 for (; nBlockIndex != TLS_ARRAY_ELEMENT__MAX; ++nBlockIndex)
504 {
505 if (SetBlockOccupiedFlag(nBlockIndex))
506 {
507 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
508
509 if (!bIsManualCleanup)
510 {
511 AllocateBlockThreadHandle(nBlockIndex);
512 }
513
514
515 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
516
517 nOutFreeBlockIndex = nBlockIndex;
518 break;
519 }
520 }
521
522 bool bResult = nBlockIndex != TLS_ARRAY_ELEMENT__MAX;
523 return bResult;
524 }
525
526
527 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
528
529 bool CTLSStorageArray::FindAbandonedStorageBlockIndex(unsigned int &nOutFreeBlockIndex,
530 tlsindextype iValueCount)
531 {
532 bool bResult = false;
533
534 do
535 {
536 CClientHandleArray haTranslatedHandlesStorage;
537 CHandleTranslationMap tmTranslationMapStorage;
538
539 const HANDLE *ph_TranslatedHandles;
540 const unsigned int *puiTranslationMap;
541
542 // Translate handles into array for the case if there are invalids
543 unsigned int nHandleCount = TranslateClientHandles(haTranslatedHandlesStorage, tmTranslationMapStorage,
544 ph_TranslatedHandles, puiTranslationMap);
545 OU_ASSERT(OU_IN_INT_RANGE(nHandleCount, 0, MAXIMUM_WAIT_OBJECTS + 1));
546
547 if (nHandleCount == 0)
548 {
549 break;
550 }
551
552 // Since allocating a new storage block is a relatively slow operation
553 // it is acceptable to enter kernel for checking for exited threads.
554 DWORD dwWaitResult = ::WaitForMultipleObjects(nHandleCount, ph_TranslatedHandles, FALSE, 0);
555
556 if (!OU_IN_INT_RANGE(dwWaitResult - WAIT_OBJECT_0, 0, nHandleCount))
557 {
558 // Wait should not normally fail. If it does it's in most cases an indication
559 // of invalid handle passed as parameter. However it may fail because of other
560 // reasons as well. If this assertion fails too often and you are sure all the
561 // handles are valid, it is safe to comment it.
562 OU_ASSERT(dwWaitResult != WAIT_FAILED);
563
564 break;
565 }
566
567 unsigned int nTranslatedBlockIndex = (unsigned int)(dwWaitResult - WAIT_OBJECT_0);
568 unsigned int nBlockIndex = !puiTranslationMap ? nTranslatedBlockIndex : puiTranslationMap[nTranslatedBlockIndex];
569
570 CTLSStorageBlock *psbStorageBlock = GetStorageBlockPointer(nBlockIndex, iValueCount);
571 ReinitializeStorageSingleBlock(psbStorageBlock, iValueCount);
572
573 // Close old handle and make a duplicate of current thread handle
574 FreeStorageThreadHandle(nBlockIndex);
575 AllocateBlockThreadHandle(nBlockIndex);
576
577 nOutFreeBlockIndex = nBlockIndex;
578 bResult = true;
579 }
580 while (false);
581
582 return bResult;
583 }
584
585 unsigned int CTLSStorageArray::TranslateClientHandles(CClientHandleArray haTranslatedHandlesStorage, CHandleTranslationMap tmTranslationMapStorage,
586 const HANDLE *&ph_OutTranslatedHandles, const unsigned int *&puiOutTranslationMap) const
587 {
588 ph_OutTranslatedHandles = haTranslatedHandlesStorage;
589 puiOutTranslationMap = tmTranslationMapStorage;
590
591 unsigned int nTargetStartIndex = 0;
592 unsigned int nSourceStartIndex = 0, nSourceCurrentIndex = 0;
593
594 while (true)
595 {
596 if (GetBlockThreadHandle(nSourceCurrentIndex) == INVALID_HANDLE_VALUE)
597 {
598 const HANDLE *ph_BlockThreadHandles = GetBlockThreadHandlesStorage();
599
600 unsigned int nTargetIncrement = nSourceCurrentIndex - nSourceStartIndex;
601
602 memcpy(&haTranslatedHandlesStorage[nTargetStartIndex], &ph_BlockThreadHandles[nSourceStartIndex], nTargetIncrement * sizeof(HANDLE));
603 for (; nTargetIncrement != 0; ++nTargetStartIndex, ++nSourceStartIndex, --nTargetIncrement) { tmTranslationMapStorage[nTargetStartIndex] = nSourceStartIndex; }
604
605 // Skip invalid handle (at this point nSourceStartIndex is equal to nSourceCurrentIndex)
606 ++nSourceStartIndex;
607 }
608
609 ++nSourceCurrentIndex;
610
611 if (nSourceCurrentIndex == TLS_ARRAY_ELEMENT__MAX)
612 {
613 // Start indice can be equal if and only if no invalid handles have been found
614 if (nSourceStartIndex != nTargetStartIndex)
615 {
616 const HANDLE *ph_BlockThreadHandles = GetBlockThreadHandlesStorage();
617
618 unsigned int nTargetIncrement = nSourceCurrentIndex - nSourceStartIndex;
619
620 memcpy(&haTranslatedHandlesStorage[nTargetStartIndex], &ph_BlockThreadHandles[nSourceStartIndex], nTargetIncrement * sizeof(HANDLE));
621 for (; nTargetIncrement != 0; ++nTargetStartIndex, ++nSourceStartIndex, --nTargetIncrement) { tmTranslationMapStorage[nTargetStartIndex] = nSourceStartIndex; }
622 }
623
624 break;
625 }
626 }
627
628 // If all the handles are valid...
629 if (nTargetStartIndex == 0)
630 {
631 // ...just return original handle array as no copying was performed
632 ph_OutTranslatedHandles = GetBlockThreadHandlesStorage();
633 puiOutTranslationMap = NULL;
634 }
635
636 return nTargetStartIndex;
637 }
638
639
640 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
641
642
643 void CTLSStorageArray::FreeStorageAllBlocks(tlsindextype iValueCount)
644 {
645 for (unsigned int nBlockIndex = 0; nBlockIndex != TLS_ARRAY_ELEMENT__MAX; ++nBlockIndex)
646 {
647 if (GetBlockOccupiedFlag(nBlockIndex))
648 {
649 CTLSStorageBlock *psbStorageBlock = GetStorageBlockPointer(nBlockIndex, iValueCount);
650
651 FinalizeStorageSingleBlock(psbStorageBlock, iValueCount);
652 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
653
654 FreeStorageThreadHandle(nBlockIndex);
655
656
657 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
658 }
659 else
660 {
661 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
662
663 OU_ASSERT(GetBlockThreadHandle(nBlockIndex) == INVALID_HANDLE_VALUE); // Where did the handle come from if block is not occupied?
664
665
666 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
667 }
668 }
669 }
670
671 void CTLSStorageArray::ReinitializeStorageSingleBlock(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount)
672 {
673 FinalizeStorageSingleBlock(psbStorageBlock, iValueCount);
674
675 ZeroStorageBlockMemory(psbStorageBlock, iValueCount);
676 AssignSingleBlockHostArray(psbStorageBlock);
677 }
678
679 void CTLSStorageArray::FinalizeStorageSingleBlock(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount)
680 {
681 for (tlsindextype iValueIndex = 0; iValueIndex != iValueCount; ++iValueIndex)
682 {
683 tlsvaluetype vValueData = psbStorageBlock->GetValueData(iValueIndex);
684
685 if (vValueData)
686 {
687 CTLSValueDestructor fnValueDestructor = psbStorageBlock->GetValueDestructor(iValueIndex);
688
689 if (fnValueDestructor)
690 {
691 fnValueDestructor(vValueData);
692 }
693 }
694 }
695 }
696
697
698 void CTLSStorageArray::AssignAllBlocksHostArray(tlsindextype iValueCount)
699 {
700 for (unsigned int nBlockIndex = 0; nBlockIndex != TLS_ARRAY_ELEMENT__MAX; ++nBlockIndex)
701 {
702 CTLSStorageBlock *psbStorageBlock = GetStorageBlockPointer(nBlockIndex, iValueCount);
703
704 AssignSingleBlockHostArray(psbStorageBlock);
705 }
706 }
707
708 void CTLSStorageArray::AssignSingleBlockHostArray(CTLSStorageBlock *psbStorageBlock)
709 {
710 psbStorageBlock->SetHostArray(this);
711 }
712
713
714 CTLSStorageBlock *CTLSStorageArray::GetStorageBlockPointer(unsigned int nBlockIndex, tlsindextype iValueCount) const
715 {
716 OU_ASSERT(OU_IN_INT_RANGE(nBlockIndex, 0, TLS_ARRAY_ELEMENT__MAX));
717
718 const size_t nHeaderSize = CTLSStorageArray::GetHeaderSize();
719 const size_t nBlockSize = CTLSStorageBlock::GetRequiredSize(iValueCount);
720 const size_t nBlockZeroOffset = CTLSStorageBlock::GetZeroOffset(iValueCount);
721
722 CTLSStorageBlock *psbStorageBlock = (CTLSStorageBlock *)(((int8ou *)this) + nHeaderSize + nBlockIndex * nBlockSize + nBlockZeroOffset);
723 return psbStorageBlock;
724 }
725
726 unsigned int CTLSStorageArray::GetStorageBlockIndex(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount) const
727 {
728 const size_t nHeaderSize = CTLSStorageArray::GetHeaderSize();
729 const size_t nBlockSize = CTLSStorageBlock::GetRequiredSize(iValueCount);
730 const size_t nBlockZeroOffset = CTLSStorageBlock::GetZeroOffset(iValueCount);
731
732 unsigned int uiBlockIndex = (unsigned int)((((int8ou *)psbStorageBlock) - nBlockZeroOffset - nHeaderSize - ((int8ou *)this)) / nBlockSize);
733 OU_ASSERT((((int8ou *)psbStorageBlock) - nBlockZeroOffset - nHeaderSize - ((int8ou *)this)) % nBlockSize == 0);
734 OU_ASSERT(OU_IN_INT_RANGE(uiBlockIndex, 0, TLS_ARRAY_ELEMENT__MAX));
735
736 return uiBlockIndex;
737 }
738
739 void CTLSStorageArray::ZeroStorageBlockMemory(CTLSStorageBlock *psbStorageBlock, tlsindextype iValueCount)
740 {
741 const size_t nBlockSize = CTLSStorageBlock::GetRequiredSize(iValueCount);
742 const size_t nBlockZeroOffset = CTLSStorageBlock::GetZeroOffset(iValueCount);
743
744 memset(((int8ou *)psbStorageBlock) - nBlockZeroOffset, 0, nBlockSize);
745 }
746
747
748 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
749
750 void CTLSStorageArray::AllocateBlockThreadHandle(unsigned int nBlockIndex)
751 {
752 OU_ASSERT(GetBlockThreadHandle(nBlockIndex) == INVALID_HANDLE_VALUE);
753
754 HANDLE hCurrentThreadDuplicate;
755
756 HANDLE hCurrentProcess = ::GetCurrentProcess();
757 HANDLE hCurrentThread = ::GetCurrentThread();
758 if (!::DuplicateHandle(hCurrentProcess, hCurrentThread, hCurrentProcess, &hCurrentThreadDuplicate, SYNCHRONIZE, FALSE, 0))
759 {
760 // Handle duplication should not normally fail.
761 // Thread and process pseudo-handles have full access allowed.
762 // The duplication may only fail in case of kernel internal problems
763 // (like lack of the resources or resource limit hits).
764 // Well, in this case thread data will remain in memory until
765 // CTLSInitialization::FinalizeTLSAPI() is called.
766 hCurrentThreadDuplicate = INVALID_HANDLE_VALUE;
767 }
768
769 SetBlockThreadHandle(nBlockIndex, hCurrentThreadDuplicate);
770 }
771
772 void CTLSStorageArray::FreeStorageThreadHandle(unsigned int nBlockIndex)
773 {
774 HANDLE hExistingThreadHandle = GetBlockThreadHandle(nBlockIndex);
775
776 if (hExistingThreadHandle != INVALID_HANDLE_VALUE)
777 {
778 BOOL bHandleCloseResult = ::CloseHandle(hExistingThreadHandle);
779 OU_VERIFY(bHandleCloseResult); // Closing handle should normally succeed
780
781 SetBlockThreadHandle(nBlockIndex, INVALID_HANDLE_VALUE);
782 }
783 }
784
785
786 void CTLSStorageArray::AssignAllBlocksInvalidThreads()
787 {
788 for (unsigned int nBlockIndex = 0; nBlockIndex != TLS_ARRAY_ELEMENT__MAX; ++nBlockIndex)
789 {
790 SetBlockThreadHandle(nBlockIndex, INVALID_HANDLE_VALUE);
791 }
792 }
793
794 bool CTLSStorageArray::CheckIfAllBlocksHaveInvalidThreads()
795 {
796 unsigned nBlockIndex = 0;
797
798 for (; nBlockIndex != TLS_ARRAY_ELEMENT__MAX; ++nBlockIndex)
799 {
800 if (GetBlockThreadHandle(nBlockIndex) != INVALID_HANDLE_VALUE)
801 {
802 break;
803 }
804 }
805
806 bool bResult = nBlockIndex == TLS_ARRAY_ELEMENT__MAX;
807 return bResult;
808 }
809
810
811 #endif // #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
812
813
814 //////////////////////////////////////////////////////////////////////////
815 // CTLSStorageInstance methods
816
817 CTLSStorageInstance *CTLSStorageInstance::AllocateInstance(tlsindextype iValueCount, unsigned int uiInitializationFlags)
818 {
819 size_t nSizeRequired = sizeof(CTLSStorageInstance);
820
821 CTLSStorageInstance *psiNewInstance = (CTLSStorageInstance *)AllocateMemoryBlock(nSizeRequired);
822
823 if (psiNewInstance)
824 {
825 new(psiNewInstance) CTLSStorageInstance(iValueCount, uiInitializationFlags);
826 }
827
828 return psiNewInstance;
829 }
830
831 void CTLSStorageInstance::FreeInstance()
832 {
833 this->CTLSStorageInstance::~CTLSStorageInstance();
834 FreeMemoryBlock(this);
835 }
836
837
838 CTLSStorageInstance::CTLSStorageInstance(tlsindextype iValueCount, unsigned int uiInitializationFlags):
839 m_psaStorageList((atomicptr)0),
840 m_hskStorageKey((HTLSKEYVALUE::value_type)0),
841 m_iValueCount(iValueCount)
842 {
843 SetInitializationFlags(uiInitializationFlags);
844 }
845
846 CTLSStorageInstance::~CTLSStorageInstance()
847 {
848 Finit();
849 }
850
851
852 bool CTLSStorageInstance::Init(ESTORAGEINSTANCEKIND ikInstanceKind)
853 {
854 bool bResult = false;
855
856 bool bKeyAllocationResult = false;
857 HTLSKEYVALUE hkvStorageKey;
858
859 do
860 {
861 if (!AllocateStorageKey(hkvStorageKey, ikInstanceKind))
862 {
863 break;
864 }
865
866 bKeyAllocationResult = true;
867
868 CTLSStorageArray *psaFirstStorageArray = AllocateStorageArray();
869
870 if (!psaFirstStorageArray)
871 {
872 break;
873 }
874
875 SetStorageKey(hkvStorageKey);
876 SetStorageKeyValidFlag();
877 AddStorageArrayToArrayList(psaFirstStorageArray);
878
879 bResult = true;
880 }
881 while (false);
882
883 if (!bResult)
884 {
885 if (bKeyAllocationResult)
886 {
887 FreeStorageKey(hkvStorageKey);
888 }
889 }
890
891 return bResult;
892 }
893
894 void CTLSStorageInstance::Finit()
895 {
896 CTLSStorageArray *psaStorageArrayList = GetStorageArrayList();
897
898 if (psaStorageArrayList)
899 {
900 FreeStorageArrayList(psaStorageArrayList);
901
902 bool bListClearingResult = TrySettingStorageArrayList(NULL, psaStorageArrayList); // It could be assigned directly, but I just do not want to add an extra method
903 OU_VERIFY(bListClearingResult);
904 }
905
906 if (GetStorageKeyValidFlag())
907 {
908 const HTLSKEYVALUE &hkvStorageKey = GetStorageKey();
909 FreeStorageKey(hkvStorageKey);
910
911 ResetStorageKeyValidFlag();
912 }
913 }
914
915
916 void CTLSStorageInstance::FreeStorageBlockOnThreadExit(CTLSStorageBlock *psbStorageBlock)
917 {
918 FreeStorageBlock(psbStorageBlock);
919 }
920
921
922 bool CTLSStorageInstance::FindFreeStorageBlock(CTLSStorageBlock *&psbOutStorageBlock)
923 {
924 bool bResult = false;
925
926 do
927 {
928 if (!FindFreeStorageBlockInArrayList(psbOutStorageBlock))
929 {
930 CTLSStorageArray *psaStorageArray = AllocateStorageArray();
931
932 if (!psaStorageArray)
933 {
934 break;
935 }
936
937 FindFreeStorageBlockFromArray(psbOutStorageBlock, psaStorageArray); // Must always succeed as array is not added to list yet
938
939 AddStorageArrayToArrayList(psaStorageArray);
940 }
941
942 bResult = true;
943 }
944 while (false);
945
946 return bResult;
947 }
948
949 bool CTLSStorageInstance::FindFreeStorageBlockInArrayList(CTLSStorageBlock *&psbOutStorageBlock)
950 {
951 bool bResult;
952
953 CTLSStorageArray *psaListOldHead = NULL;
954 CTLSStorageArray *psaListCurrentHead = GetStorageArrayList();
955
956 while (true)
957 {
958 if (FindFreeStorageBlockInArrayListSegment(psbOutStorageBlock, psaListCurrentHead, psaListOldHead))
959 {
960 bResult = true;
961 break;
962 }
963
964 psaListOldHead = psaListCurrentHead;
965 psaListCurrentHead = GetStorageArrayList();
966
967 if (psaListOldHead == psaListCurrentHead)
968 {
969 bResult = false;
970 break;
971 }
972 }
973
974 return bResult;
975 }
976
977 bool CTLSStorageInstance::FindFreeStorageBlockInArrayListSegment(CTLSStorageBlock *&psbOutStorageBlock,
978 CTLSStorageArray *psaListSegmentBegin, CTLSStorageArray *psaListSegmentEnd)
979 {
980 OU_ASSERT(psaListSegmentBegin != psaListSegmentEnd);
981
982 bool bResult;
983
984 CTLSStorageArray *psaListSegmentCurrent = psaListSegmentBegin;
985
986 while (true)
987 {
988 if (FindFreeStorageBlockFromArray(psbOutStorageBlock, psaListSegmentCurrent))
989 {
990 bResult = true;
991 break;
992 }
993
994 psaListSegmentCurrent = psaListSegmentCurrent->GetNextArray();
995
996 if (psaListSegmentCurrent == psaListSegmentEnd)
997 {
998 bResult = false;
999 break;
1000 }
1001 }
1002
1003 return bResult;
1004 }
1005
1006 bool CTLSStorageInstance::FindFreeStorageBlockFromArray(CTLSStorageBlock *&psbOutStorageBlock,
1007 CTLSStorageArray *psaArrayInstance)
1008 {
1009 tlsindextype iValueCount = GetValueCount();
1010 bool bIsManualCleanup = GetThreadManualCleanupFlag();
1011
1012 return psaArrayInstance->FindFreeStorageBlock(psbOutStorageBlock, iValueCount, bIsManualCleanup);
1013 }
1014
1015
1016 void CTLSStorageInstance::AddStorageArrayToArrayList(CTLSStorageArray *psaStorageArray)
1017 {
1018 while (true)
1019 {
1020 CTLSStorageArray *psaListCurrentHead = GetStorageArrayList();
1021 psaStorageArray->SetNextArray(psaListCurrentHead);
1022
1023 if (TrySettingStorageArrayList(psaStorageArray, psaListCurrentHead))
1024 {
1025 break;
1026 }
1027 }
1028 }
1029
1030
1031 bool CTLSStorageInstance::AllocateStorageKey(HTLSKEYVALUE &hkvOutStorageKey, ESTORAGEINSTANCEKIND ikInstanceKind)
1032 {
1033 bool bResult = false;
1034
1035 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
1036
1037 DWORD dwTlsIndex = ::TlsAlloc();
1038
1039 if (dwTlsIndex != TLS_OUT_OF_INDEXES)
1040 {
1041 hkvOutStorageKey = (HTLSKEYVALUE)(HTLSKEYVALUE::value_type)(size_t)dwTlsIndex;
1042 bResult = true;
1043 }
1044
1045
1046 #else // #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
1047
1048 pthread_key_t pkThreadKey;
1049
1050 int iKeyCreationResult = pthread_key_create(&pkThreadKey,
1051 (ikInstanceKind == SIK_AUTOCLEANUP) ? &CTLSStorageInstance::FreeStorageBlock_Callback_Automatic : &CTLSStorageInstance::FreeStorageBlock_Callback_Manual);
1052 if (iKeyCreationResult == EOK)
1053 {
1054 hkvOutStorageKey = (HTLSKEYVALUE)(HTLSKEYVALUE::value_type)(size_t)pkThreadKey;
1055 bResult = true;
1056 }
1057
1058
1059 #endif // #if _OU_TARGET_OS == ...
1060
1061 return bResult;
1062 }
1063
1064 void CTLSStorageInstance::FreeStorageKey(const HTLSKEYVALUE &hkvStorageKey)
1065 {
1066 #if _OU_TARGET_OS == _OU_TARGET_OS_WINDOWS
1067
1068 DWORD dwTlsIndex = (DWORD)(size_t)(HTLSKEYVALUE::value_type)hkvStorageKey;
1069 OU_ASSERT(dwTlsIndex != TLS_OUT_OF_INDEXES);
1070
1071 BOOL bIndexFreeingResult = ::TlsFree(dwTlsIndex);
1072 OU_VERIFY(bIndexFreeingResult);
1073
1074
1075 #else // #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
1076
1077 pthread_key_t pkThreadKey = (pthread_key_t)(size_t)(HTLSKEYVALUE::value_type)hkvStorageKey;
1078
1079 int iKeyDeletionResult = pthread_key_delete(pkThreadKey);
1080 OU_VERIFY(iKeyDeletionResult == EOK);
1081
1082
1083 #endif // #if _OU_TARGET_OS == ...
1084 }
1085
1086
1087 #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
1088
1089 void CTLSStorageInstance::FreeStorageBlock_Callback_Automatic(void *pv_DataValue)
1090 {
1091 if (pv_DataValue) // Just a precaution
1092 {
1093 CTLSStorageBlock *psbStorageBlock = (CTLSStorageBlock *)pv_DataValue;
1094
1095 g_apsiStorageGlobalInstances[SIK_AUTOCLEANUP]->FreeStorageBlock(psbStorageBlock);
1096 }
1097 }
1098
1099 void CTLSStorageInstance::FreeStorageBlock_Callback_Manual(void *pv_DataValue)
1100 {
1101 if (pv_DataValue) // Just a precaution
1102 {
1103 CTLSStorageBlock *psbStorageBlock = (CTLSStorageBlock *)pv_DataValue;
1104
1105 g_apsiStorageGlobalInstances[SIK_MANUALCLEANUP]->FreeStorageBlock(psbStorageBlock);
1106 }
1107 }
1108
1109
1110 #endif // #if _OU_TARGET_OS != _OU_TARGET_OS_WINDOWS
1111
1112
1113 void CTLSStorageInstance::FreeStorageBlock(CTLSStorageBlock *psbStorageBlock)
1114 {
1115 const int iValueCount = GetValueCount();
1116
1117 CTLSStorageArray *psaArrayInstance = psbStorageBlock->GetHostArray();
1118 psaArrayInstance->FreeStorageBlockOnThreadExit(psbStorageBlock, iValueCount);
1119 }
1120
1121
1122 CTLSStorageArray *CTLSStorageInstance::AllocateStorageArray()
1123 {
1124 const tlsindextype iValueCount = GetValueCount();
1125
1126 return CTLSStorageArray::AllocateInstance(iValueCount);
1127 }
1128
1129 void CTLSStorageInstance::FreeStorageArrayList(CTLSStorageArray *psaStorageArrayList)
1130 {
1131 const tlsindextype iValueCount = GetValueCount();
1132
1133 while (psaStorageArrayList)
1134 {
1135 CTLSStorageArray *psaStorageNextArray = psaStorageArrayList->GetNextArray();
1136
1137 psaStorageArrayList->FreeInstance(iValueCount);
1138
1139 psaStorageArrayList = psaStorageNextArray;
1140 }
1141 }
1142
1143
1144 //////////////////////////////////////////////////////////////////////////
1145 // CThreadLocalStorage methods
1146
1147 bool CThreadLocalStorage::AllocateAndSetStorageValue(const HTLSKEYSELECTOR &hksKeySelector,
1148 tlsindextype iValueIndex, tlsvaluetype vValueData, CTLSValueDestructor fnValueDestructor)
1149 {
1150 OU_ASSERT(OU_IN_SIZET_RANGE(DecodeInstanceKindFromKeySelector(hksKeySelector), SIK__MIN, SIK__MAX));
1151
1152 bool bResult = false;
1153
1154 do
1155 {
1156 ESTORAGEINSTANCEKIND ikInstanceKind = (ESTORAGEINSTANCEKIND)DecodeInstanceKindFromKeySelector(hksKeySelector);
1157 CTLSStorageInstance *psiStorageInstance = g_apsiStorageGlobalInstances[ikInstanceKind];
1158
1159 CTLSStorageBlock *psbStorageBlock;
1160
1161 if (!psiStorageInstance->FindFreeStorageBlock(psbStorageBlock))
1162 {
1163 break;
1164 }
1165
1166 SetKeyStorageBlock(hksKeySelector, psbStorageBlock);
1167
1168 psbStorageBlock->SetValueData(iValueIndex, vValueData);
1169 psbStorageBlock->SetValueDestructor(iValueIndex, fnValueDestructor);
1170
1171 bResult = true;
1172 }
1173 while (false);
1174
1175 return bResult;
1176 }
1177
1178
1179 //////////////////////////////////////////////////////////////////////////
1180 // CTLSInitialization methods
1181
1182 bool CTLSInitialization::InitializeTLSAPI(HTLSKEY &hskOutStorageKey, tlsindextype iValueCount,
1183 unsigned int uiInitializationFlags/*=0*/)
1184 {
1185 OU_ASSERT(g_uiThreadLocalStorageInitializationCount != 0U - 1U);
1186
1187 bool bResult = false;
1188
1189 bool bAtomicAPIInitialized = false;
1190
1191 do
1192 {
1193 const ESTORAGEINSTANCEKIND ikInstanceKind = (uiInitializationFlags & SIF_MANUAL_CLEANUP_ON_THREAD_EXIT) ? SIK_MANUALCLEANUP : SIK_AUTOCLEANUP;
1194
1195 if (g_apsiStorageGlobalInstances[ikInstanceKind] == NULL) // Initialization/finalization must be called from main thread
1196 {
1197 if (!InitializeAtomicAPI())
1198 {
1199 break;
1200 }
1201
1202 bAtomicAPIInitialized = true;
1203
1204 if (!InitializeTLSAPIValidated(ikInstanceKind, iValueCount, uiInitializationFlags))
1205 {
1206 break;
1207 }
1208
1209 const HTLSKEYVALUE &hkvStorageKey = g_apsiStorageGlobalInstances[ikInstanceKind]->RetrieveStorageKey();
1210 g_ahkvStorageGlobalKeyValues[ikInstanceKind] = hkvStorageKey;
1211 }
1212
1213 ++g_uiThreadLocalStorageInitializationCount;
1214
1215 hskOutStorageKey = EncodeKeySelectorFromStorageKind(ikInstanceKind);
1216 OU_ASSERT(iValueCount == g_apsiStorageGlobalInstances[ikInstanceKind]->RetrieveValueCount());
1217 OU_ASSERT(uiInitializationFlags == g_apsiStorageGlobalInstances[ikInstanceKind]->RetrieveInitializationFlags());
1218
1219 bResult = true;
1220 }
1221 while (false);
1222
1223 if (!bResult)
1224 {
1225 if (bAtomicAPIInitialized)
1226 {
1227 FinalizeAtomicAPI();
1228 }
1229 }
1230
1231 return bResult;
1232 }
1233
1234 void CTLSInitialization::FinalizeTLSAPI()
1235 {
1236 OU_ASSERT(g_uiThreadLocalStorageInitializationCount != 0U);
1237
1238 ESTORAGEINSTANCEKIND ikInstanceKind =
1239 (--g_uiThreadLocalStorageInitializationCount == 0U) ? SIK__MIN : SIK__MAX; // Initialization/finalization must be called from main thread
1240 for (; ikInstanceKind != SIK__MAX; ++ikInstanceKind)
1241 {
1242 if (g_apsiStorageGlobalInstances[ikInstanceKind])
1243 {
1244 g_ahkvStorageGlobalKeyValues[ikInstanceKind] = 0;
1245
1246 FinalizeTLSAPIValidated(ikInstanceKind);
1247
1248 FinalizeAtomicAPI();
1249 }
1250 }
1251 }
1252
1253
1254 void CTLSInitialization::CleanupOnThreadExit()
1255 {
1256 const ESTORAGEINSTANCEKIND ikInstanceKind = SIK_MANUALCLEANUP;
1257 CTLSStorageInstance *psiStorageInstance = g_apsiStorageGlobalInstances[ikInstanceKind];
1258
1259 if (psiStorageInstance != NULL)
1260 {
1261 OU_ASSERT(psiStorageInstance->GetIsThreadManualCleanup());
1262
1263 const HTLSKEYSELECTOR &hksKeySelector = EncodeKeySelectorFromStorageKind(ikInstanceKind);
1264 CTLSStorageBlock *psbStorageBlock = CThreadLocalStorage::GetKeyStorageBlock(hksKeySelector);
1265
1266 if (psbStorageBlock)
1267 {
1268 psiStorageInstance->FreeStorageBlockOnThreadExit(psbStorageBlock);
1269
1270 CThreadLocalStorage::SetKeyStorageBlock(hksKeySelector, NULL);
1271 }
1272 }
1273 else
1274 {
1275 OU_ASSERT(false); // The method is not supposed to be called if manual cleanup was not requested on initialization
1276 }
1277 }
1278
1279
1280 bool CTLSInitialization::InitializeTLSAPIValidated(unsigned int uiInstanceKind,
1281 tlsindextype iValueCount, unsigned int uiInitializationFlags)
1282 {
1283 OU_ASSERT(g_apsiStorageGlobalInstances[uiInstanceKind] == NULL);
1284
1285 bool bResult = false;
1286
1287 CTLSStorageInstance *psiStorageInstance;
1288
1289 do
1290 {
1291 // Use static methods instead of constructor/destructor
1292 // to avoid overloading operators new/delete and for
1293 // uniformity with CTLSStorageArray class
1294 psiStorageInstance = CTLSStorageInstance::AllocateInstance(iValueCount, uiInitializationFlags);
1295
1296 if (!psiStorageInstance)
1297 {
1298 break;
1299 }
1300
1301 if (!psiStorageInstance->Init((ESTORAGEINSTANCEKIND)uiInstanceKind))
1302 {
1303 break;
1304 }
1305
1306 g_apsiStorageGlobalInstances[uiInstanceKind] = psiStorageInstance;
1307
1308 bResult = true;
1309 }
1310 while (false);
1311
1312 if (!bResult)
1313 {
1314 if (psiStorageInstance)
1315 {
1316 psiStorageInstance->FreeInstance();
1317 }
1318 }
1319
1320 return bResult;
1321 }
1322
1323 void CTLSInitialization::FinalizeTLSAPIValidated(unsigned int uiInstanceKind)
1324 {
1325 OU_ASSERT(g_apsiStorageGlobalInstances[uiInstanceKind] != NULL);
1326
1327 g_apsiStorageGlobalInstances[uiInstanceKind]->FreeInstance();
1328 g_apsiStorageGlobalInstances[uiInstanceKind] = NULL;
1329 }
1330
1331
1332 END_NAMESPACE_OU();
1333
1334
1335 #endif // #if _OU_FEATURE_SET >= _OU_FEATURE_SET_TLS
1336