-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpreproc.c
5244 lines (4805 loc) · 165 KB
/
preproc.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 1996-2012 The NASM Authors - All Rights Reserved
* See the file AUTHORS included with the NASM distribution for
* the specific copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----------------------------------------------------------------------- */
/*
* preproc.c macro preprocessor for the Netwide Assembler
*/
/* Typical flow of text through preproc
*
* pp_getline gets tokenized lines, either
*
* from a macro expansion
*
* or
* {
* read_line gets raw text from stdmacpos, or predef, or current input file
* tokenize converts to tokens
* }
*
* expand_mmac_params is used to expand %1 etc., unless a macro is being
* defined or a false conditional is being processed
* (%0, %1, %+1, %-1, %%foo
*
* do_directive checks for directives
*
* expand_smacro is used to expand single line macros
*
* expand_mmacro is used to expand multi-line macros
*
* detoken is used to convert the line back to text
*/
#include "compiler.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <inttypes.h>
#include "nasm.h"
#include "nasmlib.h"
#include "preproc.h"
#include "hashtbl.h"
#include "quote.h"
#include "stdscan.h"
#include "eval.h"
#include "tokens.h"
#include "tables.h"
typedef struct SMacro SMacro;
typedef struct MMacro MMacro;
typedef struct MMacroInvocation MMacroInvocation;
typedef struct Context Context;
typedef struct Token Token;
typedef struct Blocks Blocks;
typedef struct Line Line;
typedef struct Include Include;
typedef struct Cond Cond;
typedef struct IncPath IncPath;
/*
* Note on the storage of both SMacro and MMacros: the hash table
* indexes them case-insensitively, and we then have to go through a
* linked list of potential case aliases (and, for MMacros, parameter
* ranges); this is to preserve the matching semantics of the earlier
* code. If the number of case aliases for a specific macro is a
* performance issue, you may want to reconsider your coding style.
*/
/*
* Store the definition of a single-line macro.
*/
struct SMacro {
SMacro *next;
char *name;
bool casesense;
bool in_progress;
unsigned int nparam;
Token *expansion;
};
/*
* Store the definition of a multi-line macro. This is also used to
* store the interiors of `%rep...%endrep' blocks, which are
* effectively self-re-invoking multi-line macros which simply
* don't have a name or bother to appear in the hash tables. %rep
* blocks are signified by having a NULL `name' field.
*
* In a MMacro describing a `%rep' block, the `in_progress' field
* isn't merely boolean, but gives the number of repeats left to
* run.
*
* The `next' field is used for storing MMacros in hash tables; the
* `next_active' field is for stacking them on istk entries.
*
* When a MMacro is being expanded, `params', `iline', `nparam',
* `paramlen', `rotate' and `unique' are local to the invocation.
*/
struct MMacro {
MMacro *next;
MMacroInvocation *prev; /* previous invocation */
char *name;
int nparam_min, nparam_max;
bool casesense;
bool plus; /* is the last parameter greedy? */
bool nolist; /* is this macro listing-inhibited? */
int64_t in_progress; /* is this macro currently being expanded? */
int32_t max_depth; /* maximum number of recursive expansions allowed */
Token *dlist; /* All defaults as one list */
Token **defaults; /* Parameter default pointers */
int ndefs; /* number of default parameters */
Line *expansion;
MMacro *next_active;
MMacro *rep_nest; /* used for nesting %rep */
Token **params; /* actual parameters */
Token *iline; /* invocation line */
unsigned int nparam, rotate;
int *paramlen;
uint64_t unique;
int lineno; /* Current line number on expansion */
uint64_t condcnt; /* number of if blocks... */
};
/* Store the definition of a multi-line macro, as defined in a
* previous recursive macro expansion.
*/
struct MMacroInvocation {
MMacroInvocation *prev; /* previous invocation */
Token **params; /* actual parameters */
Token *iline; /* invocation line */
unsigned int nparam, rotate;
int *paramlen;
uint64_t unique;
uint64_t condcnt;
};
/*
* The context stack is composed of a linked list of these.
*/
struct Context {
Context *next;
char *name;
struct hash_table localmac;
uint32_t number;
};
/*
* This is the internal form which we break input lines up into.
* Typically stored in linked lists.
*
* Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
* necessarily used as-is, but is intended to denote the number of
* the substituted parameter. So in the definition
*
* %define a(x,y) ( (x) & ~(y) )
*
* the token representing `x' will have its type changed to
* TOK_SMAC_PARAM, but the one representing `y' will be
* TOK_SMAC_PARAM+1.
*
* TOK_INTERNAL_STRING is a dirty hack: it's a single string token
* which doesn't need quotes around it. Used in the pre-include
* mechanism as an alternative to trying to find a sensible type of
* quote to use on the filename we were passed.
*/
enum pp_token_type {
TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
TOK_PREPROC_ID, TOK_STRING,
TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
TOK_INTERNAL_STRING,
TOK_PREPROC_Q, TOK_PREPROC_QQ,
TOK_PASTE, /* %+ */
TOK_INDIRECT, /* %[...] */
TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
};
#define PP_CONCAT_MASK(x) (1 << (x))
struct tokseq_match {
int mask_head;
int mask_tail;
};
struct Token {
Token *next;
char *text;
union {
SMacro *mac; /* associated macro for TOK_SMAC_END */
size_t len; /* scratch length field */
} a; /* Auxiliary data */
enum pp_token_type type;
};
/*
* Multi-line macro definitions are stored as a linked list of
* these, which is essentially a container to allow several linked
* lists of Tokens.
*
* Note that in this module, linked lists are treated as stacks
* wherever possible. For this reason, Lines are _pushed_ on to the
* `expansion' field in MMacro structures, so that the linked list,
* if walked, would give the macro lines in reverse order; this
* means that we can walk the list when expanding a macro, and thus
* push the lines on to the `expansion' field in _istk_ in reverse
* order (so that when popped back off they are in the right
* order). It may seem cockeyed, and it relies on my design having
* an even number of steps in, but it works...
*
* Some of these structures, rather than being actual lines, are
* markers delimiting the end of the expansion of a given macro.
* This is for use in the cycle-tracking and %rep-handling code.
* Such structures have `finishes' non-NULL, and `first' NULL. All
* others have `finishes' NULL, but `first' may still be NULL if
* the line is blank.
*/
struct Line {
Line *next;
MMacro *finishes;
Token *first;
};
/*
* To handle an arbitrary level of file inclusion, we maintain a
* stack (ie linked list) of these things.
*/
struct Include {
Include *next;
FILE *fp;
Cond *conds;
Line *expansion;
char *fname;
int lineno, lineinc;
MMacro *mstk; /* stack of active macros/reps */
};
/*
* Include search path. This is simply a list of strings which get
* prepended, in turn, to the name of an include file, in an
* attempt to find the file if it's not in the current directory.
*/
struct IncPath {
IncPath *next;
char *path;
};
/*
* Conditional assembly: we maintain a separate stack of these for
* each level of file inclusion. (The only reason we keep the
* stacks separate is to ensure that a stray `%endif' in a file
* included from within the true branch of a `%if' won't terminate
* it and cause confusion: instead, rightly, it'll cause an error.)
*/
struct Cond {
Cond *next;
int state;
};
enum {
/*
* These states are for use just after %if or %elif: IF_TRUE
* means the condition has evaluated to truth so we are
* currently emitting, whereas IF_FALSE means we are not
* currently emitting but will start doing so if a %else comes
* up. In these states, all directives are admissible: %elif,
* %else and %endif. (And of course %if.)
*/
COND_IF_TRUE, COND_IF_FALSE,
/*
* These states come up after a %else: ELSE_TRUE means we're
* emitting, and ELSE_FALSE means we're not. In ELSE_* states,
* any %elif or %else will cause an error.
*/
COND_ELSE_TRUE, COND_ELSE_FALSE,
/*
* These states mean that we're not emitting now, and also that
* nothing until %endif will be emitted at all. COND_DONE is
* used when we've had our moment of emission
* and have now started seeing %elifs. COND_NEVER is used when
* the condition construct in question is contained within a
* non-emitting branch of a larger condition construct,
* or if there is an error.
*/
COND_DONE, COND_NEVER
};
#define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
/*
* These defines are used as the possible return values for do_directive
*/
#define NO_DIRECTIVE_FOUND 0
#define DIRECTIVE_FOUND 1
/*
* This define sets the upper limit for smacro and recursive mmacro
* expansions
*/
#define DEADMAN_LIMIT (1 << 20)
/* max reps */
#define REP_LIMIT ((INT64_C(1) << 62))
/*
* Condition codes. Note that we use c_ prefix not C_ because C_ is
* used in nasm.h for the "real" condition codes. At _this_ level,
* we treat CXZ and ECXZ as condition codes, albeit non-invertible
* ones, so we need a different enum...
*/
static const char * const conditions[] = {
"a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
"na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
"np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
};
enum pp_conds {
c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
c_none = -1
};
static const enum pp_conds inverse_ccs[] = {
c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
};
/*
* Directive names.
*/
/* If this is a an IF, ELIF, ELSE or ENDIF keyword */
static int is_condition(enum preproc_token arg)
{
return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
}
/* For TASM compatibility we need to be able to recognise TASM compatible
* conditional compilation directives. Using the NASM pre-processor does
* not work, so we look for them specifically from the following list and
* then jam in the equivalent NASM directive into the input stream.
*/
enum {
TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
TM_IFNDEF, TM_INCLUDE, TM_LOCAL
};
static const char * const tasm_directives[] = {
"arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
"ifndef", "include", "local"
};
static int StackSize = 4;
static char *StackPointer = "ebp";
static int ArgOffset = 8;
static int LocalOffset = 0;
static Context *cstk;
static Include *istk;
static IncPath *ipath = NULL;
static int pass; /* HACK: pass 0 = generate dependencies only */
static StrList **dephead, **deptail; /* Dependency list */
static uint64_t unique; /* unique identifier numbers */
static Line *predef = NULL;
static bool do_predef;
static ListGen *list;
/*
* The current set of multi-line macros we have defined.
*/
static struct hash_table mmacros;
/*
* The current set of single-line macros we have defined.
*/
static struct hash_table smacros;
/*
* The multi-line macro we are currently defining, or the %rep
* block we are currently reading, if any.
*/
static MMacro *defining;
static uint64_t nested_mac_count;
static uint64_t nested_rep_count;
/*
* The number of macro parameters to allocate space for at a time.
*/
#define PARAM_DELTA 16
/*
* The standard macro set: defined in macros.c in the array nasm_stdmac.
* This gives our position in the macro set, when we're processing it.
*/
static macros_t *stdmacpos;
/*
* The extra standard macros that come from the object format, if
* any.
*/
static macros_t *extrastdmac = NULL;
static bool any_extrastdmac;
/*
* Tokens are allocated in blocks to improve speed
*/
#define TOKEN_BLOCKSIZE 4096
static Token *freeTokens = NULL;
struct Blocks {
Blocks *next;
void *chunk;
};
static Blocks blocks = { NULL, NULL };
/*
* Forward declarations.
*/
static Token *expand_mmac_params(Token * tline);
static Token *expand_smacro(Token * tline);
static Token *expand_id(Token * tline);
static Context *get_ctx(const char *name, const char **namep,
bool all_contexts);
static void make_tok_num(Token * tok, int64_t val);
static void error(int severity, const char *fmt, ...);
static void error_precond(int severity, const char *fmt, ...);
static void *new_Block(size_t size);
static void delete_Blocks(void);
static Token *new_Token(Token * next, enum pp_token_type type,
const char *text, int txtlen);
static Token *delete_Token(Token * t);
/*
* Macros for safe checking of token pointers, avoid *(NULL)
*/
#define tok_type_(x,t) ((x) && (x)->type == (t))
#define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
#define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
#define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
/*
* nasm_unquote with error if the string contains NUL characters.
* If the string contains NUL characters, issue an error and return
* the C len, i.e. truncate at the NUL.
*/
static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
{
size_t len = nasm_unquote(qstr, NULL);
size_t clen = strlen(qstr);
if (len != clen)
error(ERR_NONFATAL, "NUL character in `%s' directive",
pp_directives[directive]);
return clen;
}
/*
* In-place reverse a list of tokens.
*/
static Token *reverse_tokens(Token *t)
{
Token *prev = NULL;
Token *next;
while (t) {
next = t->next;
t->next = prev;
prev = t;
t = next;
}
return prev;
}
/*
* Handle TASM specific directives, which do not contain a % in
* front of them. We do it here because I could not find any other
* place to do it for the moment, and it is a hack (ideally it would
* be nice to be able to use the NASM pre-processor to do it).
*/
static char *check_tasm_directive(char *line)
{
int32_t i, j, k, m, len;
char *p, *q, *oldline, oldchar;
p = nasm_skip_spaces(line);
/* Binary search for the directive name */
i = -1;
j = ARRAY_SIZE(tasm_directives);
q = nasm_skip_word(p);
len = q - p;
if (len) {
oldchar = p[len];
p[len] = 0;
while (j - i > 1) {
k = (j + i) / 2;
m = nasm_stricmp(p, tasm_directives[k]);
if (m == 0) {
/* We have found a directive, so jam a % in front of it
* so that NASM will then recognise it as one if it's own.
*/
p[len] = oldchar;
len = strlen(p);
oldline = line;
line = nasm_malloc(len + 2);
line[0] = '%';
if (k == TM_IFDIFI) {
/*
* NASM does not recognise IFDIFI, so we convert
* it to %if 0. This is not used in NASM
* compatible code, but does need to parse for the
* TASM macro package.
*/
strcpy(line + 1, "if 0");
} else {
memcpy(line + 1, p, len + 1);
}
nasm_free(oldline);
return line;
} else if (m < 0) {
j = k;
} else
i = k;
}
p[len] = oldchar;
}
return line;
}
/*
* The pre-preprocessing stage... This function translates line
* number indications as they emerge from GNU cpp (`# lineno "file"
* flags') into NASM preprocessor line number indications (`%line
* lineno file').
*/
static char *prepreproc(char *line)
{
int lineno, fnlen;
char *fname, *oldline;
if (line[0] == '#' && line[1] == ' ') {
oldline = line;
fname = oldline + 2;
lineno = atoi(fname);
fname += strspn(fname, "0123456789 ");
if (*fname == '"')
fname++;
fnlen = strcspn(fname, "\"");
line = nasm_malloc(20 + fnlen);
snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
nasm_free(oldline);
}
if (tasm_compatible_mode)
return check_tasm_directive(line);
return line;
}
/*
* Free a linked list of tokens.
*/
static void free_tlist(Token * list)
{
while (list)
list = delete_Token(list);
}
/*
* Free a linked list of lines.
*/
static void free_llist(Line * list)
{
Line *l, *tmp;
list_for_each_safe(l, tmp, list) {
free_tlist(l->first);
nasm_free(l);
}
}
/*
* Free an MMacro
*/
static void free_mmacro(MMacro * m)
{
nasm_free(m->name);
free_tlist(m->dlist);
nasm_free(m->defaults);
free_llist(m->expansion);
nasm_free(m);
}
/*
* Free all currently defined macros, and free the hash tables
*/
static void free_smacro_table(struct hash_table *smt)
{
SMacro *s, *tmp;
const char *key;
struct hash_tbl_node *it = NULL;
while ((s = hash_iterate(smt, &it, &key)) != NULL) {
nasm_free((void *)key);
list_for_each_safe(s, tmp, s) {
nasm_free(s->name);
free_tlist(s->expansion);
nasm_free(s);
}
}
hash_free(smt);
}
static void free_mmacro_table(struct hash_table *mmt)
{
MMacro *m, *tmp;
const char *key;
struct hash_tbl_node *it = NULL;
it = NULL;
while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
nasm_free((void *)key);
list_for_each_safe(m ,tmp, m)
free_mmacro(m);
}
hash_free(mmt);
}
static void free_macros(void)
{
free_smacro_table(&smacros);
free_mmacro_table(&mmacros);
}
/*
* Initialize the hash tables
*/
static void init_macros(void)
{
hash_init(&smacros, HASH_LARGE);
hash_init(&mmacros, HASH_LARGE);
}
/*
* Pop the context stack.
*/
static void ctx_pop(void)
{
Context *c = cstk;
cstk = cstk->next;
free_smacro_table(&c->localmac);
nasm_free(c->name);
nasm_free(c);
}
/*
* Search for a key in the hash index; adding it if necessary
* (in which case we initialize the data pointer to NULL.)
*/
static void **
hash_findi_add(struct hash_table *hash, const char *str)
{
struct hash_insert hi;
void **r;
char *strx;
r = hash_findi(hash, str, &hi);
if (r)
return r;
strx = nasm_strdup(str); /* Use a more efficient allocator here? */
return hash_add(&hi, strx, NULL);
}
/*
* Like hash_findi, but returns the data element rather than a pointer
* to it. Used only when not adding a new element, hence no third
* argument.
*/
static void *
hash_findix(struct hash_table *hash, const char *str)
{
void **p;
p = hash_findi(hash, str, NULL);
return p ? *p : NULL;
}
/*
* read line from standart macros set,
* if there no more left -- return NULL
*/
static char *line_from_stdmac(void)
{
unsigned char c;
const unsigned char *p = stdmacpos;
char *line, *q;
size_t len = 0;
if (!stdmacpos)
return NULL;
while ((c = *p++)) {
if (c >= 0x80)
len += pp_directives_len[c - 0x80] + 1;
else
len++;
}
line = nasm_malloc(len + 1);
q = line;
while ((c = *stdmacpos++)) {
if (c >= 0x80) {
memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
q += pp_directives_len[c - 0x80];
*q++ = ' ';
} else {
*q++ = c;
}
}
stdmacpos = p;
*q = '\0';
if (!*stdmacpos) {
/* This was the last of the standard macro chain... */
stdmacpos = NULL;
if (any_extrastdmac) {
stdmacpos = extrastdmac;
any_extrastdmac = false;
} else if (do_predef) {
Line *pd, *l;
Token *head, **tail, *t;
/*
* Nasty hack: here we push the contents of
* `predef' on to the top-level expansion stack,
* since this is the most convenient way to
* implement the pre-include and pre-define
* features.
*/
list_for_each(pd, predef) {
head = NULL;
tail = &head;
list_for_each(t, pd->first) {
*tail = new_Token(NULL, t->type, t->text, 0);
tail = &(*tail)->next;
}
l = nasm_malloc(sizeof(Line));
l->next = istk->expansion;
l->first = head;
l->finishes = NULL;
istk->expansion = l;
}
do_predef = false;
}
}
return line;
}
#define BUF_DELTA 512
/*
* Read a line from the top file in istk, handling multiple CR/LFs
* at the end of the line read, and handling spurious ^Zs. Will
* return lines from the standard macro set if this has not already
* been done.
*/
static char *read_line(void)
{
char *buffer, *p, *q;
int bufsize, continued_count;
/*
* standart macros set (predefined) goes first
*/
p = line_from_stdmac();
if (p)
return p;
/*
* regular read from a file
*/
bufsize = BUF_DELTA;
buffer = nasm_malloc(BUF_DELTA);
p = buffer;
continued_count = 0;
while (1) {
q = fgets(p, bufsize - (p - buffer), istk->fp);
if (!q)
break;
p += strlen(p);
if (p > buffer && p[-1] == '\n') {
/*
* Convert backslash-CRLF line continuation sequences into
* nothing at all (for DOS and Windows)
*/
if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
p -= 3;
*p = 0;
continued_count++;
}
/*
* Also convert backslash-LF line continuation sequences into
* nothing at all (for Unix)
*/
else if (((p - 1) > buffer) && (p[-2] == '\\')) {
p -= 2;
*p = 0;
continued_count++;
} else {
break;
}
}
if (p - buffer > bufsize - 10) {
int32_t offset = p - buffer;
bufsize += BUF_DELTA;
buffer = nasm_realloc(buffer, bufsize);
p = buffer + offset; /* prevent stale-pointer problems */
}
}
if (!q && p == buffer) {
nasm_free(buffer);
return NULL;
}
src_set_linnum(src_get_linnum() + istk->lineinc +
(continued_count * istk->lineinc));
/*
* Play safe: remove CRs as well as LFs, if any of either are
* present at the end of the line.
*/
while (--p >= buffer && (*p == '\n' || *p == '\r'))
*p = '\0';
/*
* Handle spurious ^Z, which may be inserted into source files
* by some file transfer utilities.
*/
buffer[strcspn(buffer, "\032")] = '\0';
list->line(LIST_READ, buffer);
return buffer;
}
/*
* Tokenize a line of text. This is a very simple process since we
* don't need to parse the value out of e.g. numeric tokens: we
* simply split one string into many.
*/
static Token *tokenize(char *line)
{
char c, *p = line;
enum pp_token_type type;
Token *list = NULL;
Token *t, **tail = &list;
while (*line) {
p = line;
if (*p == '%') {
p++;
if (*p == '+' && !nasm_isdigit(p[1])) {
p++;
type = TOK_PASTE;
} else if (nasm_isdigit(*p) ||
((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
do {
p++;
}
while (nasm_isdigit(*p));
type = TOK_PREPROC_ID;
} else if (*p == '{') {
p++;
while (*p) {
if (*p == '}')
break;
p[-1] = *p;
p++;
}
if (*p != '}')
error(ERR_WARNING | ERR_PASS1, "unterminated %{ construct");
p[-1] = '\0';
if (*p)
p++;
type = TOK_PREPROC_ID;
} else if (*p == '[') {
int lvl = 1;
line += 2; /* Skip the leading %[ */
p++;
while (lvl && (c = *p++)) {
switch (c) {
case ']':
lvl--;
break;
case '%':
if (*p == '[')
lvl++;
break;
case '\'':
case '\"':
case '`':
p = nasm_skip_string(p - 1) + 1;
break;
default:
break;
}
}
p--;
if (*p)
*p++ = '\0';
if (lvl)
error(ERR_NONFATAL, "unterminated %[ construct");
type = TOK_INDIRECT;
} else if (*p == '?') {
type = TOK_PREPROC_Q; /* %? */
p++;
if (*p == '?') {
type = TOK_PREPROC_QQ; /* %?? */
p++;
}
} else if (*p == '!') {
type = TOK_PREPROC_ID;
p++;
if (isidchar(*p)) {
do {
p++;
}
while (isidchar(*p));
} else if (*p == '\'' || *p == '\"' || *p == '`') {
p = nasm_skip_string(p);
if (*p)
p++;
else
error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
} else {
/* %! without string or identifier */
type = TOK_OTHER; /* Legacy behavior... */
}
} else if (isidchar(*p) ||
((*p == '!' || *p == '%' || *p == '$') &&
isidchar(p[1]))) {
do {
p++;
}
while (isidchar(*p));
type = TOK_PREPROC_ID;
} else {
type = TOK_OTHER;
if (*p == '%')
p++;
}
} else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
type = TOK_ID;
p++;
while (*p && isidchar(*p))
p++;
} else if (*p == '\'' || *p == '"' || *p == '`') {