-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
1460 lines (1326 loc) · 36.6 KB
/
util.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
/***************************************************************
Copyright (C) 2006-2009 Hewlett-Packard Development Company, L.P.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
***************************************************************/
/* Equivalent to core nomos v1.29 */
/**
* \file
* \brief misc utilites
*
* @version "$Id: util.c 4032 2011-04-05 22:16:20Z bobgo $"
*/
#include <stdarg.h>
#include <stdio.h>
#include "nomos.h"
#include "util.h"
#include "list.h"
#include "nomos_regex.h"
#include "nomos_utils.h"
#define MM_CACHESIZE 20 ///< MM Cache size
#define MAXLENGTH 100 ///< Buffer length
#ifdef REUSE_STATIC_MEMORY
static char grepzone[10485760]; /* 10M for now, adjust if needed */
#endif /* REUSE_STATIC_MEMORY */
/*
File local variables
*/
static va_list ap;
static char utilbuf[myBUFSIZ];
static struct mm_cache mmap_data[MM_CACHESIZE];
static char cmdBuf[512];
#ifdef MEMORY_TRACING
#define MEMCACHESIZ 200000
static int memlast = -1;
static struct mm_cache memcache[MEMCACHESIZ];
void memCacheDump();
#endif /* MEMORY_TRACING */
/**
* \brief Check if given path is a directory
* \param dpath Path to check
* \return True if path is a directory, false otherwise
*/
int isDIR(char *dpath)
{
#ifdef PROC_TRACE
traceFunc("== isDIR(%s)\n", dpath);
#endif /* PROC_TRACE */
return(isINODE(dpath, S_IFDIR));
}
/**
* \brief Check if given file is empty
* \param fpath Path of file to check
* \return True if file is empty, false otherwise
* \sa isFILE()
*/
int isEMPTYFILE(char *fpath)
{
#ifdef PROC_TRACE
traceFunc("== isEMPTYFILE(%s)\n", fpath);
#endif /* PROC_TRACE */
if (!isFILE(fpath)) {
return(0);
}
return(cur.stbuf.st_size == 0);
}
/**
* \brief Check if given path is a Block device
* \param bpath Path to check
* \return True if path is a block device, false otherwise
* \sa isINODE()
*/
int isBLOCK(char *bpath)
{
#ifdef PROC_TRACE
traceFunc("== isBLOCK(%s)\n", bpath);
#endif /* PROC_TRACE */
return(isINODE(bpath, S_IFBLK));
}
/**
* \brief Check if given path is a character device
* \param cpath Path to check
* \return True if path is a character device, false otherwise
* \sa isINODE()
*/
int isCHAR(char *cpath)
{
#ifdef PROC_TRACE
traceFunc("== isCHAR(%s)\n", cpath);
#endif /* PROC_TRACE */
return(isINODE(cpath, S_IFCHR));
}
/**
* \brief Check if given path is a pipe
* \param ppath Path to check
* \return True if path is a pipe, false otherwise
* \sa isINODE()
*/
int isPIPE(char *ppath)
{
#ifdef PROC_TRACE
traceFunc("== isPIPE(%s)\n", ppath);
#endif /* PROC_TRACE */
return(isINODE(ppath, S_IFIFO));
}
/**
* \brief Check if given path is a symbolic link
* \param spath Path to check
* \return True if path is a symbolic link, false otherwise
* \sa isINODE()
*/
int isSYMLINK(char *spath)
{
#ifdef PROC_TRACE
traceFunc("== isSYMLINK(%s)\n", spath);
#endif /* PROC_TRACE */
return(isINODE(spath, S_IFLNK));
}
/**
* \brief Check for a inode against a flag
* \param ipath Path of inode
* \param typ Flag to check against to
* \return Return true if inode matches with the flag, false otherwise
*/
int isINODE(char *ipath, int typ)
{
int ret;
char sErrorBuf[1024];
#ifdef PROC_TRACE
traceFunc("== isINODE(%s, 0x%x)\n", ipath, typ);
#endif /* PROC_TRACE */
if ((ret = stat(ipath, &cur.stbuf)) < 0) {
/*
IF we're trying to stat() a file that doesn't exist,
that's no biggie.
Any other error, however, is fatal.
*/
if (errno == ENOENT) {
return 0;
}
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_ERROR("Error: %s getting stat on file: %s", sErrorBuf, ipath)
}
if (typ == 0) {
return(1);
}
return((int)(cur.stbuf.st_mode & S_IFMT & typ));
}
/**
* \brief Check if a relocation target is accessible
* \param basename Base name of the original target
* \return Path of the new target, NULL on failure
*/
char *newReloTarget(char *basename)
{
static char newpath[myBUFSIZ];
int i;
#ifdef PROC_TRACE
traceFunc("== newReloTarget(%s)\n", basename);
#endif /* PROC_TRACE */
for (i = 0; i < MAX_RENAME; i++) {
(void) sprintf(newpath, "%s_%s-renamed.%03d", basename, gl.progName, i);
if (access(newpath, F_OK) && errno == ENOENT) {
break;
}
}
if (i == MAX_RENAME) {
LOG_FATAL("%s: no suitable relocation target (%d tries)", basename, i)
Bail(-__LINE__);
}
return(newpath);
}
#ifdef MEMORY_TRACING
/**
* \brief memAlloc is a front-end to calloc() that dies on allocation-failure
* thus, we don't have to always check the return value from calloc()
* in the guts of the application code; we die here if alloc fails.
*/
char *memAllocTagged(int size, char *name)
{
void *ptr;
sErrorBuf[1024];
/*
* we don't track memory allocated; we front-end for errors and return
* the pointer we were given.
*/
#if defined(PROC_TRACE) || defined(MEM_ACCT)
traceFunc("== memAllocTagged(%d, \"%s\")\n", size, name);
#endif /* PROC_TRACE || MEM_ACCT */
if (size < 1) {
LOG_FATAL("Cannot alloc %d bytes!", size)
Bail(-__LINE__);
}
if (++memlast == MEMCACHESIZ) {
LOG_FATAL("*** memAllocTagged: out of memcache entries")
Bail(-__LINE__);
}
#ifdef USE_CALLOC
if ((ptr = calloc((size_t) 1, (size_t) size)) == (void *) NULL) {
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("calloc for %s, error: %s", name, sErrorBuf)
Bail(-__LINE__);
}
#else /* not USE_CALLOC */
if ((ptr = malloc((size_t) size)) == (void *) NULL) {
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("malloc for %s, error: %s", name, sErrorBuf)
Bail(-__LINE__);
}
(void) memset(ptr, 0, (size_t) size);
#endif /* not USE_CALLOC */
#if DEBUG > 3 || defined(MEM_ACCT)
printf("+%p:%p=(%d)\n", ptr, ptr+size-1, size);
#endif /* DEBUG > 3 || MEM_ACCT */
memcache[memlast].mmPtr = ptr;
memcache[memlast].size = size;
(void) strcpy(memcache[memlast].label, name);
#ifdef MEM_ACCT
printf("memAllocTagged(%d, \"%s\") == %p [entry %04d]\n", size, name, ptr,
memlast);
/* memCacheDump("post-memAllocTagged:"); */
#endif /* MEM_ACCT */
return(ptr);
}
void memFreeTagged(void *ptr, char *note)
{
struct mm_cache *mmp;
int i;
#if defined(PROC_TRACE) || defined(MEM_ACCT)
traceFunc("== memFree(%p, \"%s\")\n", ptr, note);
#endif /* PROC_TRACE || MEM_ACCT */
#ifdef MEMORY_TRACING
DEBUG("mprobe(%p)\n", ptr)
mprobe(ptr); /* see if glibc still likes this memory */
#endif /* MEMORY_TRACING */
for (mmp = memcache, i = 0; i <= memlast; mmp++, i++) {
if (mmp->mmPtr == ptr) {
#ifdef MEM_ACCT
printf("memFree(%p, \"%s\") is entry %04d (%d bytes)\n", ptr, note, i,
mmp->size);
#endif /* MEM_ACCT */
break;
}
}
if (i > memlast) {
LOG_FATAL("Could not locate %p to free!", ptr)
Bail(-__LINE__);
}
free(ptr);
#if DEBUG > 3 || defined(MEM_ACCT)
printf("-%p=(%d)\n", ptr, mmp->size);
#endif /* DEBUG > 3 || MEM_ACCT */
if (i != memlast) {
(void) memmove(&memcache[i], &memcache[i+1],
(memlast-i)*sizeof(struct mm_cache));
}
memset(&memcache[memlast], 0, sizeof(struct mm_cache));
memlast--;
#ifdef MEM_ACCT
memCacheDump("post-memFree:");
#endif /* MEM_ACCT */
return;
}
void memCacheDump(char *s)
{
struct mm_cache *m;
static int first = 1;
int i, start;
/* */
if (s != NULL_STR) {
printf("%s\n", s);
}
if (memlast < 0) {
printf("%%%%%% mem-cache is EMPTY\n");
return;
}
start = (memlast > 50 ? memlast-50 : 0);
printf("%%%%%% mem-cache @ %p [last=%d]\n", memcache, memlast);
for (m = memcache+start, i = start; i <= memlast; m++, i++) {
printf("mem-entry %04d: %p (%d) - %s\n", i, m->mmPtr,
m->size, m->label);
if (!first) {
printf("... \"%s\"\n", m->mmPtr);
}
}
printf("%%%%%% mem-cache END\n");
if (first) {
first --;
}
return;
}
#endif /* MEMORY_TRACING */
/**
* \brief Find Begin of Line in a string
*
* The function starts from the starting position and tracks backward till a
* EOL is hit.
* \param s Starting position in string to scan
* \param upperLimit Upper limit of the string
* \return - Location of BOL if found
* - If we hit upperLimit, return upper limit
* - NULL otherwise
*/
char *findBol(char *s, char *upperLimit)
{
char *cp;
#ifdef PROC_TRACE
traceFunc("== findBol(%p, %p)\n", s, upperLimit);
#endif /* PROC_TRACE */
if (s == NULL_STR || upperLimit == NULL_STR) {
return(NULL_STR);
}
for (cp = s; cp > upperLimit; cp--) {
#ifdef DEBUG
DEBUG("cp %p upperLimit %p\n", cp, upperLimit)
#endif /* DEBUG */
if (isEOL(*cp)) {
#ifdef DEBUG
DEBUG("Got it! BOL == %p\n", cp)
#endif /* DEBUG */
return((char*)(cp+1));
}
}
if (cp == upperLimit) {
#ifdef DEBUG
DEBUG("AT upperLimit %p\n", upperLimit);
#endif /* DEBUG */
return(upperLimit);
}
return(NULL_STR);
}
/**
* \brief Find first ROL in a string
* \param s Starting position in a string
* \return - Position of first EOL hit
* - Last element of the string if EOL not found
* - NULL otherwise
*/
char *findEol(char *s)
{
char *cp;
#ifdef PROC_TRACE
traceFunc("== findEol(%p)\n", s);
#endif /* PROC_TRACE */
if (s == NULL_STR) {
return(NULL_STR);
}
for (cp = s; *cp != NULL_CHAR; cp++) {
if (isEOL(*cp)) {
return(cp); /* return ptr to EOL or NULL */
}
}
if (*cp == NULL_CHAR) {
return(cp);
}
return(NULL_STR);
}
/**
* \brief Rename an inode at oldpath to newpath
*
* The functions calls rename() first. If it fails, another try is done using
* `mv` command.
* \note If everything fails, function prints an error and call Bail()
* \param oldpath Original path to be renamed
* \param newpath New path of the inode
*/
void renameInode(char *oldpath, char *newpath)
{
int err = 0;
char sErrorBuf[1024];
/*
* we die here if the unlink() fails.
*/
#if defined(PROC_TRACE) || defined(UNPACK_DEBUG)
traceFunc("== renameInode(%s, %s)\n", oldpath, newpath);
#endif /* PROC_TRACE || UNPACK_DEBUG */
#ifdef DEBUG
(void) mySystem("ls -ldi '%s'", oldpath);
#endif /* DEBUG */
if (rename(oldpath, newpath) < 0) {
if (errno == EXDEV) {
err = mySystem("mv '%s' %s", oldpath, newpath);
}
else {
err = 1;
}
if (err) {
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("rename(%s, %s) error: %s", oldpath, newpath, sErrorBuf)
Bail(-__LINE__);
}
}
#ifdef DEBUG
(void) mySystem("ls -ldi %s", newpath);
#endif /* DEBUG */
return;
}
/**
* \brief Change inode mode bits
*
* \note The function prints error and call Bail() if chmod() fails
* \param pathname Path of the inode
* \param mode New mode bits (e.g. 0660)
*/
void chmodInode(char *pathname, int mode)
{
char sErrorBuf[1024];
/*
* we die here if the chmod() fails.
*/
#if defined(PROC_TRACE) || defined(UNPACK_DEBUG)
traceFunc("== chmodInode(%s, 0%o)\n", pathname, mode);
#endif /* PROC_TRACE || UNPACK_DEBUG */
if (chmod(pathname, mode) < 0) {
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("chmod(\"%s\", 0%o) error: %s", pathname, mode, sErrorBuf)
Bail(-__LINE__);
}
return;
}
/**
* \brief Open a file and return the file pointer
* \note The function prints error and call Bail() on failure
* \param pathname Path of the file to open
* \param mode Mode in which the file should be opened
* \return File pointer
*/
FILE *fopenFile(char *pathname, char *mode)
{
FILE *fp;
char sErrorBuf[1024];
/*
* we don't track directories opened; we front-end and return what's
* given to us. we die here if the fopen() fails.
*/
#ifdef PROC_TRACE
traceFunc("== fopenFile(%s, \"%s\")\n", pathname, mode);
#endif /* PROC_TRACE */
if ((fp = fopen(pathname, mode)) == (FILE *) NULL) {
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("fopen(%s) error: %s", pathname, sErrorBuf);
Bail(-__LINE__);
}
return(fp);
}
/*
*
Save for now, could be useful for debugging
static void printListToFile(list_t *l, char *filename, char *mode) {
FILE *fp;
item_t *ip;
fp = fopenFile(filename, mode);
while ((ip = listIterate(l)) != NULL_ITEM) {
fprintf(fp, "%s\n", ip->str);
}
(void) fclose(fp);
return;
}
*/
/**
* \brief Open a process pipe using popen()
* \note The function prints error and call Bail() on failure
* \param command Command to open a pipe to
* \param mode Mode of the pipe
* \return File pointer to the opened pipe
*/
FILE *popenProc(char *command, char *mode)
{
FILE *pp;
char sErrorBuf[1024];
/*
* we don't track directories opened; we front-end and return what's
* given to us. we die here if the popen() fails.
*/
#ifdef PROC_TRACE
traceFunc("== popenProc(\"%s\", %s)\n", command, mode);
#endif /* PROC_TRACE */
if ((pp = popen(command, mode)) == (FILE *) NULL) {
#ifdef MEMORY_TRACING
memCacheDump("Post-popen-failure:");
#endif /* MEMORY_TRACING */
strerror_r(errno, sErrorBuf, sizeof(sErrorBuf));
LOG_FATAL("popen(\"%s\") error: %s", command, sErrorBuf)
Bail(-__LINE__);
}
return(pp);
}
/**
* \brief VERY simple line count, does NOT have to be perfect!
* \param textp Pointer to string
* \return Number of lines found
*/
char *wordCount(char *textp)
{
static char wcbuf[64];
int lines;
char *cp;
#ifdef PROC_TRACE
traceFunc("== wordCount(%p)\n", textp);
#endif /* PROC_TRACE */
lines = 0;
for (cp = textp; *cp; cp++) {
switch (*cp) {
case '\f':
break;
case '\n':
case '\r':
case '\v':
lines++;
break;
case ' ':
case '\t':
break;
default:
break;
}
}
(void) sprintf(wcbuf, "%d lines", lines);
/*
* Save these values for use elsewhere, too.
*/
cur.nLines = lines;
return(wcbuf);
}
/**
* \brief Create a copy of a string
* \param s String to be copied
* \param label Label on the new memory
* \return New string
* \sa memAlloc()
*/
char *copyString(char *s, char *label)
{
char *cp;
int len;
#ifdef PROC_TRACE
traceFunc("== copyString(%p, \"%s\")\n", s, label);
#endif /* PROC_TRACE */
cp = memAlloc(len=(strlen(s)+1), label);
#ifdef DEBUG
printf("+CS: %d @ %p\n", len, cp);
#endif /* DEBUG */
(void) strcpy(cp, s);
return(cp);
}
/**
* \brief Get the basename from a file path
* \param path Path to the file
* \return Basename start pointer on the path
*/
char *pathBasename(char *path)
{
char *cp;
#ifdef PROC_TRACE
traceFunc("== pathBasename(\"%s\")\n", path);
#endif /* PROC_TRACE */
cp = strrchr(path, '/');
return(cp == NULL_STR ? path : (char *)(cp+1));
}
/**
* \brief Get occurrence of a regex in a given string pointer
*/
char *getInstances(char *textp, int size, int nBefore, int nAfter, char *regex,
int recordOffsets)
{
int i;
int notDone;
int buflen = 1;
static char *ibuf = NULL;
static int bufmax = 0;
char *sep = _REGEX(_UTIL_XYZZY);
item_t *p;
item_t *bp = 0;
char *fileeof;
char *start;
char *end;
char *curptr;
char *bufmark;
char save;
char *cp;
int newDataLen;
int regexFlags = REG_ICASE|REG_EXTENDED;
#if defined(PROC_TRACE) || defined(PHRASE_DEBUG) || defined(DOCTOR_DEBUG)
traceFunc("== getInstances(%p, %d, %d, %d, \"%s\", %d)\n", textp, size,
nBefore, nAfter, regex, recordOffsets);
#endif /* PROC_TRACE || PHRASE_DEBUG || DOCTOR_DEBUG */
if ((notDone = strGrep(regex, textp, regexFlags)) == 0) {
#ifdef PHRASE_DEBUG
printf("... no match: 1st strGrep()\n");
#endif /* PHRASE_DEBUG */
return(NULL_STR);
}
/*
* The global 'offsets list' is indexed by the seed/key (a regex) that we
* use for doctoring buffers... each entry will contain a list (containing
* the "paragraphs" that match the key) AND its size (e.g., # of 'chunks'),
* which also means, if there are N chunks, there are N-1 'xyzzy' separators.
*/
p = listGetItem(&cur.offList, regex);
p->seqNo = cur.offList.used;
p->nMatch = 0;
if (recordOffsets) {
if (p->bList) free(p->bList);
p->bList = (list_t *)memAlloc(sizeof(list_t), MTAG_LIST);
(void) sprintf(utilbuf, "\"%c%c%c%c%c%c%c%c%c%c\" match-list",
*regex, *(regex+1), *(regex+2), *(regex+3), *(regex+4),
*(regex+5), *(regex+6), *(regex+7), *(regex+8), *(regex+9));
#ifdef PHRASE_DEBUG
printf("Creating %s\n", utilbuf);
#endif /* PHRASE_DEBUG */
listInit(p->bList, 0, utilbuf); /* <- MEMORY LEAK from p->bList->items not freed */
#ifdef QA_CHECKS
p->val3++; /* sanity-check -- should never be >1 ! */
if (p->val3 > 1) {
LOG_FATAL("Called getInstances(%s) more than once", regex)
Bail(-__LINE__);
}
#endif /* QA_CHECKS */
}
#ifdef REUSE_STATIC_MEMORY
if (ibuf == NULL_STR) { /* first time, uninitialized */
ibuf = grepzone;
bufmax = sizeof(grepzone);
}
else if (ibuf != grepzone) {
memFree(ibuf, MTAG_DOUBLED); /* free the memory... */
ibuf = grepzone; /* ... and reset */
bufmax = sizeof(grepzone);
}
#else /* not REUSE_STATIC_MEMORY */
if (ibuf == NULL_STR) {
ibuf = memAlloc((bufmax = 1024*1024), MTAG_SEARCHBUF);
}
#endif /* not REUSE_STATIC_MEMORY */
*ibuf = NULL_CHAR;
bufmark = ibuf;
end = NULL_STR;
/*
* At this point, we know the string we're looking for is IN the file.
*/
#ifdef PHRASE_DEBUG
printf("getInstances: \"%s\" [#1] in buf [%d-%d]\n", regex,
cur.regm.rm_so, cur.regm.rm_eo-1);
printf("Really in the buffer: [");
for (cp = textp + cur.regm.rm_so; cp < (textp + cur.regm.rm_eo); cp++) {
printf("%c", *cp);
}
printf("]\n");
#endif /* PHRASE_DEBUG */
/*
* Find the start of the text line containing the "first" match.
* locate start of "$nBefore lines above pattern match"; go up to the
* text on the _previous_ line before we 'really start counting'
*/
curptr = textp;
fileeof = (char *) (textp+size);
while (notDone) { /* curptr is the 'current block' ptr */
p->nMatch++;
#ifdef PHRASE_DEBUG
printf("... found Match #%d\n", p->nMatch);
#endif /* PHRASE_DEBUG */
if (recordOffsets) {
(void) sprintf(utilbuf, "buf%05d", p->nMatch);
bp = listGetItem(p->bList, utilbuf);
}
start = findBol(curptr + cur.regm.rm_so, textp);
/*
* Go to the beggining of the current line and, if nBefore > 0, go 'up'
* in the text "$nBefore" lines. Count 2-consecutive EOL-chars as one
* line since some text files use <CR><LF> as line-terminators.
*/
if ((nBefore > 0) && (start > textp)) {
for (i = 0; (i < nBefore) && (start > textp); i++) {
start -= 2;
if ((start > textp) && isEOL(*start)) {
start--;
}
if (start > textp) {
start = findBol(start, textp);
}
#ifdef PHRASE_DEBUG
DEBUG("start = %p\n", start)
#endif /* PHRASE_DEBUG */
}
}
if (recordOffsets) {
bp->bStart = start-textp;
}
/*
* Now do what "grep -A $nAfter _filename+" does.
*****
* If nAfter == 0, we want the end of the current line.
*****
* If nAfter > 0, locate the end of the line of LAST occurrence of the
* string within the next $nAfter lines. Not well-worded, you say?
*****
* E.g., if we're saving SIX lines below and we see our pattern 4 lines
* below the first match then we'll save 10 lines from the first match.
* And to continue this example, if we then see our pattern 9 lines from
* the start of the buffer (since we're looking up to 10 lines now), we
* will save *15* lines. Repeat until the last 6 lines we save DO NOT
* have our pattern.
*/
do {
curptr += cur.regm.rm_eo;
end = findEol(curptr);
if (end < fileeof) {
end++; /* first char past end-of-line */
}
if (nAfter > 0) {
for (i = 0; end < fileeof; end++) {
if (isEOL(*end)) { /* double-EOL */
end++; /* <CR><LF>? */
}
end = findEol(end);
if (end == NULL_STR) {
LOG_FATAL("lost the end-of-line")
Bail(-__LINE__);
}
if (*end == NULL_CHAR) {
break; /* EOF == done */
}
if (++i == nAfter) {
break;
}
}
if ((end < fileeof) && *end) {
end++; /* past newline-char */
}
}
#ifdef PHRASE_DEBUG
printf("Snippet, with %d lines below:\n----\n", nAfter);
for (cp = start; cp < end; cp++) {
printf("%c", *cp);
}
printf("====\n");
#endif /* PHRASE_DEBUG */
notDone = strGrep(regex, curptr, regexFlags);
if (notDone) { /* another match? */
#ifdef PHRASE_DEBUG
printf("... next match @ %d:%d (end=%d)\n",
curptr - textp + cur.regm.rm_so,
curptr - textp + cur.regm.rm_eo - 1, end - textp);
#endif /* PHRASE_DEBUG */
#ifdef QA_CHECKS
if ((curptr + cur.regm.rm_eo) > fileeof) {
Assert(YES, "Too far into file!");
}
#endif /* QA_CHECKS */
/* next match OUTSIDE the text we've already saved? */
if ((curptr + cur.regm.rm_eo) > end) {
break;
}
/* else, next match IS within the text we're looking at! */
}
} while (notDone);
/*
* Add this block of text to our buffer. If 'notdone' is true, there's
* at least one more block of text that goes in the buffer, so add the
* block-o-text-separator, too. And, make sure we don't overflow our
* buffer (BEFORE we modify it); we don't KNOW how much text to expect!
*/
save = *end;
*end = NULL_CHAR; /* char PAST the newline! */
if (recordOffsets) {
bp->bLen = end-start;
bp->buf = copyString(start, MTAG_TEXTPARA);
bp->bDocLen = 0;
#ifdef PHRASE_DEBUG
printf("%s starts @%d, len %d ends [%c%c%c%c%c%c%c]\n",
utilbuf, bp->bStart, bp->bLen, *(end-8), *(end-7),
*(end-6), *(end-5), *(end-4), *(end-3), *(end-2));
#endif /* PHRASE_DEBUG */
}
newDataLen = end-start+(notDone ? strlen(sep)+1 : 0);
while (buflen+newDataLen > bufmax) {
char *new;
#ifdef QA_CHECKS
Assert(NO, "data(%d) > bufmax(%d)", buflen+newDataLen,
bufmax);
#endif /* QA_CHECKS */
bufmax *= 2;
#ifdef MEMSTATS
printf("... DOUBLE search-pattern buffer (%d -> %d)\n",
bufmax/2, bufmax);
#endif /* MEMSTATS */
new = memAlloc(bufmax, MTAG_DOUBLED);
(void) memcpy(new, ibuf, buflen);
#if 0
printf("REPLACING buf %p(%d) with %p(%d)\n", ibuf,
bufmax/2, new, bufmax);
#endif
#ifdef REUSE_STATIC_MEMORY
if (ibuf != grepzone) {
memFree(ibuf, MTAG_TOOSMALL);
}
#else /* not REUSE_STATIC_MEMORY */
memFree(ibuf, MTAG_TOOSMALL);
#endif /* not REUSE_STATIC_MEMORY */
ibuf = new;
}
cp = bufmark = ibuf+buflen-1; /* where the NULL is _now_ */
buflen += newDataLen; /* new end-of-data ptr */
bufmark += sprintf(bufmark, "%s", start);
if (notDone) {
bufmark += sprintf(bufmark, "%s\n", sep);
}
/*
* Some files use ^M as a line-terminator, so we need to convert those
* control-M's to 'regular newlines' in case we need to use the regex
* stuff on this buffer; the regex library apparently doesn't have a
* flag for interpretting ^M as end-of-line character.
*/
while (*cp) {
if (*cp == '\r') { /* '\015'? */
*cp = '\n'; /* '\012'! */
}
cp++;
}
*end = save;
#ifdef PHRASE_DEBUG
printf("Loop end, BUF IS NOW: [\"%s\":%d]\n----\n%s====\n",
regex, strlen(ibuf), ibuf);
#endif /* PHRASE_DEBUG */
}
#if defined(PHRASE_DEBUG) || defined(DOCTOR_DEBUG)
printf("getInstances(\"%s\"): Found %d bytes of data...\n", regex,
buflen-1);
#endif /* PHRASE_DEBUG || DOCTOR_DEBUG */
#ifdef PHRASE_DEBUG
printf("getInstances(\"%s\"): buffer %p --------\n%s\n========\n",
regex, ibuf, ibuf);
#endif /* PHRASE_DEBUG */
return(ibuf);
}
/**
* \brief Get the current date
* \note The function prints a fatal log and call Bail() if ctime_r() fails
* \return Current date
*/
char *curDate()
{
static char datebuf[32];
char *cp;
time_t thyme;
(void) time(&thyme);
(void) ctime_r(&thyme, datebuf);
if ((cp = strrchr(datebuf, '\n')) == NULL_STR) {
LOG_FATAL("Unexpected time format from ctime_r()!")
Bail(-__LINE__);
}
*cp = NULL_CHAR;
return(datebuf);
}
#ifdef MEMSTATS
void memStats(char *s)
{
static int first = 1;
static char mbuf[128];
if (first) {
first = 0;
sprintf(mbuf, "grep VmRSS /proc/%d/status", getpid());
}
if (s && *s) {
int i;
printf("%s: ", s);
for (i = (int) (strlen(s)+2); i < 50; i++) {
printf(" ");
}
}
(void) mySystem(mbuf);
#if 0
system("grep Vm /proc/self/status");
system("grep Brk /proc/self/status");
#endif
}
#endif /* MEMSTATS */
/**
* \brief Create symbolic links for a given path in current directory
* \param path Path to the inode
*/
void makeSymlink(char *path)
{
#if defined(PROC_TRACE) || defined(UNPACK_DEBUG)
traceFunc("== makeSymlink(%s)\n", path);
#endif /* PROC_TRACE || UNPACK_DEBUG */
(void) sprintf(cmdBuf, ".%s", strrchr(path, '/'));
if (symlink(path, cmdBuf) < 0) {
perror(cmdBuf);
LOG_FATAL("Failed: symlink(%s, %s)", path, cmdBuf)
Bail(-__LINE__);
}
return;
}
/**
* \brief CDB -- Need to review this code, particularly for the use of an
* external file (Nomos.strings.txt). Despite the fact that variable
* is named debugStr, the file appears to be used for more than just
* debugging.
*
* Although it might be the case that it only gets called from debug
* code. It does not appear to be called during a few test runs of
* normal file scans that I tried.
*/
void printRegexMatch(int n, int cached)
{
int save_so;