-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtin.c
4523 lines (3979 loc) · 104 KB
/
builtin.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
/*
* builtin.c - Builtin functions and various utility procedures.
*/
/*
* Copyright (C) 1986, 1988, 1989, 1991-2021,
* the Free Software Foundation, Inc.
*
* This file is part of GAWK, the GNU implementation of the
* AWK Programming Language.
*
* GAWK is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GAWK 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
*/
#include "awk.h"
#if defined(HAVE_FCNTL_H)
#include <fcntl.h>
#endif
#include "random.h"
#include "floatmagic.h"
#if defined(HAVE_POPEN_H)
#include "popen.h"
#endif
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
/* The extra casts work around common compiler bugs. */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
/* Note: these assume that negative integers are represented internally
via 2's complement, which is not mandated by C. They also ignore the
fact that signed integer arithmetic overflow can trigger exceptions,
unlike unsigned which is guaranteed not to do so. */
#define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
? ~ (uintmax_t) 0 << (sizeof (t) * CHAR_BIT - 1) \
: 0))
#define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
#ifndef INTMAX_MIN
# define INTMAX_MIN TYPE_MINIMUM (intmax_t)
#endif
#ifndef UINTMAX_MAX
# define UINTMAX_MAX TYPE_MAXIMUM (uintmax_t)
#endif
#ifndef SIZE_MAX /* C99 constant, can't rely on it everywhere */
#define SIZE_MAX ((size_t) -1)
#endif
#define DEFAULT_G_PRECISION 6
static size_t mbc_byte_count(const char *ptr, size_t numchars);
static size_t mbc_char_count(const char *ptr, size_t numbytes);
/* Can declare these, since we always use the random shipped with gawk */
extern char *initstate(unsigned long seed, char *state, long n);
extern char *setstate(char *state);
extern long random(void);
extern void srandom(unsigned long seed);
extern NODE **args_array;
extern int max_args;
extern NODE **fields_arr;
extern bool output_is_tty;
extern FILE *output_fp;
static const char *add_thousands(const char *original, struct lconv *loc);
#define POP_TWO_SCALARS(s1, s2) \
s2 = POP_SCALAR(); \
s1 = POP(); \
do { if (s1->type == Node_var_array) { \
DEREF(s2); \
fatal(_("attempt to use array `%s' in a scalar context"), array_vname(s1)); \
}} while (false)
/*
* Since we supply the version of random(), we know what
* value to use here.
*/
#define GAWK_RANDOM_MAX 0x7fffffffL
/* wrerror --- handle a write or flush error */
static void
wrerror(FILE *fp, const char *from, struct redirect *rp)
{
os_maybe_set_errno();
/* for stdout, die with a real SIGPIPE, like other awks */
if (fp == stdout && errno == EPIPE)
die_via_sigpipe();
/* otherwise die verbosely */
if ((rp != NULL) ? is_non_fatal_redirect(rp->value, strlen(rp->value)) : is_non_fatal_std(fp))
update_ERRNO_int(errno);
else
fatal(_("%s to \"%s\" failed: %s"), from,
rp != NULL
? rp->value
: fp == stdout
? _("standard output")
: _("standard error"),
errno ? strerror(errno) : _("reason unknown"));
}
/* efflush --- flush output with proper error handling */
void
efflush(FILE *fp, const char *from, struct redirect *rp)
{
errno = 0;
if (rp != NULL) {
rp->output.gawk_fflush(fp, rp->output.opaque);
if (rp->output.gawk_ferror(fp, rp->output.opaque))
wrerror(fp, from, rp);
} else {
fflush(fp);
if (ferror(fp))
wrerror(fp, from, rp);
}
}
/* efwrite --- like fwrite, but with error checking */
static void
efwrite(const void *ptr,
size_t size,
size_t count,
FILE *fp,
const char *from,
struct redirect *rp,
bool flush)
{
errno = 0;
if (rp != NULL) {
if (rp->output.gawk_fwrite(ptr, size, count, fp, rp->output.opaque) != count) {
wrerror(fp, from, rp);
return;
}
} else if (fwrite(ptr, size, count, fp) != count) {
wrerror(fp, from, rp);
return;
}
if (flush
&& ((fp == stdout && output_is_tty)
|| (rp != NULL && (rp->flag & RED_NOBUF) != 0)))
efflush(fp, from, rp);
}
/* do_exp --- exponential function */
NODE *
do_exp(int nargs)
{
NODE *tmp;
double d, res;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("%s: received non-numeric argument"), "exp");
d = force_number(tmp)->numbr;
DEREF(tmp);
errno = 0;
res = exp(d);
if (errno == ERANGE)
warning(_("exp: argument %g is out of range"), d);
return make_number((AWKNUM) res);
}
/* stdfile --- return fp for a standard file */
/*
* This function allows `fflush("/dev/stdout")' to work.
* The other files will be available via getredirect().
* /dev/stdin is not included, since fflush is only for output.
*/
static FILE *
stdfile(const char *name, size_t len)
{
if (len == 11) {
if (strncmp(name, "/dev/stderr", 11) == 0)
return stderr;
else if (strncmp(name, "/dev/stdout", 11) == 0)
return stdout;
}
return NULL;
}
/* do_fflush --- flush output, either named file or pipe or everything */
NODE *
do_fflush(int nargs)
{
struct redirect *rp;
NODE *tmp;
FILE *fp;
int status = 0;
const char *file;
int len;
/*
* November, 2012.
* It turns out that circa 2002, when BWK
* added fflush() and fflush("") to his awk, he made both of
* them flush everything.
*
* Now, with our inside agent getting ready to try to get fflush()
* standardized in POSIX, we are going to make our awk consistent
* with his. This should not really affect anyone, as flushing
* everything also flushes stdout.
*
* So. Once upon a time:
* fflush() --- flush stdout
* fflush("") --- flush everything
* Now, both calls flush everything.
*/
/* fflush() */
if (nargs == 0) {
status = flush_io(); // ERRNO updated
return make_number((AWKNUM) status);
}
tmp = POP_STRING();
file = tmp->stptr;
len = tmp->stlen;
/* fflush("") */
if (tmp->stlen == 0) {
status = flush_io(); // ERRNO updated
DEREF(tmp);
return make_number((AWKNUM) status);
}
/* fflush("/some/path") */
rp = getredirect(tmp->stptr, tmp->stlen);
status = -1;
if (rp != NULL) {
if ((rp->flag & (RED_WRITE|RED_APPEND)) == 0) {
if ((rp->flag & RED_PIPE) != 0)
warning(_("fflush: cannot flush: pipe `%.*s' opened for reading, not writing"),
len, file);
else
warning(_("fflush: cannot flush: file `%.*s' opened for reading, not writing"),
len, file);
DEREF(tmp);
return make_number((AWKNUM) status);
}
fp = rp->output.fp;
if (fp != NULL) {
status = rp->output.gawk_fflush(fp, rp->output.opaque);
if (status != 0) {
if (! is_non_fatal_redirect(tmp->stptr, tmp->stlen))
fatal(_("fflush: cannot flush file `%.*s': %s"),
len, file, strerror(errno));
update_ERRNO_int(errno);
}
} else if ((rp->flag & RED_TWOWAY) != 0)
warning(_("fflush: cannot flush: two-way pipe `%.*s' has closed write end"),
len, file);
} else if ((fp = stdfile(tmp->stptr, tmp->stlen)) != NULL) {
status = (non_fatal_flush_std_file(fp) == false);
} else {
status = -1;
warning(_("fflush: `%.*s' is not an open file, pipe or co-process"), len, file);
}
DEREF(tmp);
return make_number((AWKNUM) status);
}
/* strncasecmpmbs --- like strncasecmp (multibyte string version) */
int
strncasecmpmbs(const unsigned char *s1, const unsigned char *s2, size_t n)
{
size_t i1, i2, mbclen1, mbclen2, gap;
wchar_t wc1, wc2;
mbstate_t mbs1, mbs2;
memset(& mbs1, 0, sizeof(mbs1));
memset(& mbs2, 0, sizeof(mbs2));
for (i1 = i2 = 0 ; i1 < n && i2 < n ;i1 += mbclen1, i2 += mbclen2) {
if (is_valid_character(s1[i1])) {
mbclen1 = 1;
wc1 = btowc_cache(s1[i1]);
} else {
mbclen1 = mbrtowc(& wc1, (const char *)s1 + i1,
n - i1, & mbs1);
if (mbclen1 == (size_t) -1 || mbclen1 == (size_t) -2 || mbclen1 == 0) {
/* We treat it as a singlebyte character. */
mbclen1 = 1;
wc1 = btowc_cache(s1[i1]);
}
}
if (is_valid_character(s2[i2])) {
mbclen2 = 1;
wc2 = btowc_cache(s2[i2]);
} else {
mbclen2 = mbrtowc(& wc2, (const char *)s2 + i2,
n - i2, & mbs2);
if (mbclen2 == (size_t) -1 || mbclen2 == (size_t) -2 || mbclen2 == 0) {
/* We treat it as a singlebyte character. */
mbclen2 = 1;
wc2 = btowc_cache(s2[i2]);
}
}
if ((gap = towlower(wc1) - towlower(wc2)) != 0)
/* s1 and s2 are not equivalent. */
return gap;
}
/* s1 and s2 are equivalent. */
return 0;
}
/* Inspect the buffer `src' and write the index of each byte to `dest'.
Caller must allocate `dest'.
e.g. str = <mb1(1)>, <mb1(2)>, a, b, <mb2(1)>, <mb2(2)>, <mb2(3)>, c
where mb(i) means the `i'-th byte of a multibyte character.
dest = 1, 2, 1, 1, 1, 2, 3. 1
*/
static void
index_multibyte_buffer(char* src, char* dest, int len)
{
int idx, prev_idx;
mbstate_t mbs, prevs;
memset(& prevs, 0, sizeof(mbstate_t));
for (idx = prev_idx = 0 ; idx < len ; idx++) {
size_t mbclen;
mbs = prevs;
mbclen = mbrlen(src + prev_idx, idx - prev_idx + 1, & mbs);
if (mbclen == (size_t) -1 || mbclen == 1 || mbclen == 0) {
/* singlebyte character. */
mbclen = 1;
prev_idx = idx + 1;
} else if (mbclen == (size_t) -2) {
/* a part of a multibyte character. */
mbclen = idx - prev_idx + 1;
} else if (mbclen > 1) {
/* the end of a multibyte character. */
prev_idx = idx + 1;
prevs = mbs;
} else {
/* Can't reach. */
}
dest[idx] = mbclen;
}
}
/* do_index --- find index of a string */
NODE *
do_index(int nargs)
{
NODE *s1, *s2;
const char *p1, *p2;
size_t l1, l2;
long ret;
bool do_single_byte = false;
mbstate_t mbs1, mbs2;
if (gawk_mb_cur_max > 1) {
memset(& mbs1, 0, sizeof(mbstate_t));
memset(& mbs2, 0, sizeof(mbstate_t));
}
POP_TWO_SCALARS(s1, s2);
if (do_lint) {
if ((fixtype(s1)->flags & STRING) == 0)
lintwarn(_("%s: received non-string first argument"), "index");
if ((fixtype(s2)->flags & STRING) == 0)
lintwarn(_("%s: received non-string second argument"), "index");
}
s1 = force_string(s1);
s2 = force_string(s2);
p1 = s1->stptr;
p2 = s2->stptr;
l1 = s1->stlen;
l2 = s2->stlen;
ret = 0;
/*
* Icky special case, index(foo, "") should return 1,
* since both bwk awk and mawk do, and since match("foo", "")
* returns 1. This makes index("", "") work, too, fwiw.
*/
if (l2 == 0) {
ret = 1;
goto out;
}
if (gawk_mb_cur_max > 1) {
s1 = force_wstring(s1);
s2 = force_wstring(s2);
/*
* If we don't have valid wide character strings, use
* the real bytes.
*/
do_single_byte = ((s1->wstlen == 0 && s1->stlen > 0)
|| (s2->wstlen == 0 && s2->stlen > 0));
}
/* IGNORECASE will already be false if posix */
if (IGNORECASE) {
while (l1 > 0) {
if (l2 > l1)
break;
if (! do_single_byte && gawk_mb_cur_max > 1) {
const wchar_t *pos;
pos = wcasestrstr(s1->wstptr, s1->wstlen, s2->wstptr, s2->wstlen);
if (pos == NULL)
ret = 0;
else
ret = pos - s1->wstptr + 1; /* 1-based */
goto out;
} else {
/*
* Could use tolower(*p1) == tolower(*p2) here.
* See discussion in eval.c as to why not.
*/
if (casetable[(unsigned char)*p1] == casetable[(unsigned char)*p2]
&& (l2 == 1 || strncasecmp(p1, p2, l2) == 0)) {
ret = 1 + s1->stlen - l1;
break;
}
l1--;
p1++;
}
}
} else {
while (l1 > 0) {
if (l2 > l1)
break;
if (*p1 == *p2
&& (l2 == 1 || (l2 > 0 && memcmp(p1, p2, l2) == 0))) {
ret = 1 + s1->stlen - l1;
break;
}
if (! do_single_byte && gawk_mb_cur_max > 1) {
const wchar_t *pos;
pos = wstrstr(s1->wstptr, s1->wstlen, s2->wstptr, s2->wstlen);
if (pos == NULL)
ret = 0;
else
ret = pos - s1->wstptr + 1; /* 1-based */
goto out;
} else {
l1--;
p1++;
}
}
}
out:
DEREF(s1);
DEREF(s2);
return make_number((AWKNUM) ret);
}
/* double_to_int --- convert double to int, used several places */
double
double_to_int(double d)
{
if (d >= 0)
d = floor(d);
else
d = ceil(d);
return d;
}
/* do_int --- convert double to int for awk */
NODE *
do_int(int nargs)
{
NODE *tmp;
double d;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("%s: received non-numeric argument"), "int");
d = force_number(tmp)->numbr;
d = double_to_int(d);
DEREF(tmp);
return make_number((AWKNUM) d);
}
/* do_isarray --- check if argument is array */
NODE *
do_isarray(int nargs)
{
NODE *tmp;
int ret = 1;
tmp = POP();
if (tmp->type != Node_var_array) {
ret = 0;
// could be Node_var_new
if (tmp->type == Node_val)
DEREF(tmp);
}
return make_number((AWKNUM) ret);
}
/* do_length --- length of a string, array or $0 */
NODE *
do_length(int nargs)
{
NODE *tmp;
size_t len;
tmp = POP();
if (tmp->type == Node_var_array) {
static bool warned = false;
unsigned long size;
if (do_posix)
fatal(_("length: received array argument"));
if (do_lint_extensions && ! warned) {
warned = true;
lintwarn(_("`length(array)' is a gawk extension"));
}
/*
* Support for deferred loading of array elements requires that
* we use the array length interface even though it isn't
* necessary for the built-in array types.
*
* 1/2015: The deferred arrays are gone, but this is probably
* still a good idea.
*/
size = assoc_length(tmp);
return make_number(size);
}
assert(tmp->type == Node_val);
if (do_lint && (fixtype(tmp)->flags & STRING) == 0)
lintwarn(_("%s: received non-string argument"), "length");
tmp = force_string(tmp);
if (gawk_mb_cur_max > 1) {
tmp = force_wstring(tmp);
len = tmp->wstlen;
/*
* If the bytes don't make a valid wide character
* string, fall back to the bytes themselves.
*/
if (len == 0 && tmp->stlen > 0)
len = tmp->stlen;
} else
len = tmp->stlen;
DEREF(tmp);
return make_number((AWKNUM) len);
}
/* do_log --- the log function */
NODE *
do_log(int nargs)
{
NODE *tmp;
double d, arg;
tmp = POP_SCALAR();
if (do_lint && (fixtype(tmp)->flags & NUMBER) == 0)
lintwarn(_("%s: received non-numeric argument"), "log");
arg = force_number(tmp)->numbr;
if (arg < 0.0)
warning(_("%s: received negative argument %g"), "log", arg);
d = log(arg);
DEREF(tmp);
return make_number((AWKNUM) d);
}
#ifdef HAVE_MPFR
/*
* mpz2mpfr --- convert an arbitrary-precision integer to a float
* without any loss of precision. The returned value is only
* good for temporary use.
*/
static mpfr_ptr
mpz2mpfr(mpz_ptr zi)
{
size_t prec;
static mpfr_t mpfrval;
static bool inited = false;
int tval;
/* estimate minimum precision for exact conversion */
prec = mpz_sizeinbase(zi, 2); /* most significant 1 bit position starting at 1 */
prec -= (size_t) mpz_scan1(zi, 0); /* least significant 1 bit index starting at 0 */
if (prec < MPFR_PREC_MIN)
prec = MPFR_PREC_MIN;
else if (prec > MPFR_PREC_MAX)
prec = MPFR_PREC_MAX;
if (! inited) {
mpfr_init2(mpfrval, prec);
inited = true;
} else
mpfr_set_prec(mpfrval, prec);
tval = mpfr_set_z(mpfrval, zi, ROUND_MODE);
IEEE_FMT(mpfrval, tval);
return mpfrval;
}
#endif
/*
* format_tree() formats arguments of sprintf,
* and accordingly to a fmt_string providing a format like in
* printf family from C library. Returns a string node which value
* is a formatted string. Called by sprintf function.
*
* It is one of the uglier parts of gawk. Thanks to Michal Jaegermann
* for taming this beast and making it compatible with ANSI C.
*/
NODE *
format_tree(
const char *fmt_string,
size_t n0,
NODE **the_args,
long num_args)
{
/* copy 'l' bytes from 's' to 'obufout' checking for space in the process */
/* difference of pointers should be of ptrdiff_t type, but let us be kind */
#define bchunk(s, l) if (l) { \
while ((l) > ofre) { \
size_t olen = obufout - obuf; \
erealloc(obuf, char *, osiz * 2, "format_tree"); \
ofre += osiz; \
osiz *= 2; \
obufout = obuf + olen; \
} \
memcpy(obufout, s, (size_t) (l)); \
obufout += (l); \
ofre -= (l); \
}
/* copy one byte from 's' to 'obufout' checking for space in the process */
#define bchunk_one(s) { \
if (ofre < 1) { \
size_t olen = obufout - obuf; \
erealloc(obuf, char *, osiz * 2, "format_tree"); \
ofre += osiz; \
osiz *= 2; \
obufout = obuf + olen; \
} \
*obufout++ = *s; \
--ofre; \
}
/* Is there space for something L big in the buffer? */
#define chksize(l) if ((l) >= ofre) { \
size_t olen = obufout - obuf; \
size_t delta = osiz+l-ofre; \
erealloc(obuf, char *, osiz + delta, "format_tree"); \
obufout = obuf + olen; \
ofre += delta; \
osiz += delta; \
}
size_t cur_arg = 0;
NODE *r = NULL;
int i, nc;
bool toofew = false;
char *obuf, *obufout;
size_t osiz, ofre, olen_final;
const char *chbuf;
const char *s0, *s1;
int cs1;
NODE *arg;
long fw, prec, argnum;
bool used_dollar;
bool lj, alt, have_prec, need_format;
long *cur = NULL;
uintmax_t uval;
bool sgn;
int base;
/*
* Although this is an array, the elements serve two different
* purposes. The first element is the general buffer meant
* to hold the entire result string. The second one is a
* temporary buffer for large floating point values. They
* could just as easily be separate variables, and the
* code might arguably be clearer.
*/
struct {
char *buf;
size_t bufsize;
char stackbuf[30];
} cpbufs[2];
#define cpbuf cpbufs[0].buf
char *cend = &cpbufs[0].stackbuf[sizeof(cpbufs[0].stackbuf)];
char *cp;
const char *fill;
AWKNUM tmpval = 0.0;
char signchar = '\0';
size_t len;
bool zero_flag = false;
bool quote_flag = false;
int ii, jj;
char *chp;
size_t copy_count, char_count;
char *nan_inf_val;
bool magic_posix_flag;
#ifdef HAVE_MPFR
mpz_ptr zi;
mpfr_ptr mf;
#endif
enum { MP_NONE = 0, MP_INT_WITH_PREC = 1, MP_INT_WITHOUT_PREC, MP_FLOAT } fmt_type;
static const char sp[] = " ";
static const char zero_string[] = "0";
static const char lchbuf[] = "0123456789abcdef";
static const char Uchbuf[] = "0123456789ABCDEF";
static const char bad_modifiers[] = "hjlLtz";
static bool warned[sizeof(bad_modifiers)-1]; // auto-init to zero
bool modifier_seen[sizeof(bad_modifiers)-1];
#define modifier_index(c) (strchr(bad_modifiers, c) - bad_modifiers)
#define INITIAL_OUT_SIZE 64
emalloc(obuf, char *, INITIAL_OUT_SIZE, "format_tree");
obufout = obuf;
osiz = INITIAL_OUT_SIZE;
ofre = osiz - 1;
cur_arg = 1;
{
size_t k;
for (k = 0; k < sizeof(cpbufs)/sizeof(cpbufs[0]); k++) {
cpbufs[k].bufsize = sizeof(cpbufs[k].stackbuf);
cpbufs[k].buf = cpbufs[k].stackbuf;
}
}
/*
* The point of this goop is to grow the buffer
* holding the converted number, so that large
* values don't overflow a fixed length buffer.
*/
#define PREPEND(CH) do { \
if (cp == cpbufs[0].buf) { \
char *prev = cpbufs[0].buf; \
emalloc(cpbufs[0].buf, char *, 2*cpbufs[0].bufsize, \
"format_tree"); \
memcpy((cp = cpbufs[0].buf+cpbufs[0].bufsize), prev, \
cpbufs[0].bufsize); \
cpbufs[0].bufsize *= 2; \
if (prev != cpbufs[0].stackbuf) \
efree(prev); \
cend = cpbufs[0].buf+cpbufs[0].bufsize; \
} \
*--cp = (CH); \
} while(0)
/*
* Check first for use of `count$'.
* If plain argument retrieval was used earlier, choke.
* Otherwise, return the requested argument.
* If not `count$' now, but it was used earlier, choke.
* If this format is more than total number of args, choke.
* Otherwise, return the current argument.
*/
#define parse_next_arg() { \
if (argnum > 0) { \
if (cur_arg > 1) { \
msg(_("fatal: must use `count$' on all formats or none")); \
goto out; \
} \
arg = the_args[argnum]; \
} else if (used_dollar) { \
msg(_("fatal: must use `count$' on all formats or none")); \
arg = 0; /* shutup the compiler */ \
goto out; \
} else if (cur_arg >= num_args) { \
arg = 0; /* shutup the compiler */ \
toofew = true; \
break; \
} else { \
arg = the_args[cur_arg]; \
cur_arg++; \
} \
}
need_format = false;
used_dollar = false;
s0 = s1 = fmt_string;
while (n0-- > 0) {
if (*s1 != '%') {
s1++;
continue;
}
need_format = true;
bchunk(s0, s1 - s0);
s0 = s1;
cur = &fw;
fw = 0;
prec = 0;
base = 0;
argnum = 0;
base = 0;
have_prec = false;
signchar = '\0';
zero_flag = false;
quote_flag = false;
nan_inf_val = NULL;
#ifdef HAVE_MPFR
mf = NULL;
zi = NULL;
#endif
fmt_type = MP_NONE;
lj = alt = false;
memset(modifier_seen, 0, sizeof(modifier_seen));
magic_posix_flag = false;
fill = sp;
cp = cend;
chbuf = lchbuf;
s1++;
retry:
if (n0-- == 0) /* ran out early! */
break;
switch (cs1 = *s1++) {
case (-1): /* dummy case to allow for checking */
check_pos:
if (cur != &fw)
break; /* reject as a valid format */
goto retry;
case '%':
need_format = false;
/*
* 29 Oct. 2002:
* The C99 standard pages 274 and 279 seem to imply that
* since there's no arg converted, the field width doesn't
* apply. The code already was that way, but this
* comment documents it, at least in the code.
*/
if (do_lint) {
const char *msg = NULL;
if (fw && ! have_prec)
msg = _("field width is ignored for `%%' specifier");
else if (fw == 0 && have_prec)
msg = _("precision is ignored for `%%' specifier");
else if (fw && have_prec)
msg = _("field width and precision are ignored for `%%' specifier");
if (msg != NULL)
lintwarn("%s", msg);
}
bchunk_one("%");
s0 = s1;
break;
case '0':
/*
* Only turn on zero_flag if we haven't seen
* the field width or precision yet. Otherwise,
* screws up floating point formatting.
*/
if (cur == & fw)
zero_flag = true;
if (lj)
goto retry;
/* FALL through */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (cur == NULL)
break;
if (prec >= 0)
*cur = cs1 - '0';
/*
* with a negative precision *cur is already set
* to -1, so it will remain negative, but we have
* to "eat" precision digits in any case
*/
while (n0 > 0 && *s1 >= '0' && *s1 <= '9') {
--n0;
*cur = *cur * 10 + *s1++ - '0';
}
if (prec < 0) /* negative precision is discarded */
have_prec = false;
if (cur == &prec)
cur = NULL;
if (n0 == 0) /* badly formatted control string */
continue;
goto retry;
case '$':
if (do_traditional) {
msg(_("fatal: `$' is not permitted in awk formats"));
goto out;
}
if (cur == &fw) {
argnum = fw;
fw = 0;
used_dollar = true;
if (argnum <= 0) {
msg(_("fatal: argument index with `$' must be > 0"));
goto out;
}
if (argnum >= num_args) {
msg(_("fatal: argument index %ld greater than total number of supplied arguments"), argnum);
goto out;
}
} else {
msg(_("fatal: `$' not permitted after period in format"));
goto out;
}
goto retry;
case '*':
if (cur == NULL)
break;
if (! do_traditional && used_dollar && ! isdigit((unsigned char) *s1)) {
fatal(_("fatal: must use `count$' on all formats or none"));
break; /* silence warnings */
} else if (! do_traditional && isdigit((unsigned char) *s1)) {
int val = 0;
for (; n0 > 0 && *s1 && isdigit((unsigned char) *s1); s1++, n0--) {
val *= 10;
val += *s1 - '0';
}
if (*s1 != '$') {
msg(_("fatal: no `$' supplied for positional field width or precision"));
goto out;
} else {
s1++;
n0--;
}
if (val >= num_args) {
toofew = true;
break;
}
arg = the_args[val];
} else {
parse_next_arg();
}
(void) force_number(arg);
*cur = get_number_si(arg);
if (*cur < 0 && cur == &fw) {
*cur = -*cur;
lj = true;
}
if (cur == &prec) {
if (*cur >= 0)
have_prec = true;
else
have_prec = false;
cur = NULL;