-
Notifications
You must be signed in to change notification settings - Fork 552
/
util.c
6642 lines (5830 loc) · 179 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
/* util.c
*
* Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
* 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*/
/*
* 'Very useful, no doubt, that was to Saruman; yet it seems that he was
* not content.' --Gandalf to Pippin
*
* [p.598 of _The Lord of the Rings_, III/xi: "The Palantír"]
*/
/* This file contains assorted utility routines.
* Which is a polite way of saying any stuff that people couldn't think of
* a better place for. Amongst other things, it includes the warning and
* dieing stuff, plus wrappers for malloc code.
*/
#include "EXTERN.h"
#define PERL_IN_UTIL_C
#include "perl.h"
#include "reentr.h"
#if defined(USE_PERLIO)
#include "perliol.h" /* For PerlIOUnix_refcnt */
#endif
#ifndef PERL_MICRO
#include <signal.h>
#ifndef SIG_ERR
# define SIG_ERR ((Sighandler_t) -1)
#endif
#endif
#include <math.h>
#include <stdlib.h>
#ifdef __Lynx__
/* Missing protos on LynxOS */
int putenv(char *);
#endif
#ifdef __amigaos__
# include "amigaos4/amigaio.h"
#endif
#ifdef HAS_SELECT
# ifdef I_SYS_SELECT
# include <sys/select.h>
# endif
#endif
#ifdef USE_C_BACKTRACE
# ifdef I_BFD
# define USE_BFD
# ifdef PERL_DARWIN
# undef USE_BFD /* BFD is useless in OS X. */
# endif
# ifdef USE_BFD
# include <bfd.h>
# endif
# endif
# ifdef I_DLFCN
# include <dlfcn.h>
# endif
# ifdef I_EXECINFO
# include <execinfo.h>
# endif
#endif
#ifdef PERL_DEBUG_READONLY_COW
# include <sys/mman.h>
#endif
#define FLUSH
/* NOTE: Do not call the next three routines directly. Use the macros
* in handy.h, so that we can easily redefine everything to do tracking of
* allocated hunks back to the original New to track down any memory leaks.
* XXX This advice seems to be widely ignored :-( --AD August 1996.
*/
#if defined (DEBUGGING) || defined(PERL_IMPLICIT_SYS) || defined (PERL_TRACK_MEMPOOL)
# define ALWAYS_NEED_THX
#endif
#if defined(PERL_TRACK_MEMPOOL) && defined(PERL_DEBUG_READONLY_COW)
static void
S_maybe_protect_rw(pTHX_ struct perl_memory_debug_header *header)
{
if (header->readonly
&& mprotect(header, header->size, PROT_READ|PROT_WRITE))
Perl_warn(aTHX_ "mprotect for COW string %p %lu failed with %d",
header, header->size, errno);
}
static void
S_maybe_protect_ro(pTHX_ struct perl_memory_debug_header *header)
{
if (header->readonly
&& mprotect(header, header->size, PROT_READ))
Perl_warn(aTHX_ "mprotect RW for COW string %p %lu failed with %d",
header, header->size, errno);
}
# define maybe_protect_rw(foo) S_maybe_protect_rw(aTHX_ foo)
# define maybe_protect_ro(foo) S_maybe_protect_ro(aTHX_ foo)
#else
# define maybe_protect_rw(foo) NOOP
# define maybe_protect_ro(foo) NOOP
#endif
#if defined(PERL_TRACK_MEMPOOL) || defined(PERL_DEBUG_READONLY_COW)
/* Use memory_debug_header */
# define USE_MDH
# if (defined(PERL_POISON) && defined(PERL_TRACK_MEMPOOL)) \
|| defined(PERL_DEBUG_READONLY_COW)
# define MDH_HAS_SIZE
# endif
#endif
/* paranoid version of system's malloc() */
Malloc_t
Perl_safesysmalloc(MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
dSAVEDERRNO;
#ifdef USE_MDH
if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
goto out_of_memory;
size += PERL_MEMORY_DEBUG_HEADER_SIZE;
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0)
Perl_croak_nocontext("panic: malloc, size=%" UVuf, (UV) size);
#endif
if (!size) size = 1; /* malloc(0) is NASTY on our system */
SAVE_ERRNO;
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
#else
ptr = (Malloc_t)PerlMem_malloc(size?size:1);
#endif
PERL_ALLOC_CHECK(ptr);
if (ptr != NULL) {
#ifdef USE_MDH
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
#endif
#ifdef PERL_POISON
PoisonNew(((char *)ptr), size, char);
#endif
#ifdef PERL_TRACK_MEMPOOL
header->interpreter = aTHX;
/* Link us into the list. */
header->prev = &PL_memory_debug_header;
header->next = PL_memory_debug_header.next;
PL_memory_debug_header.next = header;
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
# ifdef PERL_DEBUG_READONLY_COW
header->readonly = 0;
# endif
#endif
#ifdef MDH_HAS_SIZE
header->size = size;
#endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) malloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
/* malloc() can modify errno() even on success, but since someone
writing perl code doesn't have any control over when perl calls
malloc() we need to hide that.
*/
RESTORE_ERRNO;
}
else {
#ifdef USE_MDH
out_of_memory:
#endif
{
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
ptr = NULL;
else
croak_no_mem();
}
}
return ptr;
}
/* paranoid version of system's realloc() */
Malloc_t
Perl_safesysrealloc(Malloc_t where,MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
#ifdef PERL_DEBUG_READONLY_COW
const MEM_SIZE oldsize = where
? ((struct perl_memory_debug_header *)((char *)where - PERL_MEMORY_DEBUG_HEADER_SIZE))->size
: 0;
#endif
if (!size) {
safesysfree(where);
ptr = NULL;
}
else if (!where) {
ptr = safesysmalloc(size);
}
else {
dSAVE_ERRNO;
#ifdef USE_MDH
where = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
if (size + PERL_MEMORY_DEBUG_HEADER_SIZE < size)
goto out_of_memory;
size += PERL_MEMORY_DEBUG_HEADER_SIZE;
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)where;
# ifdef PERL_TRACK_MEMPOOL
if (header->interpreter != aTHX) {
Perl_croak_nocontext("panic: realloc from wrong pool, %p!=%p",
header->interpreter, aTHX);
}
assert(header->next->prev == header);
assert(header->prev->next == header);
# ifdef PERL_POISON
if (header->size > size) {
const MEM_SIZE freed_up = header->size - size;
char *start_of_freed = ((char *)where) + size;
PoisonFree(start_of_freed, freed_up, char);
}
# endif
# endif
# ifdef MDH_HAS_SIZE
header->size = size;
# endif
}
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0)
Perl_croak_nocontext("panic: realloc, size=%" UVuf, (UV)size);
#endif
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, size, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
Copy(where,ptr,oldsize < size ? oldsize : size,char);
if (munmap(where, oldsize)) {
perror("munmap failed");
abort();
}
#else
ptr = (Malloc_t)PerlMem_realloc(where,size);
#endif
PERL_ALLOC_CHECK(ptr);
/* MUST do this fixup first, before doing ANYTHING else, as anything else
might allocate memory/free/move memory, and until we do the fixup, it
may well be chasing (and writing to) free memory. */
if (ptr != NULL) {
#ifdef PERL_TRACK_MEMPOOL
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
# ifdef PERL_POISON
if (header->size < size) {
const MEM_SIZE fresh = size - header->size;
char *start_of_fresh = ((char *)ptr) + size;
PoisonNew(start_of_fresh, fresh, char);
}
# endif
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
maybe_protect_rw(header->prev);
header->prev->next = header;
maybe_protect_ro(header->prev);
#endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
/* realloc() can modify errno() even on success, but since someone
writing perl code doesn't have any control over when perl calls
realloc() we need to hide that.
*/
RESTORE_ERRNO;
}
/* In particular, must do that fixup above before logging anything via
*printf(), as it can reallocate memory, which can cause SEGVs. */
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) rfree\n",PTR2UV(where),(long)PL_an++));
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) realloc %ld bytes\n",PTR2UV(ptr),(long)PL_an++,(long)size));
if (ptr == NULL) {
#ifdef USE_MDH
out_of_memory:
#endif
{
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
ptr = NULL;
else
croak_no_mem();
}
}
}
return ptr;
}
/* safe version of system's free() */
Free_t
Perl_safesysfree(Malloc_t where)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
DEBUG_m( PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) free\n",PTR2UV(where),(long)PL_an++));
if (where) {
#ifdef USE_MDH
Malloc_t where_intrn = (Malloc_t)((char*)where-PERL_MEMORY_DEBUG_HEADER_SIZE);
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)where_intrn;
# ifdef MDH_HAS_SIZE
const MEM_SIZE size = header->size;
# endif
# ifdef PERL_TRACK_MEMPOOL
if (header->interpreter != aTHX) {
Perl_croak_nocontext("panic: free from wrong pool, %p!=%p",
header->interpreter, aTHX);
}
if (!header->prev) {
Perl_croak_nocontext("panic: duplicate free");
}
if (!(header->next))
Perl_croak_nocontext("panic: bad free, header->next==NULL");
if (header->next->prev != header || header->prev->next != header) {
Perl_croak_nocontext("panic: bad free, ->next->prev=%p, "
"header=%p, ->prev->next=%p",
header->next->prev, header,
header->prev->next);
}
/* Unlink us from the chain. */
maybe_protect_rw(header->next);
header->next->prev = header->prev;
maybe_protect_ro(header->next);
maybe_protect_rw(header->prev);
header->prev->next = header->next;
maybe_protect_ro(header->prev);
maybe_protect_rw(header);
# ifdef PERL_POISON
PoisonNew(where_intrn, size, char);
# endif
/* Trigger the duplicate free warning. */
header->next = NULL;
# endif
# ifdef PERL_DEBUG_READONLY_COW
if (munmap(where_intrn, size)) {
perror("munmap failed");
abort();
}
# endif
}
#else
Malloc_t where_intrn = where;
#endif /* USE_MDH */
#ifndef PERL_DEBUG_READONLY_COW
PerlMem_free(where_intrn);
#endif
}
}
/* safe version of system's calloc() */
Malloc_t
Perl_safesyscalloc(MEM_SIZE count, MEM_SIZE size)
{
#ifdef ALWAYS_NEED_THX
dTHX;
#endif
Malloc_t ptr;
#if defined(USE_MDH) || defined(DEBUGGING)
MEM_SIZE total_size = 0;
#endif
/* Even though calloc() for zero bytes is strange, be robust. */
if (size && (count <= MEM_SIZE_MAX / size)) {
#if defined(USE_MDH) || defined(DEBUGGING)
total_size = size * count;
#endif
}
else
croak_memory_wrap();
#ifdef USE_MDH
if (PERL_MEMORY_DEBUG_HEADER_SIZE <= MEM_SIZE_MAX - (MEM_SIZE)total_size)
total_size += PERL_MEMORY_DEBUG_HEADER_SIZE;
else
croak_memory_wrap();
#endif
#ifdef DEBUGGING
if ((SSize_t)size < 0 || (SSize_t)count < 0)
Perl_croak_nocontext("panic: calloc, size=%" UVuf ", count=%" UVuf,
(UV)size, (UV)count);
#endif
#ifdef PERL_DEBUG_READONLY_COW
if ((ptr = mmap(0, total_size ? total_size : 1, PROT_READ|PROT_WRITE,
MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
perror("mmap failed");
abort();
}
#elif defined(PERL_TRACK_MEMPOOL)
/* Have to use malloc() because we've added some space for our tracking
header. */
/* malloc(0) is non-portable. */
ptr = (Malloc_t)PerlMem_malloc(total_size ? total_size : 1);
#else
/* Use calloc() because it might save a memset() if the memory is fresh
and clean from the OS. */
if (count && size)
ptr = (Malloc_t)PerlMem_calloc(count, size);
else /* calloc(0) is non-portable. */
ptr = (Malloc_t)PerlMem_calloc(count ? count : 1, size ? size : 1);
#endif
PERL_ALLOC_CHECK(ptr);
DEBUG_m(PerlIO_printf(Perl_debug_log, "0x%" UVxf ": (%05ld) calloc %zu x %zu = %zu bytes\n",PTR2UV(ptr),(long)PL_an++, count, size, total_size));
if (ptr != NULL) {
#ifdef USE_MDH
{
struct perl_memory_debug_header *const header
= (struct perl_memory_debug_header *)ptr;
# ifndef PERL_DEBUG_READONLY_COW
memset((void*)ptr, 0, total_size);
# endif
# ifdef PERL_TRACK_MEMPOOL
header->interpreter = aTHX;
/* Link us into the list. */
header->prev = &PL_memory_debug_header;
header->next = PL_memory_debug_header.next;
PL_memory_debug_header.next = header;
maybe_protect_rw(header->next);
header->next->prev = header;
maybe_protect_ro(header->next);
# ifdef PERL_DEBUG_READONLY_COW
header->readonly = 0;
# endif
# endif
# ifdef MDH_HAS_SIZE
header->size = total_size;
# endif
ptr = (Malloc_t)((char*)ptr+PERL_MEMORY_DEBUG_HEADER_SIZE);
}
#endif
return ptr;
}
else {
#ifndef ALWAYS_NEED_THX
dTHX;
#endif
if (PL_nomemok)
return NULL;
croak_no_mem();
}
}
/* These must be defined when not using Perl's malloc for binary
* compatibility */
#ifndef MYMALLOC
Malloc_t Perl_malloc (MEM_SIZE nbytes)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_malloc(nbytes);
}
Malloc_t Perl_calloc (MEM_SIZE elements, MEM_SIZE size)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_calloc(elements, size);
}
Malloc_t Perl_realloc (Malloc_t where, MEM_SIZE nbytes)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
return (Malloc_t)PerlMem_realloc(where, nbytes);
}
Free_t Perl_mfree (Malloc_t where)
{
#ifdef PERL_IMPLICIT_SYS
dTHX;
#endif
PerlMem_free(where);
}
#endif
/* copy a string up to some (non-backslashed) delimiter, if any.
* With allow_escape, converts \<delimiter> to <delimiter>, while leaves
* \<non-delimiter> as-is.
* Returns the position in the src string of the closing delimiter, if
* any, or returns fromend otherwise.
* This is the internal implementation for Perl_delimcpy and
* Perl_delimcpy_no_escape.
*/
static char *
S_delimcpy_intern(char *to, const char *toend, const char *from,
const char *fromend, int delim, I32 *retlen,
const bool allow_escape)
{
I32 tolen;
PERL_ARGS_ASSERT_DELIMCPY;
for (tolen = 0; from < fromend; from++, tolen++) {
if (allow_escape && *from == '\\' && from + 1 < fromend) {
if (from[1] != delim) {
if (to < toend)
*to++ = *from;
tolen++;
}
from++;
}
else if (*from == delim)
break;
if (to < toend)
*to++ = *from;
}
if (to < toend)
*to = '\0';
*retlen = tolen;
return (char *)from;
}
char *
Perl_delimcpy(char *to, const char *toend, const char *from, const char *fromend, int delim, I32 *retlen)
{
PERL_ARGS_ASSERT_DELIMCPY;
return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 1);
}
char *
Perl_delimcpy_no_escape(char *to, const char *toend, const char *from,
const char *fromend, int delim, I32 *retlen)
{
PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
return S_delimcpy_intern(to, toend, from, fromend, delim, retlen, 0);
}
/*
=head1 Miscellaneous Functions
=for apidoc ninstr
Find the first (leftmost) occurrence of a sequence of bytes within another
sequence. This is the Perl version of C<strstr()>, extended to handle
arbitrary sequences, potentially containing embedded C<NUL> characters (C<NUL>
is what the initial C<n> in the function name stands for; some systems have an
equivalent, C<memmem()>, but with a somewhat different API).
Another way of thinking about this function is finding a needle in a haystack.
C<big> points to the first byte in the haystack. C<big_end> points to one byte
beyond the final byte in the haystack. C<little> points to the first byte in
the needle. C<little_end> points to one byte beyond the final byte in the
needle. All the parameters must be non-C<NULL>.
The function returns C<NULL> if there is no occurrence of C<little> within
C<big>. If C<little> is the empty string, C<big> is returned.
Because this function operates at the byte level, and because of the inherent
characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the
needle and the haystack are strings with the same UTF-8ness, but not if the
UTF-8ness differs.
=cut
*/
char *
Perl_ninstr(const char *big, const char *bigend, const char *little, const char *lend)
{
PERL_ARGS_ASSERT_NINSTR;
#ifdef HAS_MEMMEM
return ninstr(big, bigend, little, lend);
#else
if (little >= lend)
return (char*)big;
{
const char first = *little;
bigend -= lend - little++;
OUTER:
while (big <= bigend) {
if (*big++ == first) {
const char *s, *x;
for (x=big,s=little; s < lend; x++,s++) {
if (*s != *x)
goto OUTER;
}
return (char*)(big-1);
}
}
}
return NULL;
#endif
}
/*
=head1 Miscellaneous Functions
=for apidoc rninstr
Like C<L</ninstr>>, but instead finds the final (rightmost) occurrence of a
sequence of bytes within another sequence, returning C<NULL> if there is no
such occurrence.
=cut
*/
char *
Perl_rninstr(const char *big, const char *bigend, const char *little, const char *lend)
{
const char *bigbeg;
const I32 first = *little;
const char * const littleend = lend;
PERL_ARGS_ASSERT_RNINSTR;
if (little >= littleend)
return (char*)bigend;
bigbeg = big;
big = bigend - (littleend - little++);
while (big >= bigbeg) {
const char *s, *x;
if (*big-- != first)
continue;
for (x=big+2,s=little; s < littleend; /**/ ) {
if (*s != *x)
break;
else {
x++;
s++;
}
}
if (s >= littleend)
return (char*)(big+1);
}
return NULL;
}
/* As a space optimization, we do not compile tables for strings of length
0 and 1, and for strings of length 2 unless FBMcf_TAIL. These are
special-cased in fbm_instr().
If FBMcf_TAIL, the table is created as if the string has a trailing \n. */
/*
=head1 Miscellaneous Functions
=for apidoc fbm_compile
Analyzes the string in order to make fast searches on it using C<fbm_instr()>
-- the Boyer-Moore algorithm.
=cut
*/
void
Perl_fbm_compile(pTHX_ SV *sv, U32 flags)
{
const U8 *s;
STRLEN i;
STRLEN len;
U32 frequency = 256;
MAGIC *mg;
PERL_DEB( STRLEN rarest = 0 );
PERL_ARGS_ASSERT_FBM_COMPILE;
if (isGV_with_GP(sv) || SvROK(sv))
return;
if (SvVALID(sv))
return;
if (flags & FBMcf_TAIL) {
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL;
sv_catpvs(sv, "\n"); /* Taken into account in fbm_instr() */
if (mg && mg->mg_len >= 0)
mg->mg_len++;
}
if (!SvPOK(sv) || SvNIOKp(sv))
s = (U8*)SvPV_force_mutable(sv, len);
else s = (U8 *)SvPV_mutable(sv, len);
if (len == 0) /* TAIL might be on a zero-length string. */
return;
SvUPGRADE(sv, SVt_PVMG);
SvIOK_off(sv);
SvNOK_off(sv);
/* add PERL_MAGIC_bm magic holding the FBM lookup table */
assert(!mg_find(sv, PERL_MAGIC_bm));
mg = sv_magicext(sv, NULL, PERL_MAGIC_bm, &PL_vtbl_bm, NULL, 0);
assert(mg);
if (len > 2) {
/* Shorter strings are special-cased in Perl_fbm_instr(), and don't use
the BM table. */
const U8 mlen = (len>255) ? 255 : (U8)len;
const unsigned char *const sb = s + len - mlen; /* first char (maybe) */
U8 *table;
Newx(table, 256, U8);
memset((void*)table, mlen, 256);
mg->mg_ptr = (char *)table;
mg->mg_len = 256;
s += len - 1; /* last char */
i = 0;
while (s >= sb) {
if (table[*s] == mlen)
table[*s] = (U8)i;
s--, i++;
}
}
s = (const unsigned char*)(SvPVX_const(sv)); /* deeper magic */
for (i = 0; i < len; i++) {
if (PL_freq[s[i]] < frequency) {
PERL_DEB( rarest = i );
frequency = PL_freq[s[i]];
}
}
BmUSEFUL(sv) = 100; /* Initial value */
((XPVNV*)SvANY(sv))->xnv_u.xnv_bm_tail = cBOOL(flags & FBMcf_TAIL);
DEBUG_r(PerlIO_printf(Perl_debug_log, "rarest char %c at %" UVuf "\n",
s[rarest], (UV)rarest));
}
/*
=for apidoc fbm_instr
Returns the location of the SV in the string delimited by C<big> and
C<bigend> (C<bigend>) is the char following the last char).
It returns C<NULL> if the string can't be found. The C<sv>
does not have to be C<fbm_compiled>, but the search will not be as fast
then.
=cut
If SvTAIL(littlestr) is true, a fake "\n" was appended to to the string
during FBM compilation due to FBMcf_TAIL in flags. It indicates that
the littlestr must be anchored to the end of bigstr (or to any \n if
FBMrf_MULTILINE).
E.g. The regex compiler would compile /abc/ to a littlestr of "abc",
while /abc$/ compiles to "abc\n" with SvTAIL() true.
A littlestr of "abc", !SvTAIL matches as /abc/;
a littlestr of "ab\n", SvTAIL matches as:
without FBMrf_MULTILINE: /ab\n?\z/
with FBMrf_MULTILINE: /ab\n/ || /ab\z/;
(According to Ilya from 1999; I don't know if this is still true, DAPM 2015):
"If SvTAIL is actually due to \Z or \z, this gives false positives
if multiline".
*/
char *
Perl_fbm_instr(pTHX_ unsigned char *big, unsigned char *bigend, SV *littlestr, U32 flags)
{
unsigned char *s;
STRLEN l;
const unsigned char *little = (const unsigned char *)SvPV_const(littlestr,l);
STRLEN littlelen = l;
const I32 multiline = flags & FBMrf_MULTILINE;
bool valid = SvVALID(littlestr);
bool tail = valid ? cBOOL(SvTAIL(littlestr)) : FALSE;
PERL_ARGS_ASSERT_FBM_INSTR;
assert(bigend >= big);
if ((STRLEN)(bigend - big) < littlelen) {
if ( tail
&& ((STRLEN)(bigend - big) == littlelen - 1)
&& (littlelen == 1
|| (*big == *little &&
memEQ((char *)big, (char *)little, littlelen - 1))))
return (char*)big;
return NULL;
}
switch (littlelen) { /* Special cases for 0, 1 and 2 */
case 0:
return (char*)big; /* Cannot be SvTAIL! */
case 1:
if (tail && !multiline) /* Anchor only! */
/* [-1] is safe because we know that bigend != big. */
return (char *) (bigend - (bigend[-1] == '\n'));
s = (unsigned char *)memchr((void*)big, *little, bigend-big);
if (s)
return (char *)s;
if (tail)
return (char *) bigend;
return NULL;
case 2:
if (tail && !multiline) {
/* a littlestr with SvTAIL must be of the form "X\n" (where X
* is a single char). It is anchored, and can only match
* "....X\n" or "....X" */
if (bigend[-2] == *little && bigend[-1] == '\n')
return (char*)bigend - 2;
if (bigend[-1] == *little)
return (char*)bigend - 1;
return NULL;
}
{
/* memchr() is likely to be very fast, possibly using whatever
* hardware support is available, such as checking a whole
* cache line in one instruction.
* So for a 2 char pattern, calling memchr() is likely to be
* faster than running FBM, or rolling our own. The previous
* version of this code was roll-your-own which typically
* only needed to read every 2nd char, which was good back in
* the day, but no longer.
*/
unsigned char c1 = little[0];
unsigned char c2 = little[1];
/* *** for all this case, bigend points to the last char,
* not the trailing \0: this makes the conditions slightly
* simpler */
bigend--;
s = big;
if (c1 != c2) {
while (s < bigend) {
/* do a quick test for c1 before calling memchr();
* this avoids the expensive fn call overhead when
* there are lots of c1's */
if (LIKELY(*s != c1)) {
s++;
s = (unsigned char *)memchr((void*)s, c1, bigend - s);
if (!s)
break;
}
if (s[1] == c2)
return (char*)s;
/* failed; try searching for c2 this time; that way
* we don't go pathologically slow when the string
* consists mostly of c1's or vice versa.
*/
s += 2;
if (s > bigend)
break;
s = (unsigned char *)memchr((void*)s, c2, bigend - s + 1);
if (!s)
break;
if (s[-1] == c1)
return (char*)s - 1;
}
}
else {
/* c1, c2 the same */
while (s < bigend) {
if (s[0] == c1) {
got_1char:
if (s[1] == c1)
return (char*)s;
s += 2;
}
else {
s++;
s = (unsigned char *)memchr((void*)s, c1, bigend - s);
if (!s || s >= bigend)
break;
goto got_1char;
}
}
}
/* failed to find 2 chars; try anchored match at end without
* the \n */
if (tail && bigend[0] == little[0])
return (char *)bigend;
return NULL;
}
default:
break; /* Only lengths 0 1 and 2 have special-case code. */
}
if (tail && !multiline) { /* tail anchored? */
s = bigend - littlelen;
if (s >= big && bigend[-1] == '\n' && *s == *little
/* Automatically of length > 2 */
&& memEQ((char*)s + 1, (char*)little + 1, littlelen - 2))
{
return (char*)s; /* how sweet it is */
}
if (s[1] == *little
&& memEQ((char*)s + 2, (char*)little + 1, littlelen - 2))
{
return (char*)s + 1; /* how sweet it is */
}
return NULL;
}
if (!valid) {
/* not compiled; use Perl_ninstr() instead */
char * const b = ninstr((char*)big,(char*)bigend,
(char*)little, (char*)little + littlelen);
assert(!tail); /* valid => FBM; tail only set on SvVALID SVs */
return b;
}
/* Do actual FBM. */
if (littlelen > (STRLEN)(bigend - big))
return NULL;
{
const MAGIC *const mg = mg_find(littlestr, PERL_MAGIC_bm);
const unsigned char *oldlittle;
assert(mg);
--littlelen; /* Last char found by table lookup */
s = big + littlelen;
little += littlelen; /* last char */
oldlittle = little;
if (s < bigend) {
const unsigned char * const table = (const unsigned char *) mg->mg_ptr;
const unsigned char lastc = *little;
I32 tmp;
top2:
if ((tmp = table[*s])) {
/* *s != lastc; earliest position it could match now is
* tmp slots further on */
if ((s += tmp) >= bigend)
goto check_end;
if (LIKELY(*s != lastc)) {
s++;
s = (unsigned char *)memchr((void*)s, lastc, bigend - s);
if (!s) {