This repository has been archived by the owner on Mar 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
/
nedmalloc.c
2275 lines (2201 loc) · 69.5 KB
/
nedmalloc.c
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
/* Alternative malloc implementation for multiple threads without
lock contention based on dlmalloc. (C) 2005-2012 Niall Douglas
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#if 0 /* Effectively makes nedmalloc = dlmalloc */
#define THREADCACHEMAX 0
#define DEFAULT_GRANULARITY 65536
#define DEFAULTMAXTHREADSINPOOL 1
#endif
#ifdef _MSC_VER
/* Enable full aliasing on MSVC */
/*#pragma optimize("a", on)*/
/*#pragma optimize("g", off)*/
#pragma warning(push)
#pragma warning(disable:4100) /* unreferenced formal parameter */
#pragma warning(disable:4127) /* conditional expression is constant */
#pragma warning(disable:4232) /* address of dllimport is not static, identity not guaranteed */
#pragma warning(disable:4706) /* assignment within conditional expression */
#define _CRT_SECURE_NO_WARNINGS 1 /* Don't care about MSVC warnings on POSIX functions */
#include <stdio.h>
#define fopen(f, m) _fsopen((f), (m), 0x40/*_SH_DENYNO*/) /* Have Windows let other programs view the log file as it is written */
#ifndef UNICODE
#define UNICODE /* Turn on windows unicode support */
#endif
#else
#include <stdio.h>
#endif
/*#define NEDMALLOC_DEBUG 1*/
/*#define ENABLE_LOGGING 7
#define NEDMALLOC_TESTLOGENTRY(tc, np, type, mspace, size, mem, alignment, flags, returned) (((type)&ENABLE_LOGGING)&&((size)>16*1024))
#define NEDMALLOC_STACKBACKTRACEDEPTH 16*/
/*#define NEDMALLOC_FORCERESERVE(p, mem, size) (((size)>=(256*1024)) ? M2_RESERVE_MULT(8) : 0)*/
/*#define WIN32_DIRECT_USE_FILE_MAPPINGS 0*/
/*#define NEDMALLOC_DEBUG 1*/
/*#define FULLSANITYCHECKS*/
/*#define FORCEINLINE*/
/* There is only support for the user mode page allocator on Windows at present */
#if !defined(ENABLE_USERMODEPAGEALLOCATOR)
#define ENABLE_USERMODEPAGEALLOCATOR 0
#endif
/* If link time code generation is on, don't force or prevent inlining */
#if defined(_MSC_VER) && defined(NEDMALLOC_DLL_EXPORTS)
#define FORCEINLINE
#define NOINLINE
#endif
#include "nedmalloc.h"
#include <errno.h>
#ifdef HAVE_VALGRIND
#include <valgrind/valgrind.h>
#include <valgrind/memcheck.h>
#endif
#if defined(WIN32)
#include <malloc.h>
#else
#if defined(__cplusplus)
extern "C"
#else
extern
#endif
#if defined(__linux__) || defined(__FreeBSD__)
/* Sadly we can't include <malloc.h> as it causes a redefinition error */
size_t malloc_usable_size(void *);
#elif defined(__APPLE__)
#if TARGET_OS_IPHONE
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#else
#error Do not know what to do here
#endif
#endif
#if USE_ALLOCATOR==1
#define MSPACES 1
#define ONLY_MSPACES 1
#endif
#define USE_DL_PREFIX 1
#define USE_RECURSIVE_LOCKS 1
#ifndef USE_LOCKS
#define USE_LOCKS 1
#endif
#define FOOTERS 1 /* Need to enable footers so frees lock the right mspace */
#define INSECURE 0 /* nedblkmstate works a lot better with magic enabled */
#ifndef NEDMALLOC_DEBUG
#if defined(DEBUG) || defined(_DEBUG)
#define NEDMALLOC_DEBUG 1
#else
#define NEDMALLOC_DEBUG 0
#endif
#endif
/* We need to consistently define DEBUG=0|1, _DEBUG and NDEBUG for dlmalloc */
#if !defined(DEBUG) && !defined(NDEBUG)
#ifdef __GNUC__
#warning DEBUG may not be defined but without NDEBUG being defined allocator will run with assert checking! Define NDEBUG to run at full speed.
#elif defined(_MSC_VER)
#pragma message(__FILE__ ": WARNING: DEBUG may not be defined but without NDEBUG being defined allocator will run with assert checking! Define NDEBUG to run at full speed.")
#endif
#endif
#undef DEBUG
#undef _DEBUG
#if NEDMALLOC_DEBUG
#define _DEBUG
#define DEBUG 1
#else
#define DEBUG 0
#endif
#ifdef NDEBUG /* Disable assert checking on release builds */
#undef DEBUG
#undef _DEBUG
#endif
/* The default of 64Kb means we spend too much time kernel-side */
#ifndef DEFAULT_GRANULARITY
#define DEFAULT_GRANULARITY (1*1024*1024)
#if DEBUG
#define DEFAULT_GRANULARITY_ALIGNED
#endif
#endif
/*#define USE_SPIN_LOCKS 0*/
#if ENABLE_USERMODEPAGEALLOCATOR
extern int OSHavePhysicalPageSupport(void);
extern void *userpage_malloc(size_t toallocate, unsigned flags);
extern int userpage_free(void *mem, size_t size);
extern void *userpage_realloc(void *mem, size_t oldsize, size_t newsize, int flags, unsigned flags2);
#define USERPAGE_TOPDOWN (M2_CUSTOM_FLAGS_BEGIN<<0)
#define USERPAGE_NOCOMMIT (M2_CUSTOM_FLAGS_BEGIN<<1)
/* This can provide a very significant speed boost */
#undef MMAP_CLEARS
#define MMAP_CLEARS 0
#define MUNMAP(h, a, s) (!OSHavePhysicalPageSupport() ? MUNMAP_DEFAULT((h), (a), (s)) : userpage_free((a), (s)))
#define MMAP(s, f) (!OSHavePhysicalPageSupport() ? MMAP_DEFAULT((s)) : userpage_malloc((s), (f)))
#define MREMAP(addr, osz, nsz, mv) (!OSHavePhysicalPageSupport() ? MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) : userpage_realloc((addr), (osz), (nsz), (mv), 0))
#define DIRECT_MMAP(h, s, f) (!OSHavePhysicalPageSupport() ? DIRECT_MMAP_DEFAULT((h), (s), (f)) : userpage_malloc((s), (f)|USERPAGE_TOPDOWN))
#define DIRECT_MREMAP(h, a, os, ns, f, f2) (!OSHavePhysicalPageSupport() ? DIRECT_MREMAP_DEFAULT((h), (a), (os), (ns), (f), (f2)) : userpage_realloc((a), (os), (ns), (f), (f2)|USERPAGE_TOPDOWN))
/*#undef MREMAP
#define MREMAP(addr, osz, nsz, mv) (!OSHavePhysicalPageSupport() ? MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) : MFAIL)*/
/*#undef DIRECT_MREMAP
#define DIRECT_MREMAP(h, a, os, ns, f, f2) (!OSHavePhysicalPageSupport() ? DIRECT_MREMAP_DEFAULT((h), (a), (os), (ns), (f), (f2)) : MFAIL)*/
#endif
#include "malloc.c.h"
#ifdef NDEBUG /* Disable assert checking on release builds */
#undef DEBUG
#endif
/* The default number of threads allowed into a pool at once */
#ifndef DEFAULTMAXTHREADSINPOOL
#define DEFAULTMAXTHREADSINPOOL 4
#endif
/* The maximum size to be allocated from the thread cache */
#ifndef THREADCACHEMAX
#define THREADCACHEMAX 8192
#elif THREADCACHEMAX && !defined(THREADCACHEMAXBINS)
#ifdef __GNUC__
#warning If you are changing THREADCACHEMAX, do you also need to change THREADCACHEMAXBINS=(topbitpos(THREADCACHEMAX)-4)?
#elif defined(_MSC_VER)
#pragma message(__FILE__ ": WARNING: If you are changing THREADCACHEMAX, do you also need to change THREADCACHEMAXBINS=(topbitpos(THREADCACHEMAX)-4)?")
#endif
#endif
/* The maximum concurrent threads in a pool possible */
#ifndef MAXTHREADSINPOOL
#define MAXTHREADSINPOOL 16
#endif
/* The maximum number of threadcaches which can be allocated */
#ifndef THREADCACHEMAXCACHES
#define THREADCACHEMAXCACHES 256
#endif
#ifndef THREADCACHEMAXBINS
#if 0
/* The number of cache entries for finer grained bins. This is (topbitpos(THREADCACHEMAX)-4)*2 */
#define THREADCACHEMAXBINS ((13-4)*2)
#else
/* The number of cache entries. This is (topbitpos(THREADCACHEMAX)-4) */
#define THREADCACHEMAXBINS (13-4)
#endif
#endif
/* Point at which the free space in a thread cache is garbage collected */
#ifndef THREADCACHEMAXFREESPACE
#define THREADCACHEMAXFREESPACE (1024*1024)
#endif
/* NEDMALLOC_FORCERESERVE is used to force malloc2 flags for normal malloc, calloc et al */
#ifndef NEDMALLOC_FORCERESERVE
#define NEDMALLOC_FORCERESERVE(p, mem, size) 0
#endif
/* ENABLE_LOGGING is a bitmask of what events to log */
#if ENABLE_LOGGING
#ifndef NEDMALLOC_LOGFILE
#define NEDMALLOC_LOGFILE "nedmalloc.csv"
#endif
#endif
/* NEDMALLOC_TESTLOGENTRY returns non-zero if the entry should be logged */
#ifndef NEDMALLOC_TESTLOGENTRY
#define NEDMALLOC_TESTLOGENTRY(tc, np, type, mspace, size, mem, alignment, flags, returned) ((type)&ENABLE_LOGGING)
#endif
/* NEDMALLOC_STACKBACKTRACEDEPTH has the logger store a stack backtrace per logged item. Slow! */
#ifndef NEDMALLOC_STACKBACKTRACEDEPTH
#define NEDMALLOC_STACKBACKTRACEDEPTH 0
#endif
#if NEDMALLOC_STACKBACKTRACEDEPTH
#include "Dbghelp.h"
#include "psapi.h"
#pragma comment(lib, "dbghelp.lib")
#pragma comment(lib, "psapi.lib")
#endif
#define NM_FLAGS_MASK (M2_FLAGS_MASK&~M2_ZERO_MEMORY)
#if USE_LOCKS
#ifdef WIN32
#define TLSVAR DWORD
#define TLSALLOC(k) (*(k)=TlsAlloc(), TLS_OUT_OF_INDEXES==*(k))
#define TLSFREE(k) (!TlsFree(k))
#define TLSGET(k) TlsGetValue(k)
#define TLSSET(k, a) (!TlsSetValue(k, a))
#ifdef DEBUG
static LPVOID ChkedTlsGetValue(DWORD idx)
{
LPVOID ret=TlsGetValue(idx);
assert(S_OK==GetLastError());
return ret;
}
#undef TLSGET
#define TLSGET(k) ChkedTlsGetValue(k)
#endif
#else
#define TLSVAR pthread_key_t
#define TLSALLOC(k) pthread_key_create(k, 0)
#define TLSFREE(k) pthread_key_delete(k)
#define TLSGET(k) pthread_getspecific(k)
#define TLSSET(k, a) pthread_setspecific(k, a)
#endif
#else /* Probably if you're not using locks then you don't want ANY pthread stuff at all */
#define TLSVAR void *
#define TLSALLOC(k) (*k=0)
#define TLSFREE(k) (k=0)
#define TLSGET(k) k
#define TLSSET(k, a) (k=a, 0)
#endif
#if ENABLE_USERMODEPAGEALLOCATOR
#include "usermodepageallocator.c"
#endif
#if defined(__cplusplus)
#if !defined(NO_NED_NAMESPACE)
namespace nedalloc {
#else
extern "C" {
#endif
#endif
#if USE_ALLOCATOR==0
static void *unsupported_operation(const char *opname) THROWSPEC
{
fprintf(stderr, "nedmalloc: The operation %s is not supported under this build configuration\n", opname);
abort();
return 0;
}
static size_t mspacecounter=(size_t) 0xdeadbeef;
#endif
#ifndef ENABLE_FAST_HEAP_DETECTION
static void *RESTRICT leastusedaddress;
static size_t largestusedblock;
#endif
/* Used to redirect system allocator ops if needed */
extern void *(*sysmalloc)(size_t);
extern void *(*syscalloc)(size_t, size_t);
extern void *(*sysrealloc)(void *, size_t);
extern void (*sysfree)(void *);
extern size_t (*sysblksize)(void *);
#if !defined(REPLACE_SYSTEM_ALLOCATOR) || (!defined(_MSC_VER) && !defined(__MINGW32__))
void *(*sysmalloc)(size_t)=malloc;
void *(*syscalloc)(size_t, size_t)=calloc;
void *(*sysrealloc)(void *, size_t)=realloc;
void (*sysfree)(void *)=free;
size_t (*sysblksize)(void *)=
#if defined(_MSC_VER) || defined(__MINGW32__)
/* This is the MSVCRT equivalent */
_msize;
#elif defined(__linux__) || defined(__FreeBSD__)
/* This is the glibc/ptmalloc2/dlmalloc/BSD equivalent. */
malloc_usable_size;
#elif defined(__APPLE__)
/* This is the Apple BSD libc equivalent. */
(size_t (*)(void *)) malloc_size;
#else
#error Cannot tolerate the memory allocator of an unknown system!
#endif
#else
/* Remove the MSVCRT dependency on the memory functions */
void *(*sysmalloc)(size_t);
void *(*syscalloc)(size_t, size_t);
void *(*sysrealloc)(void *, size_t);
void (*sysfree)(void *);
size_t (*sysblksize)(void *);
#endif
static FORCEINLINE NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void *CallMalloc(void *RESTRICT mspace, size_t size, size_t alignment, unsigned flags) THROWSPEC
{
void *RESTRICT ret=0;
#if USE_MAGIC_HEADERS
size_t _alignment=alignment;
size_t *_ret=0;
size_t bytes=size+alignment+3*sizeof(size_t);
/* Avoid addition overflow. */
if(bytes<size)
return 0;
size=bytes;
_alignment=0;
#endif
#if USE_ALLOCATOR==0
ret=(flags & M2_ZERO_MEMORY) ? syscalloc(1, size) : sysmalloc(size); /* magic headers takes care of alignment */
#elif USE_ALLOCATOR==1
ret=mspace_malloc2((mstate) mspace, size, alignment, flags);
#ifdef HAVE_VALGRIND
if(ret) VALGRIND_MEMPOOL_ALLOC(mspace, ret, size);
#endif
#ifndef ENABLE_FAST_HEAP_DETECTION
if(ret)
{
mchunkptr p=mem2chunk(ret);
size_t truesize=chunksize(p) - overhead_for(p);
if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
}
#endif
#endif
if(!ret) return 0;
#if DEBUG
if(flags & M2_ZERO_MEMORY)
{
const char *RESTRICT n;
for(n=(const char *)ret; n<(const char *)ret+size; n++)
{
assert(!*n);
}
}
#endif
#if USE_MAGIC_HEADERS
_ret=(size_t *) ret;
ret=(void *)(_ret+3);
if(alignment) ret=(void *)(((size_t) ret+alignment-1)&~(alignment-1));
for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *)"NEDMALOC";
_ret[0]=(size_t) mspace;
_ret[1]=size-3*sizeof(size_t);
#endif
return ret;
}
static FORCEINLINE NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void *CallRealloc(void *RESTRICT mspace, void *RESTRICT mem, int isforeign, size_t oldsize, size_t newsize, size_t alignment, unsigned flags) THROWSPEC
{
void *RESTRICT ret=0;
#if USE_MAGIC_HEADERS
mstate oldmspace=0;
size_t *_ret=0, *_mem=(size_t *) mem-3;
#endif
if(isforeign)
{ /* Transfer */
#if USE_MAGIC_HEADERS
assert(_mem[0]!=*(size_t *) "NEDMALOC");
#endif
if((ret=CallMalloc(mspace, newsize, alignment, flags)))
{
#if defined(DEBUG)
printf("*** nedmalloc frees system allocated block %p\n", mem);
#endif
memcpy(ret, mem, oldsize<newsize ? oldsize : newsize);
sysfree(mem);
}
return ret;
}
#if USE_MAGIC_HEADERS
assert(_mem[0]==*(size_t *) "NEDMALOC");
newsize+=3*sizeof(size_t);
oldmspace=(mstate) _mem[1];
assert(oldsize>=_mem[2]);
for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
mem=(void *)(++_mem);
#endif
#if USE_ALLOCATOR==0
ret=sysrealloc(mem, newsize);
#elif USE_ALLOCATOR==1
ret=mspace_realloc2((mstate) mspace, mem, newsize, alignment, flags);
#ifdef HAVE_VALGRIND
if(ret) VALGRIND_MEMPOOL_CHANGE(mspace, mem, ret, newsize);
#endif
#ifndef ENABLE_FAST_HEAP_DETECTION
if(ret)
{
mchunkptr p=mem2chunk(ret);
size_t truesize=chunksize(p) - overhead_for(p);
if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
}
#endif
#endif
if(!ret)
{ /* Put it back the way it was */
#if USE_MAGIC_HEADERS
for(; *_mem==0; *_mem++=*(size_t *) "NEDMALOC");
#endif
return 0;
}
#if USE_MAGIC_HEADERS
_ret=(size_t *) ret;
ret=(void *)(_ret+3);
for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *) "NEDMALOC";
_ret[0]=(size_t) mspace;
_ret[1]=newsize-3*sizeof(size_t);
#endif
return ret;
}
static FORCEINLINE void CallFree(void *RESTRICT mspace, void *RESTRICT mem, int isforeign) THROWSPEC
{
#if USE_MAGIC_HEADERS
mstate oldmspace=0;
size_t *_mem=(size_t *) mem-3, oldsize=0;
#endif
if(isforeign)
{
#if USE_MAGIC_HEADERS
assert(_mem[0]!=*(size_t *) "NEDMALOC");
#endif
#if defined(DEBUG)
printf("*** nedmalloc frees system allocated block %p\n", mem);
#endif
sysfree(mem);
return;
}
#if USE_MAGIC_HEADERS
assert(_mem[0]==*(size_t *) "NEDMALOC");
oldmspace=(mstate) _mem[1];
oldsize=_mem[2];
for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
mem=(void *)(++_mem);
#endif
#if USE_ALLOCATOR==0
sysfree(mem);
#elif USE_ALLOCATOR==1
#ifdef HAVE_VALGRIND
{
void *m=mspace ? mspace : get_mstate_for(mem2chunk(mem));
mspace_free((mstate) mspace, mem);
VALGRIND_MEMPOOL_FREE(m, mem);
/* Mark the first two pointers in the newly freed block as used (linked list of freed blocks) */
VALGRIND_MAKE_MEM_DEFINED(mem, 2*sizeof(void *));
}
#else
mspace_free((mstate) mspace, mem);
#endif
#endif
}
static NEDMALLOCNOALIASATTR mstate nedblkmstate(void *RESTRICT mem) THROWSPEC
{
if(mem)
{
#if USE_MAGIC_HEADERS
size_t *_mem=(size_t *) mem-3;
if(_mem[0]==*(size_t *) "NEDMALOC")
{
return (mstate) _mem[1];
}
else return 0;
#else
#if USE_ALLOCATOR==0
/* Fail everything */
return 0;
#elif USE_ALLOCATOR==1
#ifdef ENABLE_FAST_HEAP_DETECTION
#ifdef WIN32
/* On Windows for RELEASE both x86 and x64 the NT heap precedes each block with an eight byte header
which looks like:
normal: 4 bytes of size, 4 bytes of [char < 64, char < 64, char < 64 bit 0 always set, char random ]
mmaped: 4 bytes of size 4 bytes of [zero, zero, 0xb, zero ]
On Windows for DEBUG both x86 and x64 the preceding four bytes is always 0xfdfdfdfd (no man's land).
*/
#pragma pack(push, 1)
struct _HEAP_ENTRY
{
USHORT Size;
USHORT PreviousSize;
UCHAR Cookie; /* SegmentIndex */
UCHAR Flags; /* always bit 0 (HEAP_ENTRY_BUSY). bit 1=(HEAP_ENTRY_EXTRA_PRESENT), bit 2=normal block (HEAP_ENTRY_FILL_PATTERN), bit 3=mmap block (HEAP_ENTRY_VIRTUAL_ALLOC). Bit 4 (HEAP_ENTRY_LAST_ENTRY) could be set */
UCHAR UnusedBytes;
UCHAR SmallTagIndex; /* fastbin index. Always one of 0x02, 0x03, 0x04 < 0x80 */
} *RESTRICT he=((struct _HEAP_ENTRY *) mem)-1;
#pragma pack(pop)
unsigned int header=((unsigned int *)mem)[-1], mask1=0x8080E100, result1, mask2=0xFFFFFF06, result2;
result1=header & mask1; /* Positive testing for NT heap */
result2=header & mask2; /* Positive testing for dlmalloc */
if(result1==0x00000100 && result2!=0x00000102)
{ /* This is likely a NT heap block */
return 0;
}
#endif
#ifdef __linux__
/* On Linux glibc uses ptmalloc2 (really dlmalloc) just as we do, but prev_foot contains rubbish
when the preceding block is allocated because ptmalloc2 finds the local mstate by rounding the ptr
down to the nearest megabyte. It's like dlmalloc with FOOTERS disabled. */
mchunkptr p=mem2chunk(mem);
mstate fm=get_mstate_for(p);
/* If it's a ptmalloc2 block, fm is likely to be some crazy value */
if(!is_aligned(fm)) return 0;
if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
if(ok_magic(fm))
return fm;
else
return 0;
if(1) { }
#endif
else
{
mchunkptr p=mem2chunk(mem);
mstate fm=get_mstate_for(p);
assert(ok_magic(fm)); /* If this fails, someone tried to free a block twice */
if(ok_magic(fm))
return fm;
}
#else /* ENABLE_FAST_HEAP_DETECTION */
#ifdef WIN32
#ifdef _MSC_VER
__try
#else
#if ENABLE_TOLERANT_NEDMALLOC
#error Lack of SEH support makes nedmalloc unreliable with foreign memory blocks. Make sure ENABLE_TOLERANT_NEDMALLOC is turned off!
#endif
#endif /* defined(_MSC_VER) */
#elif ENABLE_TOLERANT_NEDMALLOC
#warning nedmalloc is unreliable with foreign memory blocks, so make sure you really want ENABLE_TOLERANT_NEDMALLOC turned on!
#endif
{
/* We try to return zero here if it isn't one of our own blocks, however
the current block annotation scheme used by dlmalloc makes it impossible
to be absolutely sure of avoiding a segfault.
mchunkptr->prev_foot = mem-(2*size_t) = mstate ^ mparams.magic for PRECEDING block;
mchunkptr->head = mem-(1*size_t) = 8 multiple size of this block with bottom three bits = FLAG_BITS
FLAG_BITS = bit 0 is CINUSE (currently in use unless is mmap), bit 1 is PINUSE (previous block currently
in use unless mmap), bit 2 is UNUSED and currently is always zero.
*/
register void *RESTRICT leastusedaddress_=leastusedaddress; /* Cache these to avoid register reloading */
register size_t largestusedblock_=largestusedblock;
if(!is_aligned(mem)) return 0; /* Would fail very rarely as all allocators return aligned blocks */
if(mem<leastusedaddress_) return 0; /* Simple but effective */
{
mchunkptr p=mem2chunk(mem);
mstate fm=0;
int ismmapped=is_mmapped(p);
if((!ismmapped && !is_inuse(p)) || (p->head & FLAG4_BIT)) return 0;
/* Reduced uncertainty by 0.5^2 = 25.0% */
/* size should never exceed largestusedblock */
if(chunksize(p)-overhead_for(p)>largestusedblock_) return 0;
/* Reduced uncertainty by a minimum of 0.5^3 = 12.5%, maximum 0.5^16 = 0.0015% */
/* Having sanity checked prev_foot and head, check next block */
if(!ismmapped && (!next_pinuse(p) || (next_chunk(p)->head & FLAG4_BIT))) return 0;
/* Reduced uncertainty by 0.5^5 = 3.13% or 0.5^18 = 0.00038% */
#if 0
/* If previous block is free, check that its next block pointer equals us */
if(!ismmapped && !pinuse(p))
if(next_chunk(prev_chunk(p))!=p) return 0;
/* We could start comparing prev_foot's for similarity but it starts getting slow. */
#endif
fm = get_mstate_for(p);
if(!is_aligned(fm) || (void *)fm<leastusedaddress_) return 0;
#if 0
/* See if mem is lower in memory than mem */
if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
#endif
assert(ok_magic(fm)); /* If this fails, someone tried to free a block twice */
if(ok_magic(fm))
return fm;
}
}
#ifdef WIN32
#ifdef _MSC_VER
__except(1) { }
#endif
#endif /* WIN32 */
#endif /* ENABLE_FAST_HEAP_DETECTION */
#endif /* USE_ALLOCATOR */
#endif /* USE_MAGIC_HEADERS */
}
return 0;
}
NEDMALLOCNOALIASATTR size_t nedblksize(int *RESTRICT isforeign, void *RESTRICT mem, unsigned flags) THROWSPEC
{
if(mem)
{
if(isforeign) *isforeign=1;
#if USE_MAGIC_HEADERS
{
size_t *_mem=(size_t *) mem-3;
if(_mem[0]==*(size_t *) "NEDMALOC")
{
mstate mspace=(mstate) _mem[1];
size_t size=_mem[2];
if(isforeign) *isforeign=0;
return size;
}
}
#elif USE_ALLOCATOR==1
if((flags & NM_SKIP_TOLERANCE_CHECKS) || nedblkmstate(mem))
{
mchunkptr p=mem2chunk(mem);
if(isforeign) *isforeign=0;
return chunksize(p)-overhead_for(p);
}
#ifdef DEBUG
else
{
int a=1; /* Set breakpoints here if needed */
}
#endif
#endif
#if defined(ENABLE_TOLERANT_NEDMALLOC) || USE_ALLOCATOR==0
return sysblksize(mem);
#endif
}
return 0;
}
NEDMALLOCNOALIASATTR size_t nedmemsize(void *RESTRICT mem) THROWSPEC { return nedblksize(0, mem, 0); }
NEDMALLOCNOALIASATTR void nedsetvalue(void *v) THROWSPEC { nedpsetvalue((nedpool *) 0, v); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc(size_t size) THROWSPEC { return nedpmalloc((nedpool *) 0, size); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedcalloc(size_t no, size_t size) THROWSPEC { return nedpcalloc((nedpool *) 0, no, size); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc(void *mem, size_t size) THROWSPEC { return nedprealloc((nedpool *) 0, mem, size); }
NEDMALLOCNOALIASATTR void nedfree(void *mem) THROWSPEC { nedpfree((nedpool *) 0, mem); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmemalign(size_t alignment, size_t bytes) THROWSPEC { return nedpmemalign((nedpool *) 0, alignment, bytes); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc2(size_t size, size_t alignment, unsigned flags) THROWSPEC { return nedpmalloc2((nedpool *) 0, size, alignment, flags); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc2(void *mem, size_t size, size_t alignment, unsigned flags) THROWSPEC { return nedprealloc2((nedpool *) 0, mem, size, alignment, flags); }
NEDMALLOCNOALIASATTR void nedfree2(void *mem, unsigned flags) THROWSPEC { nedpfree2((nedpool *) 0, mem, flags); }
NEDMALLOCNOALIASATTR struct nedmallinfo nedmallinfo(void) THROWSPEC { return nedpmallinfo((nedpool *) 0); }
NEDMALLOCNOALIASATTR int nedmallopt(int parno, int value) THROWSPEC { return nedpmallopt((nedpool *) 0, parno, value); }
NEDMALLOCNOALIASATTR int nedmalloc_trim(size_t pad) THROWSPEC { return nedpmalloc_trim((nedpool *) 0, pad); }
void nedmalloc_stats() THROWSPEC { nedpmalloc_stats((nedpool *) 0); }
NEDMALLOCNOALIASATTR size_t nedmalloc_footprint() THROWSPEC { return nedpmalloc_footprint((nedpool *) 0); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_calloc(size_t elemsno, size_t elemsize, void **chunks) THROWSPEC { return nedpindependent_calloc((nedpool *) 0, elemsno, elemsize, chunks); }
NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_comalloc(size_t elems, size_t *sizes, void **chunks) THROWSPEC { return nedpindependent_comalloc((nedpool *) 0, elems, sizes, chunks); }
#ifdef WIN32
typedef unsigned __int64 timeCount;
static timeCount GetTimestamp()
{
static LARGE_INTEGER ticksPerSec;
static double scalefactor;
static timeCount baseCount;
LARGE_INTEGER val;
timeCount ret;
if(!scalefactor)
{
if(QueryPerformanceFrequency(&ticksPerSec))
scalefactor=ticksPerSec.QuadPart/1000000000000.0;
else
scalefactor=1;
}
if(!QueryPerformanceCounter(&val))
return (timeCount) GetTickCount() * 1000000000;
ret=(timeCount) (val.QuadPart/scalefactor);
if(!baseCount) baseCount=ret;
return ret-baseCount;
}
#else
#include <sys/time.h>
typedef unsigned long long timeCount;
static timeCount GetTimestamp()
{
static timeCount baseCount;
timeCount ret;
#ifdef CLOCK_MONOTONIC
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
ret=((timeCount) ts.tv_sec*1000000000000LL)+ts.tv_nsec*1000LL;
#else
struct timeval tv;
gettimeofday(&tv, 0);
ret=((timeCount) tv.tv_sec*1000000000000LL)+tv.tv_usec*1000000LL;
#endif
if(!baseCount) baseCount=ret;
return ret-baseCount;
}
#endif
/* Set ENABLE_LOGGING to an AND mask of which of these you want to
log, so set it to 0xffffffff for everything */
typedef enum LogEntryType_t
{
LOGENTRY_MALLOC =(1<<0),
LOGENTRY_REALLOC =(1<<1),
LOGENTRY_FREE =(1<<2),
LOGENTRY_THREADCACHE_MALLOC =(1<<3),
LOGENTRY_THREADCACHE_FREE =(1<<4),
LOGENTRY_THREADCACHE_CLEAN =(1<<5),
LOGENTRY_POOL_MALLOC =(1<<6),
LOGENTRY_POOL_REALLOC =(1<<7),
LOGENTRY_POOL_FREE =(1<<8)
} LogEntryType;
#if NEDMALLOC_STACKBACKTRACEDEPTH
typedef struct StackFrameType_t
{
void *pc;
char module[64];
char functname[256];
char file[96];
int lineno;
} StackFrameType;
#endif
typedef struct logentry_t
{
timeCount timestamp;
nedpool *np;
LogEntryType type;
int mspace;
size_t size;
void *mem;
size_t alignment;
unsigned flags;
void *returned;
#if NEDMALLOC_STACKBACKTRACEDEPTH
StackFrameType stack[NEDMALLOC_STACKBACKTRACEDEPTH];
#endif
} logentry;
static const char *LogEntryTypeStrings[]={
"LOGENTRY_MALLOC",
"LOGENTRY_REALLOC",
"LOGENTRY_FREE",
"LOGENTRY_THREADCACHE_MALLOC",
"LOGENTRY_THREADCACHE_FREE",
"LOGENTRY_THREADCACHE_CLEAN",
"LOGENTRY_POOL_MALLOC",
"LOGENTRY_POOL_REALLOC",
"LOGENTRY_POOL_FREE",
"******************"
};
struct threadcacheblk_t;
typedef struct threadcacheblk_t threadcacheblk;
struct threadcacheblk_t
{ /* Keep less than 32 bytes as sizeof(threadcacheblk) is the minimum allocation size */
#ifdef FULLSANITYCHECKS
unsigned int magic;
#endif
int isforeign;
unsigned int lastUsed;
size_t size;
threadcacheblk *RESTRICT next, *RESTRICT prev;
};
typedef struct threadcache_t
{
#ifdef FULLSANITYCHECKS
unsigned int magic1;
#endif
int mymspace; /* Last mspace entry this thread used */
long threadid;
unsigned int mallocs, frees, successes;
#if ENABLE_LOGGING
logentry *logentries, *logentriesptr, *logentriesend;
#endif
size_t freeInCache; /* How much free space is stored in this cache */
threadcacheblk *RESTRICT bins[(THREADCACHEMAXBINS+1)*2];
#ifdef FULLSANITYCHECKS
unsigned int magic2;
#endif
} threadcache;
struct nedpool_t
{
#if USE_LOCKS
MLOCK_T mutex;
#endif
void *uservalue;
int threads; /* Max entries in m to use */
threadcache *RESTRICT caches[THREADCACHEMAXCACHES];
TLSVAR mycache; /* Thread cache for this thread. 0 for unset, negative for use mspace-1 directly, otherwise is cache-1 */
mstate m[MAXTHREADSINPOOL+1]; /* mspace entries for this pool */
};
static nedpool syspool;
#if ENABLE_LOGGING
#if NEDMALLOC_STACKBACKTRACEDEPTH
#if defined(WIN32) && defined(_MSC_VER)
#define COPY_STRING(d, s, maxlen) { size_t len=strlen(s); len=(len>maxlen) ? maxlen-1 : len; memcpy(d, s, len); d[len]=0; }
#pragma optimize("g", off)
static int ExceptionFilter(unsigned int code, struct _EXCEPTION_POINTERS *ep, CONTEXT *ct) THROWSPEC
{
*ct=*ep->ContextRecord;
return EXCEPTION_EXECUTE_HANDLER;
}
static DWORD64 __stdcall GetModBase(HANDLE hProcess, DWORD64 dwAddr) THROWSPEC
{
DWORD64 modulebase;
// Try to get the module base if already loaded, otherwise load the module
modulebase=SymGetModuleBase64(hProcess, dwAddr);
if(modulebase)
return modulebase;
else
{
MEMORY_BASIC_INFORMATION stMBI ;
if ( 0 != VirtualQueryEx ( hProcess, (LPCVOID)(size_t)dwAddr, &stMBI, sizeof(stMBI)))
{
int n;
DWORD dwPathLen=0, dwNameLen=0 ;
TCHAR szFile[ MAX_PATH ], szModuleName[ MAX_PATH ] ;
MODULEINFO mi={0};
dwPathLen = GetModuleFileName ( (HMODULE) stMBI.AllocationBase , szFile, MAX_PATH );
dwNameLen = GetModuleBaseName (hProcess, (HMODULE) stMBI.AllocationBase , szModuleName, MAX_PATH );
for(n=dwNameLen; n>0; n--)
{
if(szModuleName[n]=='.')
{
szModuleName[n]=0;
break;
}
}
if(!GetModuleInformation(hProcess, (HMODULE) stMBI.AllocationBase, &mi, sizeof(mi)))
{
//fxmessage("WARNING: GetModuleInformation() returned error code %d\n", GetLastError());
}
if(!SymLoadModule64 ( hProcess, NULL, (PSTR)( (dwPathLen) ? szFile : 0), (PSTR)( (dwNameLen) ? szModuleName : 0),
(DWORD64) mi.lpBaseOfDll, mi.SizeOfImage))
{
//fxmessage("WARNING: SymLoadModule64() returned error code %d\n", GetLastError());
}
//fxmessage("%s, %p, %x, %x\n", szFile, mi.lpBaseOfDll, mi.SizeOfImage, (DWORD) mi.lpBaseOfDll+mi.SizeOfImage);
modulebase=SymGetModuleBase64(hProcess, dwAddr);
return modulebase;
}
}
return 0;
}
extern HANDLE sym_myprocess;
extern VOID (WINAPI *RtlCaptureContextAddr)(PCONTEXT);
extern void DeinitSym(void) THROWSPEC;
static void DoStackWalk(logentry *p) THROWSPEC
{
int i,i2;
HANDLE mythread=(HANDLE) GetCurrentThread();
STACKFRAME64 sf={ 0 };
CONTEXT ct={ 0 };
if(!sym_myprocess)
{
DWORD symopts;
DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &sym_myprocess, 0, FALSE, DUPLICATE_SAME_ACCESS);
symopts=SymGetOptions();
SymSetOptions(symopts /*| SYMOPT_DEFERRED_LOADS*/ | SYMOPT_LOAD_LINES);
SymInitialize(sym_myprocess, NULL, TRUE);
atexit(DeinitSym);
}
ct.ContextFlags=CONTEXT_FULL;
// Use RtlCaptureContext() if we have it as it saves an exception throw
if((VOID (WINAPI *)(PCONTEXT)) -1==RtlCaptureContextAddr)
RtlCaptureContextAddr=(VOID (WINAPI *)(PCONTEXT)) GetProcAddress(GetModuleHandle(L"kernel32"), "RtlCaptureContext");
if(RtlCaptureContextAddr)
RtlCaptureContextAddr(&ct);
else
{ // This is nasty, but it works
__try
{
int *foo=0;
*foo=78;
}
__except (ExceptionFilter(GetExceptionCode(), GetExceptionInformation(), &ct))
{
}
}
sf.AddrPC.Mode=sf.AddrStack.Mode=sf.AddrFrame.Mode=AddrModeFlat;
#if !(defined(_M_AMD64) || defined(_M_X64))
sf.AddrPC.Offset =ct.Eip;
sf.AddrStack.Offset=ct.Esp;
sf.AddrFrame.Offset=ct.Ebp;
#else
sf.AddrPC.Offset =ct.Rip;
sf.AddrStack.Offset=ct.Rsp;
sf.AddrFrame.Offset=ct.Rbp; // maybe Rdi?
#endif
for(i2=0; i2<NEDMALLOC_STACKBACKTRACEDEPTH; i2++)
{
IMAGEHLP_MODULE64 ihm={ sizeof(IMAGEHLP_MODULE64) };
char temp[MAX_PATH+sizeof(IMAGEHLP_SYMBOL64)];
IMAGEHLP_SYMBOL64 *ihs;
IMAGEHLP_LINE64 ihl={ sizeof(IMAGEHLP_LINE64) };
DWORD64 offset;
if(!StackWalk64(
#if !(defined(_M_AMD64) || defined(_M_X64))
IMAGE_FILE_MACHINE_I386,
#else
IMAGE_FILE_MACHINE_AMD64,
#endif
sym_myprocess, mythread, &sf, &ct, NULL, SymFunctionTableAccess64, GetModBase, NULL))
break;
if(0==sf.AddrPC.Offset)
break;
i=i2;
if(i) // Skip first entry relating to this function
{
DWORD lineoffset=0;
p->stack[i-1].pc=(void *)(size_t) sf.AddrPC.Offset;
if(SymGetModuleInfo64(sym_myprocess, sf.AddrPC.Offset, &ihm))
{
char *leaf;
leaf=strrchr(ihm.ImageName, '\\');
if(!leaf) leaf=ihm.ImageName-1;
COPY_STRING(p->stack[i-1].module, leaf+1, sizeof(p->stack[i-1].module));
}
else strcpy(p->stack[i-1].module, "<unknown>");
//fxmessage("WARNING: SymGetModuleInfo64() returned error code %d\n", GetLastError());
memset(temp, 0, MAX_PATH+sizeof(IMAGEHLP_SYMBOL64));
ihs=(IMAGEHLP_SYMBOL64 *) temp;
ihs->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL64);
ihs->Address=sf.AddrPC.Offset;
ihs->MaxNameLength=MAX_PATH;
if(SymGetSymFromAddr64(sym_myprocess, sf.AddrPC.Offset, &offset, ihs))
{
COPY_STRING(p->stack[i-1].functname, ihs->Name, sizeof(p->stack[i-1].functname));
if(strlen(p->stack[i-1].functname)<sizeof(p->stack[i-1].functname)-8)
{
sprintf(strchr(p->stack[i-1].functname, 0), " +0x%x", offset);
}
}
else
strcpy(p->stack[i-1].functname, "<unknown>");
if(SymGetLineFromAddr64(sym_myprocess, sf.AddrPC.Offset, &lineoffset, &ihl))
{
char *leaf;
p->stack[i-1].lineno=ihl.LineNumber;
leaf=strrchr(ihl.FileName, '\\');
if(!leaf) leaf=ihl.FileName-1;
COPY_STRING(p->stack[i-1].file, leaf+1, sizeof(p->stack[i-1].file));
}
else
strcpy(p->stack[i-1].file, "<unknown>");
}
}
}
#pragma optimize("g", on)
#else
static void DoStackWalk(logentry *p) THROWSPEC
{
void *backtr[NEDMALLOC_STACKBACKTRACEDEPTH];
size_t size;
char **strings;
size_t i2;
size=backtrace(backtr, NEDMALLOC_STACKBACKTRACEDEPTH);
strings=backtrace_symbols(backtr, size);
for(i2=0; i2<size; i2++)
{ // Format can be <file path>(<mangled symbol>+0x<offset>) [<pc>]
// or can be <file path> [<pc>]
int start=0, end=strlen(strings[i2]), which=0, idx;