Repository navigation
Expand file tree
/
Copy pathsphinxstd.cpp
More file actions
2224 lines (1786 loc) · 51.9 KB
/
Copy pathsphinxstd.cpp
File metadata and controls
2224 lines (1786 loc) · 51.9 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
//
// $Id$
//
//
// Copyright (c) 2001-2016, Andrew Aksyonoff
// Copyright (c) 2008-2016, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
#include "sphinx.h"
#include "sphinxint.h"
#include "sphinxutils.h"
#include <math.h>
#if !USE_WINDOWS
#include <sys/time.h> // for gettimeofday
// define this if you want to run gprof over the threads model - to track children threads also.
#define USE_GPROF 0
#endif
int g_iThreadStackSize = 1024*1024;
//////////////////////////////////////////////////////////////////////////
char CSphString::EMPTY[] = "";
#if USE_WINDOWS
#ifndef NDEBUG
void sphAssert ( const char * sExpr, const char * sFile, int iLine )
{
char sBuffer [ 1024 ];
_snprintf ( sBuffer, sizeof(sBuffer), "%s(%d): assertion %s failed\n", sFile, iLine, sExpr );
if ( MessageBox ( NULL, sBuffer, "Assert failed! Cancel to debug.",
MB_OKCANCEL | MB_TOPMOST | MB_SYSTEMMODAL | MB_ICONEXCLAMATION )!=IDOK )
{
__debugbreak ();
} else
{
fprintf ( stdout, "%s", sBuffer );
exit ( 1 );
}
}
#endif // !NDEBUG
#endif // USE_WINDOWS
/////////////////////////////////////////////////////////////////////////////
// DEBUG MEMORY MANAGER
/////////////////////////////////////////////////////////////////////////////
#if SPH_DEBUG_LEAKS
#undef new
#define SPH_DEBUG_DOFREE 1 // 0 will not actually free returned blocks; helps to catch double deletes etc
const DWORD MEMORY_MAGIC_PLAIN = 0xbbbbbbbbUL;
const DWORD MEMORY_MAGIC_ARRAY = 0xaaaaaaaaUL;
const DWORD MEMORY_MAGIC_END = 0xeeeeeeeeUL;
const DWORD MEMORY_MAGIC_DELETED = 0xdedededeUL;
struct CSphMemHeader
{
DWORD m_uMagic;
const char * m_sFile;
#if SPH_DEBUG_BACKTRACES
const char * m_sBacktrace;
#endif
int m_iLine;
size_t m_iSize;
int m_iAllocId;
BYTE * m_pPointer;
CSphMemHeader * m_pNext;
CSphMemHeader * m_pPrev;
};
static CSphMutex g_tAllocsMutex;
static int g_iCurAllocs = 0;
static int g_iAllocsId = 0;
static CSphMemHeader * g_pAllocs = NULL;
static int64_t g_iCurBytes = 0;
static int g_iTotalAllocs = 0;
static int g_iPeakAllocs = 0;
static int64_t g_iPeakBytes = 0;
#if SPH_ALLOC_FILL
static bool g_bFirstRandomAlloc = true;
#endif
void * sphDebugNew ( size_t iSize, const char * sFile, int iLine, bool bArray )
{
BYTE * pBlock = (BYTE*) ::malloc ( iSize+sizeof(CSphMemHeader)+sizeof(DWORD) );
if ( !pBlock )
sphDie ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too
*(DWORD*)( pBlock+iSize+sizeof(CSphMemHeader) ) = MEMORY_MAGIC_END;
g_tAllocsMutex.Lock();
CSphMemHeader * pHeader = (CSphMemHeader*) pBlock;
pHeader->m_uMagic = bArray ? MEMORY_MAGIC_ARRAY : MEMORY_MAGIC_PLAIN;
pHeader->m_sFile = sFile;
#if SPH_ALLOC_FILL
if ( g_bFirstRandomAlloc )
{
sphAutoSrand();
g_bFirstRandomAlloc = false;
}
BYTE * pBlockPtr = (BYTE*)(pHeader+1);
for ( size_t i = 0; i < iSize; i++ )
*pBlockPtr++ = BYTE(sphRand () & 0xFF);
#endif
#if SPH_DEBUG_BACKTRACES
const char * sTrace = DoBacktrace ( 0, 3 );
if ( sTrace )
{
char * pTrace = (char*) ::malloc ( strlen(sTrace) + 1 );
strcpy ( pTrace, sTrace ); //NOLINT
pHeader->m_sBacktrace = pTrace;
} else
pHeader->m_sBacktrace = NULL;
#endif
pHeader->m_iLine = iLine;
pHeader->m_iSize = iSize;
pHeader->m_iAllocId = ++g_iAllocsId;
pHeader->m_pPointer = pBlock;
pHeader->m_pNext = g_pAllocs;
pHeader->m_pPrev = NULL;
if ( g_pAllocs )
{
assert ( !g_pAllocs->m_pPrev );
g_pAllocs->m_pPrev = pHeader;
}
g_pAllocs = pHeader;
g_iCurAllocs++;
g_iCurBytes += iSize;
g_iTotalAllocs++;
g_iPeakAllocs = Max ( g_iPeakAllocs, g_iCurAllocs );
g_iPeakBytes = Max ( g_iPeakBytes, g_iCurBytes );
g_tAllocsMutex.Unlock();
return pHeader+1;
}
void sphDebugDelete ( void * pPtr, bool bArray )
{
if ( !pPtr )
return;
g_tAllocsMutex.Lock();
CSphMemHeader * pHeader = ((CSphMemHeader*)pPtr)-1;
switch ( pHeader->m_uMagic )
{
case MEMORY_MAGIC_ARRAY:
if ( !bArray )
sphDie ( "delete [] on non-array block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
break;
case MEMORY_MAGIC_PLAIN:
if ( bArray )
sphDie ( "delete on array block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
break;
case MEMORY_MAGIC_DELETED:
sphDie ( "double delete on block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
break;
default:
sphDie ( "delete on unmanaged block at 0x%08x", pPtr );
return;
}
BYTE * pBlock = (BYTE*) pHeader;
if ( *(DWORD*)( pBlock+pHeader->m_iSize+sizeof(CSphMemHeader) )!=MEMORY_MAGIC_END )
sphDie ( "out-of-bounds write beyond block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
// unchain
if ( pHeader==g_pAllocs )
g_pAllocs = g_pAllocs->m_pNext;
if ( pHeader->m_pPrev )
{
assert ( pHeader->m_pPrev->m_uMagic==MEMORY_MAGIC_PLAIN || pHeader->m_pPrev->m_uMagic==MEMORY_MAGIC_ARRAY );
pHeader->m_pPrev->m_pNext = pHeader->m_pNext;
}
if ( pHeader->m_pNext )
{
assert ( pHeader->m_pNext->m_uMagic==MEMORY_MAGIC_PLAIN || pHeader->m_pNext->m_uMagic==MEMORY_MAGIC_ARRAY );
pHeader->m_pNext->m_pPrev = pHeader->m_pPrev;
}
pHeader->m_pPrev = NULL;
pHeader->m_pNext = NULL;
// mark and delete
pHeader->m_uMagic = MEMORY_MAGIC_DELETED;
g_iCurAllocs--;
g_iCurBytes -= pHeader->m_iSize;
#if SPH_DEBUG_BACKTRACES
if ( pHeader->m_sBacktrace )
::free ( (void*) pHeader->m_sBacktrace );
#endif
#if SPH_DEBUG_DOFREE
::free ( pHeader );
#endif
g_tAllocsMutex.Unlock();
}
int64_t sphAllocBytes ()
{
return g_iCurBytes;
}
int sphAllocsCount ()
{
return g_iCurAllocs;
}
int sphAllocsLastID ()
{
return g_iAllocsId;
}
void sphAllocsDump ( int iFile, int iSinceID )
{
g_tAllocsMutex.Lock();
sphSafeInfo ( iFile, "--- dumping allocs since %d ---\n", iSinceID );
uint64_t iTotalBytes = 0;
int iTotal = 0;
for ( CSphMemHeader * pHeader = g_pAllocs;
pHeader && pHeader->m_iAllocId > iSinceID;
pHeader = pHeader->m_pNext )
{
sphSafeInfo ( iFile, "alloc %d at %s(%d): 0x%0p %d bytes\n", pHeader->m_iAllocId,
pHeader->m_sFile, pHeader->m_iLine, pHeader->m_pPointer, (int)pHeader->m_iSize );
#if SPH_DEBUG_BACKTRACES
sphSafeInfo ( iFile, "Backtrace:\n%s\n", pHeader->m_sBacktrace );
#endif
iTotalBytes += pHeader->m_iSize;
iTotal++;
}
sphSafeInfo ( iFile, "total allocs %d: %d.%03d bytes", iTotal, (int)(iTotalBytes/1024), (int)(iTotalBytes%1000) );
sphSafeInfo ( iFile, "--- end of dump ---\n" );
g_tAllocsMutex.Unlock();
}
void sphAllocsStats ()
{
fprintf ( stdout, "--- total-allocs=%d, peak-allocs=%d, peak-bytes=" INT64_FMT "\n",
g_iTotalAllocs, g_iPeakAllocs, g_iPeakBytes );
}
void sphAllocsCheck ()
{
g_tAllocsMutex.Lock();
for ( CSphMemHeader * pHeader=g_pAllocs; pHeader; pHeader=pHeader->m_pNext )
{
BYTE * pBlock = (BYTE*) pHeader;
if (!( pHeader->m_uMagic==MEMORY_MAGIC_ARRAY || pHeader->m_uMagic==MEMORY_MAGIC_PLAIN ))
sphDie ( "corrupted header in block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
if ( *(DWORD*)( pBlock+pHeader->m_iSize+sizeof(CSphMemHeader) )!=MEMORY_MAGIC_END )
sphDie ( "out-of-bounds write beyond block %d allocated at %s(%d)",
pHeader->m_iAllocId, pHeader->m_sFile, pHeader->m_iLine );
}
g_tAllocsMutex.Unlock();
}
void sphMemStatInit () {}
void sphMemStatDone () {}
void sphMemStatDump ( int ) {}
//////////////////////////////////////////////////////////////////////////
void * operator new ( size_t iSize, const char * sFile, int iLine )
{
return sphDebugNew ( iSize, sFile, iLine, false );
}
void * operator new [] ( size_t iSize, const char * sFile, int iLine )
{
return sphDebugNew ( iSize, sFile, iLine, true );
}
void operator delete ( void * pPtr )
{
sphDebugDelete ( pPtr, false );
}
void operator delete [] ( void * pPtr )
{
sphDebugDelete ( pPtr, true );
}
//////////////////////////////////////////////////////////////////////////////
// ALLOCACTIONS COUNT/SIZE PROFILER
//////////////////////////////////////////////////////////////////////////////
#else
#if SPH_ALLOCS_PROFILER
#undef new
static CSphMutex g_tAllocsMutex;
static int g_iAllocsId = 0;
static int g_iCurAllocs = 0;
static int64_t g_iCurBytes = 0;
static int g_iTotalAllocs = 0;
static int g_iPeakAllocs = 0;
static int64_t g_iPeakBytes = 0;
// statictic's per memory category
struct MemCategorized_t
{
int64_t m_iSize;
int m_iCount;
MemCategorized_t()
: m_iSize ( 0 )
, m_iCount ( 0 )
{
}
};
static MemCategory_e sphMemStatGet ();
// memory categories storage
static MemCategorized_t g_dMemCategoryStat [ MEM_TOTAL ];
//////////////////////////////////////////////////////////////////////////
// ALLOCATIONS COUNT/SIZE PROFILER
//////////////////////////////////////////////////////////////////////////
void * sphDebugNew ( size_t iSize )
{
BYTE * pBlock = (BYTE*) ::malloc ( iSize+sizeof(size_t)*2 );
if ( !pBlock )
sphDie ( "out of memory (unable to allocate %"PRIu64" bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too
const int iMemType = sphMemStatGet();
assert ( iMemType>=0 && iMemType<MEM_TOTAL );
g_tAllocsMutex.Lock ();
g_iAllocsId++;
g_iCurAllocs++;
g_iCurBytes += iSize;
g_iTotalAllocs++;
g_iPeakAllocs = Max ( g_iCurAllocs, g_iPeakAllocs );
g_iPeakBytes = Max ( g_iCurBytes, g_iPeakBytes );
g_dMemCategoryStat[iMemType].m_iSize += iSize;
g_dMemCategoryStat[iMemType].m_iCount++;
g_tAllocsMutex.Unlock ();
size_t * pData = (size_t *)pBlock;
pData[0] = iSize;
pData[1] = iMemType;
return pBlock + sizeof(size_t)*2;
}
void sphDebugDelete ( void * pPtr )
{
if ( !pPtr )
return;
size_t * pBlock = (size_t*) pPtr;
pBlock -= 2;
const int iSize = pBlock[0];
const int iMemType = pBlock[1];
assert ( iMemType>=0 && iMemType<MEM_TOTAL );
g_tAllocsMutex.Lock ();
g_iCurAllocs--;
g_iCurBytes -= iSize;
g_dMemCategoryStat[iMemType].m_iSize -= iSize;
g_dMemCategoryStat[iMemType].m_iCount--;
g_tAllocsMutex.Unlock ();
::free ( pBlock );
}
void sphAllocsStats ()
{
g_tAllocsMutex.Lock ();
fprintf ( stdout, "--- total-allocs=%d, peak-allocs=%d, peak-bytes=" INT64_FMT "\n",
g_iTotalAllocs, g_iPeakAllocs, g_iPeakBytes );
g_tAllocsMutex.Unlock ();
}
int64_t sphAllocBytes () { return g_iCurBytes; }
int sphAllocsCount () { return g_iCurAllocs; }
int sphAllocsLastID () { return g_iAllocsId; }
void sphAllocsDump ( int, int ) {}
void sphAllocsCheck () {}
void * operator new ( size_t iSize, const char *, int ) { return sphDebugNew ( iSize ); }
void * operator new [] ( size_t iSize, const char *, int ) { return sphDebugNew ( iSize ); }
void operator delete ( void * pPtr ) { sphDebugDelete ( pPtr ); }
void operator delete [] ( void * pPtr ) { sphDebugDelete ( pPtr ); }
//////////////////////////////////////////////////////////////////////////////
// MEMORY STATISTICS
//////////////////////////////////////////////////////////////////////////////
/// TLS key of memory category stack
SphThreadKey_t g_tTLSMemCategory;
STATIC_ASSERT ( MEM_TOTAL<255, TOO_MANY_MEMORY_CATEGORIES );
// stack of memory categories as we move deeper and deeper
class MemCategoryStack_t // NOLINT
{
#define MEM_STACK_MAX 1024
BYTE m_dStack[MEM_STACK_MAX];
int m_iDepth;
public:
// ctor ( cross platform )
void Reset ()
{
m_iDepth = 0;
m_dStack[0] = MEM_CORE;
}
void Push ( MemCategory_e eCategory )
{
assert ( eCategory>=0 && eCategory<MEM_TOTAL );
assert ( m_iDepth+1<MEM_STACK_MAX );
m_dStack[++m_iDepth] = (BYTE)eCategory;
}
#ifndef NDEBUG
void Pop ( MemCategory_e eCategory )
{
assert ( eCategory>=0 && eCategory<MEM_TOTAL );
#else
void Pop ( MemCategory_e )
{
#endif
assert ( m_iDepth-1>=0 );
assert ( m_dStack[m_iDepth]==eCategory );
m_iDepth--;
}
MemCategory_e Top () const
{
assert ( m_iDepth>= 0 && m_iDepth<MEM_STACK_MAX );
assert ( m_dStack[m_iDepth]>=0 && m_dStack[m_iDepth]<MEM_TOTAL );
return MemCategory_e ( m_dStack[m_iDepth] );
}
};
static MemCategoryStack_t * g_pMainTLS = NULL; // category stack of main thread
// memory statistic's per thread factory
static MemCategoryStack_t * sphMemStatThdInit ()
{
MemCategoryStack_t * pTLS = (MemCategoryStack_t *)sphDebugNew ( sizeof ( MemCategoryStack_t ) );
pTLS->Reset();
Verify ( sphThreadSet ( g_tTLSMemCategory, pTLS ) );
return pTLS;
}
// per thread cleanup of memory statistic's
static void sphMemStatThdCleanup ( MemCategoryStack_t * pTLS )
{
sphDebugDelete ( pTLS );
}
// init of memory statistic's data
static void sphMemStatInit ()
{
Verify ( sphThreadKeyCreate ( &g_tTLSMemCategory ) );
// main thread statistic's creation
assert ( g_pMainTLS==NULL );
g_pMainTLS = sphMemStatThdInit();
assert ( g_pMainTLS!=NULL );
}
// cleanup of memory statistic's data
static void sphMemStatDone ()
{
assert ( g_pMainTLS!=NULL );
sphMemStatThdCleanup ( g_pMainTLS );
sphThreadKeyDelete ( g_tTLSMemCategory );
}
// direct access for special category
void sphMemStatMMapAdd ( int64_t iSize )
{
g_tAllocsMutex.Lock ();
g_iCurAllocs++;
g_iCurBytes += iSize;
g_iTotalAllocs++;
g_iPeakAllocs = Max ( g_iCurAllocs, g_iPeakAllocs );
g_iPeakBytes = Max ( g_iCurBytes, g_iPeakBytes );
g_dMemCategoryStat[MEM_MMAPED].m_iSize += iSize;
g_dMemCategoryStat[MEM_MMAPED].m_iCount++;
g_tAllocsMutex.Unlock ();
}
void sphMemStatMMapDel ( int64_t iSize )
{
g_tAllocsMutex.Lock ();
g_iCurAllocs--;
g_iCurBytes -= iSize;
g_dMemCategoryStat[MEM_MMAPED].m_iSize -= iSize;
g_dMemCategoryStat[MEM_MMAPED].m_iCount--;
g_tAllocsMutex.Unlock ();
}
// push new category on arrival
void sphMemStatPush ( MemCategory_e eCategory )
{
MemCategoryStack_t * pTLS = (MemCategoryStack_t*) sphThreadGet ( g_tTLSMemCategory );
if ( pTLS )
pTLS->Push ( eCategory );
};
// restore last category
void sphMemStatPop ( MemCategory_e eCategory )
{
MemCategoryStack_t * pTLS = (MemCategoryStack_t*) sphThreadGet ( g_tTLSMemCategory );
if ( pTLS )
pTLS->Pop ( eCategory );
};
// get current category
static MemCategory_e sphMemStatGet ()
{
MemCategoryStack_t * pTLS = (MemCategoryStack_t*) sphThreadGet ( g_tTLSMemCategory );
return pTLS ? pTLS->Top() : MEM_CORE;
}
// human readable category names
#define MEM_CATEGORY(_arg) #_arg
static const char* g_dMemCategoryName[] = { MEM_CATEGORIES };
#undef MEM_CATEGORY
void sphMemStatDump ( int iFD )
{
int64_t iSize = 0;
int iCount = 0;
for ( int i=0; i<MEM_TOTAL; i++ )
{
iSize += (int64_t) g_dMemCategoryStat[i].m_iSize;
iCount += g_dMemCategoryStat[i].m_iCount;
}
sphSafeInfo ( iFD, "%-24s allocs-count=%d, mem-total=%d.%d Mb", "(total)", iCount,
(int)(iSize/1048576), (int)( (iSize*10/1048576)%10 ) );
for ( int i=0; i<MEM_TOTAL; i++ )
if ( g_dMemCategoryStat[i].m_iCount>0 )
{
iSize = (int64_t) g_dMemCategoryStat[i].m_iSize;
sphSafeInfo ( iFD, "%-24s allocs-count=%d, mem-total=%d.%d Mb",
g_dMemCategoryName[i], g_dMemCategoryStat[i].m_iCount,
(int)(iSize/1048576), (int)( (iSize*10/1048576)%10 ) );
}
}
//////////////////////////////////////////////////////////////////////////////
// PRODUCTION MEMORY MANAGER
//////////////////////////////////////////////////////////////////////////////
#else
#ifndef SPH_DONT_OVERRIDE_MEMROUTINES
void * operator new ( size_t iSize )
{
void * pResult = ::malloc ( iSize );
if ( !pResult )
sphDieRestart ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too
return pResult;
}
void * operator new [] ( size_t iSize )
{
void * pResult = ::malloc ( iSize );
if ( !pResult )
sphDieRestart ( "out of memory (unable to allocate " UINT64_FMT " bytes)", (uint64_t)iSize ); // FIXME! this may fail with malloc error too
return pResult;
}
void operator delete ( void * pPtr ) throw ()
{
if ( pPtr )
::free ( pPtr );
}
void operator delete [] ( void * pPtr ) throw ()
{
if ( pPtr )
::free ( pPtr );
}
#endif // SPH_DONT_OVERRIDE_MEMROUTINES
#endif // SPH_ALLOCS_PROFILER
#endif // SPH_DEBUG_LEAKS
//////////////////////////////////////////////////////////////////////////
// now let the rest of sphinxstd use proper new
#if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER
#undef new
#define new new(__FILE__,__LINE__)
#endif
/////////////////////////////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////////////////////////////
static SphDieCallback_t g_pfDieCallback = NULL;
void sphSetDieCallback ( SphDieCallback_t pfDieCallback )
{
g_pfDieCallback = pfDieCallback;
}
void sphDie ( const char * sTemplate, ... )
{
char sBuf[1024];
va_list ap;
va_start ( ap, sTemplate );
vsnprintf ( sBuf, sizeof(sBuf), sTemplate, ap );
va_end ( ap );
// if there's no callback,
// or if callback returns true,
// log to stdout
if ( !g_pfDieCallback || g_pfDieCallback ( sBuf ) )
fprintf ( stdout, "FATAL: %s\n", sBuf );
exit ( 1 );
}
void sphDieRestart ( const char * sTemplate, ... )
{
char sBuf[1024];
va_list ap;
va_start ( ap, sTemplate );
vsnprintf ( sBuf, sizeof(sBuf), sTemplate, ap );
va_end ( ap );
// if there's no callback,
// or if callback returns true,
// log to stdout
if ( !g_pfDieCallback || g_pfDieCallback ( sBuf ) )
fprintf ( stdout, "FATAL: %s\n", sBuf );
exit ( 2 ); // almost CRASH_EXIT
}
//////////////////////////////////////////////////////////////////////////
// RANDOM NUMBERS GENERATOR
//////////////////////////////////////////////////////////////////////////
/// MWC (Multiply-With-Carry) RNG, invented by George Marsaglia
static DWORD g_dRngState[5] = { 0x95d3474bUL, 0x035cf1f7UL, 0xfd43995fUL, 0x5dfc55fbUL, 0x334a9229UL };
/// seed
void sphSrand ( DWORD uSeed )
{
for ( int i=0; i<5; i++ )
{
uSeed = uSeed*29943829 - 1;
g_dRngState[i] = uSeed;
}
for ( int i=0; i<19; i++ )
sphRand();
}
/// auto-seed RNG based on time and PID
void sphAutoSrand ()
{
// get timestamp
#if !USE_WINDOWS
struct timeval tv;
gettimeofday ( &tv, NULL );
#else
#define getpid() GetCurrentProcessId()
struct
{
time_t tv_sec;
DWORD tv_usec;
} tv;
FILETIME ft;
GetSystemTimeAsFileTime ( &ft );
uint64_t ts = ( uint64_t(ft.dwHighDateTime)<<32 ) + uint64_t(ft.dwLowDateTime) - 116444736000000000ULL; // Jan 1, 1970 magic
ts /= 10; // to microseconds
tv.tv_sec = (DWORD)(ts/1000000);
tv.tv_usec = (DWORD)(ts%1000000);
#endif
// twist and shout
sphSrand ( sphRand() ^ DWORD(tv.tv_sec) ^ (DWORD(tv.tv_usec) + DWORD(getpid())) );
}
/// generate another dword
DWORD sphRand ()
{
uint64_t uSum;
uSum =
(uint64_t)g_dRngState[0] * (uint64_t)5115 +
(uint64_t)g_dRngState[1] * (uint64_t)1776 +
(uint64_t)g_dRngState[2] * (uint64_t)1492 +
(uint64_t)g_dRngState[3] * (uint64_t)2111111111UL +
(uint64_t)g_dRngState[4];
g_dRngState[3] = g_dRngState[2];
g_dRngState[2] = g_dRngState[1];
g_dRngState[1] = g_dRngState[0];
g_dRngState[4] = (DWORD)( uSum>>32 );
g_dRngState[0] = (DWORD)uSum;
return g_dRngState[0];
}
//////////////////////////////////////////////////////////////////////////
// THREADING FUNCTIONS
//////////////////////////////////////////////////////////////////////////
// This is a working context for a thread wrapper. It wraps every thread to
// store information about it's stack size, cleanup threads and something else.
// This struct always should be allocated in the heap, cause wrapper need
// to see it all the time and it frees it out of the heap by itself. Wrapper thread function
// receives as an argument a pointer to ThreadCall_t with one function pointer to
// a main thread function. Afterwards, thread can set up one or more cleanup functions
// which will be executed by a wrapper in the linked list order after it dies.
struct ThreadCall_t
{
void ( *m_pCall )( void * pArg );
void * m_pArg;
#if USE_GPROF
pthread_mutex_t m_dlock;
pthread_cond_t m_dwait;
itimerval m_ditimer;
#endif
ThreadCall_t * m_pNext;
};
static SphThreadKey_t g_tThreadCleanupKey;
static SphThreadKey_t g_tMyThreadStack;
#if USE_WINDOWS
#define SPH_THDFUNC DWORD __stdcall
#else
#define SPH_THDFUNC void *
#endif
SPH_THDFUNC sphThreadProcWrapper ( void * pArg )
{
// This is the first local variable in the new thread. So, its address is the top of the stack.
// We need to know thread stack size for both expression and query evaluating engines.
// We store expressions as a linked tree of structs and execution is a calls of mutually
// recursive methods. Before executing we compute tree height and multiply it by a constant
// with experimentally measured value to check whether we have enough stack to execute current query.
// The check is not ideal and do not work for all compilers and compiler settings.
char cTopOfMyStack;
assert ( sphThreadGet ( g_tThreadCleanupKey )==NULL );
assert ( sphThreadGet ( g_tMyThreadStack )==NULL );
#if SPH_ALLOCS_PROFILER
MemCategoryStack_t * pTLS = sphMemStatThdInit();
#endif
#if USE_GPROF
// Set the profile timer value
setitimer ( ITIMER_PROF, &( (ThreadCall_t*) pArg )->m_ditimer, NULL );
// Tell the calling thread that we don't need its data anymore
pthread_mutex_lock ( &( (ThreadCall_t*) pArg)->m_dlock );
pthread_cond_signal ( &( (ThreadCall_t*) pArg)->m_dwait );
pthread_mutex_unlock ( &( (ThreadCall_t*) pArg)->m_dlock );
#endif
ThreadCall_t * pCall = (ThreadCall_t*) pArg;
MemorizeStack ( & cTopOfMyStack );
pCall->m_pCall ( pCall->m_pArg );
SafeDelete ( pCall );
ThreadCall_t * pCleanup = (ThreadCall_t*) sphThreadGet ( g_tThreadCleanupKey );
while ( pCleanup )
{
pCall = pCleanup;
pCall->m_pCall ( pCall->m_pArg );
pCleanup = pCall->m_pNext;
SafeDelete ( pCall );
}
#if SPH_ALLOCS_PROFILER
sphMemStatThdCleanup ( pTLS );
#endif
return 0;
}
#if !USE_WINDOWS
void * sphThreadInit ( bool bDetached )
#else
void * sphThreadInit ( bool )
#endif
{
static bool bInit = false;
#if !USE_WINDOWS
static pthread_attr_t tJoinableAttr;
static pthread_attr_t tDetachedAttr;
#endif
if ( !bInit )
{
#if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER
sphMemStatInit();
#endif
// we're single-threaded yet, right?!
if ( !sphThreadKeyCreate ( &g_tThreadCleanupKey ) )
sphDie ( "FATAL: sphThreadKeyCreate() failed" );
if ( !sphThreadKeyCreate ( &g_tMyThreadStack ) )
sphDie ( "FATAL: sphThreadKeyCreate() failed" );
#if !USE_WINDOWS
if ( pthread_attr_init ( &tJoinableAttr ) )
sphDie ( "FATAL: pthread_attr_init( joinable ) failed" );
if ( pthread_attr_init ( &tDetachedAttr ) )
sphDie ( "FATAL: pthread_attr_init( detached ) failed" );
if ( pthread_attr_setdetachstate ( &tDetachedAttr, PTHREAD_CREATE_DETACHED ) )
sphDie ( "FATAL: pthread_attr_setdetachstate( detached ) failed" );
#endif
bInit = true;
}
#if !USE_WINDOWS
if ( pthread_attr_setstacksize ( &tJoinableAttr, g_iThreadStackSize + PTHREAD_STACK_MIN ) )
sphDie ( "FATAL: pthread_attr_setstacksize( joinable ) failed" );
if ( pthread_attr_setstacksize ( &tDetachedAttr, g_iThreadStackSize + PTHREAD_STACK_MIN ) )
sphDie ( "FATAL: pthread_attr_setstacksize( detached ) failed" );
return bDetached ? &tDetachedAttr : &tJoinableAttr;
#else
return NULL;
#endif
}
#if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER
void sphThreadDone ( int iFD )
{
sphMemStatDump ( iFD );
sphMemStatDone();
}
#else
void sphThreadDone ( int )
{
}
#endif
bool sphThreadCreate ( SphThread_t * pThread, void (*fnThread)(void*), void * pArg, bool bDetached )
{
// we can not put this on current stack because wrapper need to see
// it all the time and it will destroy this data from heap by itself
ThreadCall_t * pCall = new ThreadCall_t;
pCall->m_pCall = fnThread;
pCall->m_pArg = pArg;
pCall->m_pNext = NULL;
// create thread
#if USE_WINDOWS
sphThreadInit ( bDetached );
*pThread = CreateThread ( NULL, g_iThreadStackSize, sphThreadProcWrapper, pCall, 0, NULL );
if ( *pThread )
return true;
#else
#if USE_GPROF
getitimer ( ITIMER_PROF, &pCall->m_ditimer );
pthread_cond_init ( &pCall->m_dwait, NULL );
pthread_mutex_init ( &pCall->m_dlock, NULL );
pthread_mutex_lock ( &pCall->m_dlock );
#endif
void * pAttr = sphThreadInit ( bDetached );
errno = pthread_create ( pThread, (pthread_attr_t*) pAttr, sphThreadProcWrapper, pCall );
#if USE_GPROF
if ( !errno )
pthread_cond_wait ( &pCall->m_dwait, &pCall->m_dlock );
pthread_mutex_unlock ( &pCall->m_dlock );
pthread_mutex_destroy ( &pCall->m_dlock );
pthread_cond_destroy ( &pCall->m_dwait );
#endif
if ( !errno )
return true;
#endif
// thread creation failed so we need to cleanup ourselves
SafeDelete ( pCall );
return false;
}
bool sphThreadJoin ( SphThread_t * pThread )
{
#if USE_WINDOWS
DWORD uWait = WaitForSingleObject ( *pThread, INFINITE );
CloseHandle ( *pThread );
*pThread = NULL;
return ( uWait==WAIT_OBJECT_0 || uWait==WAIT_ABANDONED );
#else
return pthread_join ( *pThread, NULL )==0;
#endif
}
// Adds a function call (a new task for a wrapper) to a linked list
// of thread contexts. They will be executed one by one right after
// the main thread ends its execution. This is a way for a wrapper
// to free local resources allocated by its main thread.
void sphThreadOnExit ( void (*fnCleanup)(void*), void * pArg )
{
ThreadCall_t * pCleanup = new ThreadCall_t;
pCleanup->m_pCall = fnCleanup;