-
Notifications
You must be signed in to change notification settings - Fork 561
/
Copy pathutil.c
6760 lines (5872 loc) · 196 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
#include <signal.h>
#ifndef SIG_ERR
# define SIG_ERR ((Sighandler_t) -1)
#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
/* Sanity check: Format strings must not be empty */
STATIC_ASSERT_DECL(sizeof I32df > 1);
STATIC_ASSERT_DECL(sizeof U32of > 1);
STATIC_ASSERT_DECL(sizeof U32uf > 1);
STATIC_ASSERT_DECL(sizeof U32xf > 1);
STATIC_ASSERT_DECL(sizeof U32Xf > 1);
STATIC_ASSERT_DECL(sizeof IVdf > 1);
STATIC_ASSERT_DECL(sizeof UVuf > 1);
STATIC_ASSERT_DECL(sizeof UVof > 1);
STATIC_ASSERT_DECL(sizeof UVxf > 1);
STATIC_ASSERT_DECL(sizeof UVXf > 1);
STATIC_ASSERT_DECL(sizeof NVef > 1);
STATIC_ASSERT_DECL(sizeof NVff > 1);
STATIC_ASSERT_DECL(sizeof NVgf > 1);
STATIC_ASSERT_DECL(sizeof Gid_t_f > 1);
STATIC_ASSERT_DECL(sizeof Uid_t_f > 1);
/*
=for apidoc_section $memory
=for apidoc safesysmalloc
Paranoid version of system's malloc()
=cut
*/
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);
#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_ext(STR_WITH_LEN("util:safesysmalloc"));
}
}
return ptr;
}
/*
=for apidoc safesysrealloc
Paranoid version of system's realloc()
=cut
*/
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;
PERL_DEB(UV was_where = PTR2UV(where)); /* used in diags below */
#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 %p from wrong pool, %p!=%p",
where, 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 %p , size=%" UVuf,
where, (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",was_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_ext(STR_WITH_LEN("util:safesysrealloc"));
}
}
}
return ptr;
}
/*
=for apidoc safesysfree
Safe version of system's free()
=cut
*/
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 %p from wrong pool, %p!=%p",
where, header->interpreter, aTHX);
}
if (!header->prev) {
Perl_croak_nocontext("panic: duplicate free");
}
if (!(header->next))
Perl_croak_nocontext("panic: bad free of %p, header->next==NULL",
where);
if (header->next->prev != header || header->prev->next != header) {
Perl_croak_nocontext("panic: bad free of %p, ->next->prev=%p, "
"header=%p, ->prev->next=%p",
where, 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
}
}
/*
=for apidoc safesyscalloc
Safe version of system's calloc()
=cut
*/
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_ext(STR_WITH_LEN("util:safesyscalloc"));
}
}
/* 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
/* This is the value stored in *retlen in the two delimcpy routines below when
* there wasn't enough room in the destination to store everything it was asked
* to. The value is deliberately very large so that hopefully if code uses it
* unquestioningly to access memory, it will likely segfault. And it is small
* enough that if the caller does some arithmetic on it before accessing, it
* won't overflow into a small legal number. */
#define DELIMCPY_OUT_OF_BOUNDS_RET I32_MAX
/*
=for apidoc_section $string
=for apidoc delimcpy_no_escape
Copy a source buffer to a destination buffer, stopping at (but not including)
the first occurrence in the source of the delimiter byte, C<delim>. The source
is the bytes between S<C<from> and C<from_end> - 1>. Similarly, the dest is
C<to> up to C<to_end>.
The number of bytes copied is written to C<*retlen>.
Returns the position of C<delim> in the C<from> buffer, but if there is no
such occurrence before C<from_end>, then C<from_end> is returned, and the entire
buffer S<C<from> .. C<from_end> - 1> is copied.
If there is room in the destination available after the copy, an extra
terminating safety C<NUL> byte is appended (not included in the returned
length).
The error case is if the destination buffer is not large enough to accommodate
everything that should be copied. In this situation, a value larger than
S<C<to_end> - C<to>> is written to C<*retlen>, and as much of the source as
fits will be written to the destination. Not having room for the safety C<NUL>
is not considered an error.
=cut
*/
char *
Perl_delimcpy_no_escape(char *to, const char *to_end,
const char *from, const char *from_end,
const int delim, I32 *retlen)
{
const char * delim_pos;
Ptrdiff_t from_len = from_end - from;
Ptrdiff_t to_len = to_end - to;
SSize_t copy_len;
PERL_ARGS_ASSERT_DELIMCPY_NO_ESCAPE;
assert(from_len >= 0);
assert(to_len >= 0);
/* Look for the first delimiter in the source */
delim_pos = (const char *) memchr(from, delim, from_len);
/* Copy up to where the delimiter was found, or the entire buffer if not
* found */
copy_len = (delim_pos) ? delim_pos - from : from_len;
/* If not enough room, copy as much as can fit, and set error return */
if (copy_len > to_len) {
Copy(from, to, to_len, char);
*retlen = DELIMCPY_OUT_OF_BOUNDS_RET;
}
else {
Copy(from, to, copy_len, char);
/* If there is extra space available, add a trailing NUL */
if (copy_len < to_len) {
to[copy_len] = '\0';
}
*retlen = copy_len;
}
return (char *) from + copy_len;
}
/*
=for apidoc delimcpy
Copy a source buffer to a destination buffer, stopping at (but not including)
the first occurrence in the source of an unescaped (defined below) delimiter
byte, C<delim>. The source is the bytes between S<C<from> and C<from_end> -
1>. Similarly, the dest is C<to> up to C<to_end>.
The number of bytes copied is written to C<*retlen>.
Returns the position of the first uncopied C<delim> in the C<from> buffer, but
if there is no such occurrence before C<from_end>, then C<from_end> is returned,
and the entire buffer S<C<from> .. C<from_end> - 1> is copied.
If there is room in the destination available after the copy, an extra
terminating safety C<NUL> byte is appended (not included in the returned
length).
The error case is if the destination buffer is not large enough to accommodate
everything that should be copied. In this situation, a value larger than
S<C<to_end> - C<to>> is written to C<*retlen>, and as much of the source as
fits will be written to the destination. Not having room for the safety C<NUL>
is not considered an error.
In the following examples, let C<x> be the delimiter, and C<0> represent a C<NUL>
byte (B<NOT> the digit C<0>). Then we would have
Source Destination
abcxdef abc0
provided the destination buffer is at least 4 bytes long.
An escaped delimiter is one which is immediately preceded by a single
backslash. Escaped delimiters are copied, and the copy continues past the
delimiter; the backslash is not copied:
Source Destination
abc\xdef abcxdef0
(provided the destination buffer is at least 8 bytes long).
It's actually somewhat more complicated than that. A sequence of any odd number
of backslashes escapes the following delimiter, and the copy continues with
exactly one of the backslashes stripped.
Source Destination
abc\xdef abcxdef0
abc\\\xdef abc\\xdef0
abc\\\\\xdef abc\\\\xdef0
(as always, if the destination is large enough)
An even number of preceding backslashes does not escape the delimiter, so that
the copy stops just before it, and includes all the backslashes (no stripping;
zero is considered even):
Source Destination
abcxdef abc0
abc\\xdef abc\\0
abc\\\\xdef abc\\\\0
=cut
*/
char *
Perl_delimcpy(char *to, const char *to_end,
const char *from, const char *from_end,
const int delim, I32 *retlen)
{
const char * const orig_to = to;
Ptrdiff_t copy_len = 0;
bool stopped_early = FALSE; /* Ran out of room to copy to */
PERL_ARGS_ASSERT_DELIMCPY;
assert(from_end >= from);
assert(to_end >= to);
/* Don't use the loop for the trivial case of the first character being the
* delimiter; otherwise would have to worry inside the loop about backing
* up before the start of 'from' */
if (LIKELY(from_end > from && *from != delim)) {
while ((copy_len = from_end - from) > 0) {
const char * backslash_pos;
const char * delim_pos;
/* Look for the next delimiter in the remaining portion of the
* source. A loop invariant is that we already know that the copy
* should include *from; this comes from the conditional before the
* loop, and how we set things up at the end of each iteration */
delim_pos = (const char *) memchr(from + 1, delim, copy_len - 1);
/* If didn't find it, done looking; set up so copies all of the
* source */
if (! delim_pos) {
copy_len = from_end - from;
break;
}
/* Look for a backslash immediately before the delimiter */
backslash_pos = delim_pos - 1;
/* If the delimiter is not escaped, this ends the copy */
if (*backslash_pos != '\\') {
copy_len = delim_pos - from;
break;
}
/* Here there is a backslash just before the delimiter, but it
* could be the final backslash in a sequence of them. Backup to
* find the first one in it. */
do {
backslash_pos--;
}
while (backslash_pos >= from && *backslash_pos == '\\');
/* If the number of backslashes is even, they just escape one
* another, leaving the delimiter unescaped, and stopping the copy.
* */
if (! ((delim_pos - (backslash_pos + 1)) & 1)) {
copy_len = delim_pos - from; /* even, copy up to delimiter */
break;
}
/* Here is odd, so the delimiter is escaped. We will try to copy
* all but the final backslash in the sequence */
copy_len = delim_pos - 1 - from;
/* Do the copy, but not beyond the end of the destination */
if (copy_len >= to_end - to) {
Copy(from, to, to_end - to, char);
stopped_early = TRUE;
to = (char *) to_end;
}
else {
Copy(from, to, copy_len, char);
to += copy_len;
}
/* Set up so next iteration will include the delimiter */
from = delim_pos;
}
}
/* Here, have found the final segment to copy. Copy that, but not beyond
* the size of the destination. If not enough room, copy as much as can
* fit, and set error return */
if (stopped_early || copy_len > to_end - to) {
Copy(from, to, to_end - to, char);
*retlen = DELIMCPY_OUT_OF_BOUNDS_RET;
}
else {
Copy(from, to, copy_len, char);
to += copy_len;
/* If there is extra space available, add a trailing NUL */
if (to < to_end) {
*to = '\0';
}
*retlen = to - orig_to;
}
return (char *) from + copy_len;
}
/*
=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;
}
else {
const U8 first = *little;
Size_t lsize;
/* No match can start closer to the end of the haystack than the length
* of the needle. */
bigend -= lend - little;
little++; /* Look for 'first', then the remainder is in here */
lsize = lend - little;
while (big <= bigend) {
big = (char *) memchr((U8 *) big, first, bigend - big + 1);
if (big == NULL || big > bigend) {
return NULL;
}
if (memEQ(big + 1, little, lsize)) {
return (char*) big;
}
big++;
}
}
return NULL;
#endif
}
/*
=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 Ptrdiff_t little_len = lend - little;
const Ptrdiff_t big_len = bigend - big;
PERL_ARGS_ASSERT_RNINSTR;
/* A non-existent needle trivially matches the rightmost possible position
* in the haystack */
if (UNLIKELY(little_len <= 0)) {
return (char*)bigend;
}
/* If the needle is larger than the haystack, the needle can't possibly fit
* inside the haystack. */
if (UNLIKELY(little_len > big_len)) {
return NULL;
}
/* Special case length 1 needles. It's trivial if we have memrchr();
* and otherwise we just do a per-byte search backwards.
*
* XXX When we don't have memrchr, we could use something like
* S_find_next_masked( or S_find_span_end() to do per-word searches */
if (little_len == 1) {
const char final = *little;
#ifdef HAS_MEMRCHR
return (char *) memrchr(big, final, big_len);
#else
const char * cur = bigend - 1;
do {
if (*cur == final) {
return (char *) cur;
}
} while (--cur >= big);
return NULL;
#endif
}
else { /* Below, the needle is longer than a single byte */
/* We search backwards in the haystack for the final character of the
* needle. Each time one is found, we see if the characters just
* before it in the haystack match the rest of the needle. */
const char final = *(lend - 1);
/* What matches consists of 'little_len'-1 characters, then the final
* one */
const Size_t prefix_len = little_len - 1;
/* If the final character in the needle is any closer than this to the
* left edge, there wouldn't be enough room for all of it to fit in the
* haystack */
const char * const left_fence = big + prefix_len;
/* Start at the right edge */
char * cur = (char *) bigend;
/* memrchr() makes the search easy (and fast); otherwise, look
* backwards byte-by-byte. */
do {
#ifdef HAS_MEMRCHR
cur = (char *) memrchr(left_fence, final, cur - left_fence);
if (cur == NULL) {
return NULL;
}
#else
do {
cur--;
if (cur < left_fence) {
return NULL;
}
}
while (*cur != final);
#endif
/* Here, we know that *cur is 'final'; see if the preceding bytes
* of the needle also match the corresponding haystack bytes */
if memEQ(cur - prefix_len, little, prefix_len) {
return cur - prefix_len;
}
} while (cur > left_fence);
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. */
/*
=for apidoc fbm_compile
Analyzes the string in order to make fast searches on it using C<fbm_instr()>