Revert "BR3288901: Relax concat rules in preprocessor code"
[nasm.git] / preproc.c
blob5d94309d6a7a34d37fcb7e593cf6034fe204417b
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2011 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
44 * or
45 * {
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
48 * }
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
63 #include "compiler.h"
65 #include <stdio.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <stddef.h>
69 #include <string.h>
70 #include <ctype.h>
71 #include <limits.h>
72 #include <inttypes.h>
74 #include "nasm.h"
75 #include "nasmlib.h"
76 #include "preproc.h"
77 #include "hashtbl.h"
78 #include "quote.h"
79 #include "stdscan.h"
80 #include "eval.h"
81 #include "tokens.h"
82 #include "tables.h"
84 typedef struct SMacro SMacro;
85 typedef struct ExpDef ExpDef;
86 typedef struct ExpInv ExpInv;
87 typedef struct Context Context;
88 typedef struct Token Token;
89 typedef struct Blocks Blocks;
90 typedef struct Line Line;
91 typedef struct Include Include;
92 typedef struct Cond Cond;
93 typedef struct IncPath IncPath;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
107 struct SMacro {
108 SMacro *next;
109 char *name;
110 bool casesense;
111 bool in_progress;
112 unsigned int nparam;
113 Token *expansion;
117 * The context stack is composed of a linked list of these.
119 struct Context {
120 Context *next;
121 char *name;
122 struct hash_table localmac;
123 uint32_t number;
127 * This is the internal form which we break input lines up into.
128 * Typically stored in linked lists.
130 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
131 * necessarily used as-is, but is intended to denote the number of
132 * the substituted parameter. So in the definition
134 * %define a(x,y) ( (x) & ~(y) )
136 * the token representing `x' will have its type changed to
137 * TOK_SMAC_PARAM, but the one representing `y' will be
138 * TOK_SMAC_PARAM+1.
140 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
141 * which doesn't need quotes around it. Used in the pre-include
142 * mechanism as an alternative to trying to find a sensible type of
143 * quote to use on the filename we were passed.
145 enum pp_token_type {
146 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
147 TOK_PREPROC_ID, TOK_STRING,
148 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
149 TOK_INTERNAL_STRING,
150 TOK_PREPROC_Q, TOK_PREPROC_QQ,
151 TOK_PASTE, /* %+ */
152 TOK_INDIRECT, /* %[...] */
153 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
154 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
157 #define PP_CONCAT_MASK(x) (1 << (x))
159 struct tokseq_match {
160 int mask_head;
161 int mask_tail;
164 struct Token {
165 Token *next;
166 char *text;
167 union {
168 SMacro *mac; /* associated macro for TOK_SMAC_END */
169 size_t len; /* scratch length field */
170 } a; /* Auxiliary data */
171 enum pp_token_type type;
175 * Expansion definitions are stored as a linked list of
176 * these, which is essentially a container to allow several linked
177 * lists of Tokens.
179 * Note that in this module, linked lists are treated as stacks
180 * wherever possible. For this reason, Lines are _pushed_ on to the
181 * `last' field in ExpDef structures, so that the linked list,
182 * if walked, would emit the expansion lines in the proper order.
184 struct Line {
185 Line *next;
186 Token *first;
190 * Expansion Types
192 enum pp_exp_type {
193 EXP_NONE = 0, EXP_PREDEF,
194 EXP_MMACRO, EXP_REP,
195 EXP_IF, EXP_WHILE,
196 EXP_COMMENT, EXP_FINAL,
197 EXP_MAX = INT_MAX /* Keep compiler from reducing the range */
201 * Store the definition of an expansion, in which is any
202 * preprocessor directive that has an ending pair.
204 * This design allows for arbitrary expansion/recursion depth,
205 * upto the DEADMAN_LIMIT.
207 * The `next' field is used for storing ExpDef in hash tables; the
208 * `prev' field is for the global `expansions` linked-list.
210 struct ExpDef {
211 ExpDef *prev; /* previous definition */
212 ExpDef *next; /* next in hash table */
213 enum pp_exp_type type; /* expansion type */
214 char *name; /* definition name */
215 int nparam_min, nparam_max;
216 bool casesense;
217 bool plus; /* is the last parameter greedy? */
218 bool nolist; /* is this expansion listing-inhibited? */
219 Token *dlist; /* all defaults as one list */
220 Token **defaults; /* parameter default pointers */
221 int ndefs; /* number of default parameters */
223 int prepend; /* label prepend state */
224 Line *label;
225 Line *line;
226 Line *last;
227 int linecount; /* number of lines within expansion */
229 int64_t def_depth; /* current number of definition pairs deep */
230 int64_t cur_depth; /* current number of expansions */
231 int64_t max_depth; /* maximum number of expansions allowed */
233 int state; /* condition state */
234 bool ignoring; /* ignoring definition lines */
238 * Store the invocation of an expansion.
240 * The `prev' field is for the `istk->expansion` linked-list.
242 * When an expansion is being expanded, `params', `iline', `nparam',
243 * `paramlen', `rotate' and `unique' are local to the invocation.
245 struct ExpInv {
246 ExpInv *prev; /* previous invocation */
247 enum pp_exp_type type; /* expansion type */
248 ExpDef *def; /* pointer to expansion definition */
249 char *name; /* invocation name */
250 Line *label; /* pointer to label */
251 char *label_text; /* pointer to label text */
252 Line *current; /* pointer to current line in invocation */
254 Token **params; /* actual parameters */
255 Token *iline; /* invocation line */
256 unsigned int nparam, rotate;
257 int *paramlen;
259 uint64_t unique;
260 bool emitting;
261 int lineno; /* current line number in expansion */
262 int linnum; /* line number at invocation */
263 int relno; /* relative line number at invocation */
267 * To handle an arbitrary level of file inclusion, we maintain a
268 * stack (ie linked list) of these things.
270 struct Include {
271 Include *next;
272 FILE *fp;
273 Cond *conds;
274 ExpInv *expansion;
275 char *fname;
276 int lineno, lineinc;
277 int mmac_depth;
281 * Include search path. This is simply a list of strings which get
282 * prepended, in turn, to the name of an include file, in an
283 * attempt to find the file if it's not in the current directory.
285 struct IncPath {
286 IncPath *next;
287 char *path;
291 * Conditional assembly: we maintain a separate stack of these for
292 * each level of file inclusion. (The only reason we keep the
293 * stacks separate is to ensure that a stray `%endif' in a file
294 * included from within the true branch of a `%if' won't terminate
295 * it and cause confusion: instead, rightly, it'll cause an error.)
297 enum {
299 * These states are for use just after %if or %elif: IF_TRUE
300 * means the condition has evaluated to truth so we are
301 * currently emitting, whereas IF_FALSE means we are not
302 * currently emitting but will start doing so if a %else comes
303 * up. In these states, all directives are admissible: %elif,
304 * %else and %endif. (And of course %if.)
306 COND_IF_TRUE, COND_IF_FALSE,
308 * These states come up after a %else: ELSE_TRUE means we're
309 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
310 * any %elif or %else will cause an error.
312 COND_ELSE_TRUE, COND_ELSE_FALSE,
314 * These states mean that we're not emitting now, and also that
315 * nothing until %endif will be emitted at all. COND_DONE is
316 * used when we've had our moment of emission
317 * and have now started seeing %elifs. COND_NEVER is used when
318 * the condition construct in question is contained within a
319 * non-emitting branch of a larger condition construct,
320 * or if there is an error.
322 COND_DONE, COND_NEVER
324 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
327 * These defines are used as the possible return values for do_directive
329 #define NO_DIRECTIVE_FOUND 0
330 #define DIRECTIVE_FOUND 1
333 * This define sets the upper limit for smacro and expansions
335 #define DEADMAN_LIMIT (1 << 20)
337 /* max reps */
338 #define REP_LIMIT ((INT64_C(1) << 62))
341 * Condition codes. Note that we use c_ prefix not C_ because C_ is
342 * used in nasm.h for the "real" condition codes. At _this_ level,
343 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
344 * ones, so we need a different enum...
346 static const char * const conditions[] = {
347 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
348 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
349 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
351 enum pp_conds {
352 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
353 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
354 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
355 c_none = -1
357 static const enum pp_conds inverse_ccs[] = {
358 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
359 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,
360 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
363 /* For TASM compatibility we need to be able to recognise TASM compatible
364 * conditional compilation directives. Using the NASM pre-processor does
365 * not work, so we look for them specifically from the following list and
366 * then jam in the equivalent NASM directive into the input stream.
369 enum {
370 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
371 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
374 static const char * const tasm_directives[] = {
375 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
376 "ifndef", "include", "local"
379 static int StackSize = 4;
380 static char *StackPointer = "ebp";
381 static int ArgOffset = 8;
382 static int LocalOffset = 0;
384 static Context *cstk;
385 static Include *istk;
386 static IncPath *ipath = NULL;
388 static int pass; /* HACK: pass 0 = generate dependencies only */
389 static StrList **dephead, **deptail; /* Dependency list */
391 static uint64_t unique; /* unique identifier numbers */
393 static Line *predef = NULL;
394 static bool do_predef;
396 static ListGen *list;
399 * The current set of expansion definitions we have defined.
401 static struct hash_table expdefs;
404 * The current set of single-line macros we have defined.
406 static struct hash_table smacros;
409 * Linked List of all active expansion definitions
411 struct ExpDef *expansions = NULL;
414 * The expansion we are currently defining
416 static ExpDef *defining = NULL;
418 static uint64_t nested_mac_count;
419 static uint64_t nested_rep_count;
422 * Linked-list of lines to preprocess, prior to cleanup
424 static Line *finals = NULL;
425 static bool in_final = false;
428 * The number of macro parameters to allocate space for at a time.
430 #define PARAM_DELTA 16
433 * The standard macro set: defined in macros.c in the array nasm_stdmac.
434 * This gives our position in the macro set, when we're processing it.
436 static macros_t *stdmacpos;
439 * The extra standard macros that come from the object format, if
440 * any.
442 static macros_t *extrastdmac = NULL;
443 static bool any_extrastdmac;
446 * Tokens are allocated in blocks to improve speed
448 #define TOKEN_BLOCKSIZE 4096
449 static Token *freeTokens = NULL;
450 struct Blocks {
451 Blocks *next;
452 void *chunk;
455 static Blocks blocks = { NULL, NULL };
458 * Forward declarations.
460 static Token *expand_mmac_params(Token * tline);
461 static Token *expand_smacro(Token * tline);
462 static Token *expand_id(Token * tline);
463 static Context *get_ctx(const char *name, const char **namep,
464 bool all_contexts);
465 static void make_tok_num(Token * tok, int64_t val);
466 static void error(int severity, const char *fmt, ...);
467 static void error_precond(int severity, const char *fmt, ...);
468 static void *new_Block(size_t size);
469 static void delete_Blocks(void);
470 static Token *new_Token(Token * next, enum pp_token_type type,
471 const char *text, int txtlen);
472 static Token *copy_Token(Token * tline);
473 static Token *delete_Token(Token * t);
474 static Line *new_Line(void);
475 static ExpDef *new_ExpDef(int exp_type);
476 static ExpInv *new_ExpInv(int exp_type, ExpDef *ed);
479 * Macros for safe checking of token pointers, avoid *(NULL)
481 #define tok_type_(x,t) ((x) && (x)->type == (t))
482 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
483 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
484 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
486 #ifdef NASM_TRACE
488 #define stringify(x) #x
490 #define nasm_trace(msg, ...) printf("(%s:%d): " msg "\n", __func__, __LINE__, ##__VA_ARGS__)
491 #define nasm_dump_token(t) nasm_raw_dump_token(t, __FILE__, __LINE__, __func__);
492 #define nasm_dump_stream(t) nasm_raw_dump_stream(t, __FILE__, __LINE__, __func__);
494 /* FIXME: we really need some compound type here instead of inplace code */
495 static const char *nasm_get_tok_type_str(enum pp_token_type type)
497 #define SWITCH_TOK_NAME(type) \
498 case (type): \
499 return stringify(type)
501 switch (type) {
502 SWITCH_TOK_NAME(TOK_NONE);
503 SWITCH_TOK_NAME(TOK_WHITESPACE);
504 SWITCH_TOK_NAME(TOK_COMMENT);
505 SWITCH_TOK_NAME(TOK_ID);
506 SWITCH_TOK_NAME(TOK_PREPROC_ID);
507 SWITCH_TOK_NAME(TOK_STRING);
508 SWITCH_TOK_NAME(TOK_NUMBER);
509 SWITCH_TOK_NAME(TOK_FLOAT);
510 SWITCH_TOK_NAME(TOK_SMAC_END);
511 SWITCH_TOK_NAME(TOK_OTHER);
512 SWITCH_TOK_NAME(TOK_INTERNAL_STRING);
513 SWITCH_TOK_NAME(TOK_PREPROC_Q);
514 SWITCH_TOK_NAME(TOK_PREPROC_QQ);
515 SWITCH_TOK_NAME(TOK_PASTE);
516 SWITCH_TOK_NAME(TOK_INDIRECT);
517 SWITCH_TOK_NAME(TOK_SMAC_PARAM);
518 SWITCH_TOK_NAME(TOK_MAX);
521 return NULL;
524 static void nasm_raw_dump_token(Token *token, const char *file, int line, const char *func)
526 printf("---[%s (%s:%d): %p]---\n", func, file, line, (void *)token);
527 if (token) {
528 Token *t;
529 list_for_each(t, token) {
530 if (t->text)
531 printf("'%s'(%s) ", t->text,
532 nasm_get_tok_type_str(t->type));
534 printf("\n\n");
538 static void nasm_raw_dump_stream(Token *token, const char *file, int line, const char *func)
540 printf("---[%s (%s:%d): %p]---\n", func, file, line, (void *)token);
541 if (token) {
542 Token *t;
543 list_for_each(t, token)
544 printf("%s", t->text ? t->text : " ");
545 printf("\n\n");
549 #else
550 #define nasm_trace(msg, ...)
551 #define nasm_dump_token(t)
552 #define nasm_dump_stream(t)
553 #endif
556 * nasm_unquote with error if the string contains NUL characters.
557 * If the string contains NUL characters, issue an error and return
558 * the C len, i.e. truncate at the NUL.
560 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
562 size_t len = nasm_unquote(qstr, NULL);
563 size_t clen = strlen(qstr);
565 if (len != clen)
566 error(ERR_NONFATAL, "NUL character in `%s' directive",
567 pp_directives[directive]);
569 return clen;
573 * In-place reverse a list of tokens.
575 static Token *reverse_tokens(Token *t)
577 Token *prev, *next;
579 list_reverse(t, prev, next);
581 return t;
585 * Handle TASM specific directives, which do not contain a % in
586 * front of them. We do it here because I could not find any other
587 * place to do it for the moment, and it is a hack (ideally it would
588 * be nice to be able to use the NASM pre-processor to do it).
590 static char *check_tasm_directive(char *line)
592 int32_t i, j, k, m, len;
593 char *p, *q, *oldline, oldchar;
595 p = nasm_skip_spaces(line);
597 /* Binary search for the directive name */
598 i = -1;
599 j = ARRAY_SIZE(tasm_directives);
600 q = nasm_skip_word(p);
601 len = q - p;
602 if (len) {
603 oldchar = p[len];
604 p[len] = 0;
605 while (j - i > 1) {
606 k = (j + i) / 2;
607 m = nasm_stricmp(p, tasm_directives[k]);
608 if (m == 0) {
609 /* We have found a directive, so jam a % in front of it
610 * so that NASM will then recognise it as one if it's own.
612 p[len] = oldchar;
613 len = strlen(p);
614 oldline = line;
615 line = nasm_malloc(len + 2);
616 line[0] = '%';
617 if (k == TM_IFDIFI) {
619 * NASM does not recognise IFDIFI, so we convert
620 * it to %if 0. This is not used in NASM
621 * compatible code, but does need to parse for the
622 * TASM macro package.
624 strcpy(line + 1, "if 0");
625 } else {
626 memcpy(line + 1, p, len + 1);
628 nasm_free(oldline);
629 return line;
630 } else if (m < 0) {
631 j = k;
632 } else
633 i = k;
635 p[len] = oldchar;
637 return line;
641 * The pre-preprocessing stage... This function translates line
642 * number indications as they emerge from GNU cpp (`# lineno "file"
643 * flags') into NASM preprocessor line number indications (`%line
644 * lineno file').
646 static char *prepreproc(char *line)
648 int lineno, fnlen;
649 char *fname, *oldline;
651 if (line[0] == '#' && line[1] == ' ') {
652 oldline = line;
653 fname = oldline + 2;
654 lineno = atoi(fname);
655 fname += strspn(fname, "0123456789 ");
656 if (*fname == '"')
657 fname++;
658 fnlen = strcspn(fname, "\"");
659 line = nasm_malloc(20 + fnlen);
660 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
661 nasm_free(oldline);
663 if (tasm_compatible_mode)
664 return check_tasm_directive(line);
665 return line;
669 * Free a linked list of tokens.
671 static void free_tlist(Token * list)
673 while (list)
674 list = delete_Token(list);
678 * Free a linked list of lines.
680 static void free_llist(Line * list)
682 Line *l, *tmp;
683 list_for_each_safe(l, tmp, list) {
684 free_tlist(l->first);
685 nasm_free(l);
690 * Free an ExpDef
692 static void free_expdef(ExpDef * ed)
694 nasm_free(ed->name);
695 free_tlist(ed->dlist);
696 nasm_free(ed->defaults);
697 free_llist(ed->line);
698 nasm_free(ed);
702 * Free an ExpInv
704 static void free_expinv(ExpInv * ei)
706 if (ei->name != NULL)
707 nasm_free(ei->name);
708 if (ei->label_text != NULL)
709 nasm_free(ei->label_text);
710 nasm_free(ei);
714 * Free all currently defined macros, and free the hash tables
716 static void free_smacro_table(struct hash_table *smt)
718 SMacro *s, *tmp;
719 const char *key;
720 struct hash_tbl_node *it = NULL;
722 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
723 nasm_free((void *)key);
724 list_for_each_safe(s, tmp, s) {
725 nasm_free(s->name);
726 free_tlist(s->expansion);
727 nasm_free(s);
730 hash_free(smt);
733 static void free_expdef_table(struct hash_table *edt)
735 ExpDef *ed, *tmp;
736 const char *key;
737 struct hash_tbl_node *it = NULL;
739 it = NULL;
740 while ((ed = hash_iterate(edt, &it, &key)) != NULL) {
741 nasm_free((void *)key);
742 list_for_each_safe(ed ,tmp, ed)
743 free_expdef(ed);
745 hash_free(edt);
748 static void free_macros(void)
750 free_smacro_table(&smacros);
751 free_expdef_table(&expdefs);
755 * Initialize the hash tables
757 static void init_macros(void)
759 hash_init(&smacros, HASH_LARGE);
760 hash_init(&expdefs, HASH_LARGE);
764 * Pop the context stack.
766 static void ctx_pop(void)
768 Context *c = cstk;
770 cstk = cstk->next;
771 free_smacro_table(&c->localmac);
772 nasm_free(c->name);
773 nasm_free(c);
777 * Search for a key in the hash index; adding it if necessary
778 * (in which case we initialize the data pointer to NULL.)
780 static void **
781 hash_findi_add(struct hash_table *hash, const char *str)
783 struct hash_insert hi;
784 void **r;
785 char *strx;
787 r = hash_findi(hash, str, &hi);
788 if (r)
789 return r;
791 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
792 return hash_add(&hi, strx, NULL);
796 * Like hash_findi, but returns the data element rather than a pointer
797 * to it. Used only when not adding a new element, hence no third
798 * argument.
800 static void *
801 hash_findix(struct hash_table *hash, const char *str)
803 void **p;
805 p = hash_findi(hash, str, NULL);
806 return p ? *p : NULL;
810 * read line from standard macros set,
811 * if there no more left -- return NULL
813 static char *line_from_stdmac(void)
815 unsigned char c;
816 const unsigned char *p = stdmacpos;
817 char *line, *q;
818 size_t len = 0;
820 if (!stdmacpos)
821 return NULL;
823 while ((c = *p++)) {
824 if (c >= 0x80)
825 len += pp_directives_len[c - 0x80] + 1;
826 else
827 len++;
830 line = nasm_malloc(len + 1);
831 q = line;
832 while ((c = *stdmacpos++)) {
833 if (c >= 0x80) {
834 memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
835 q += pp_directives_len[c - 0x80];
836 *q++ = ' ';
837 } else {
838 *q++ = c;
841 stdmacpos = p;
842 *q = '\0';
844 if (!*stdmacpos) {
845 /* This was the last of the standard macro chain... */
846 stdmacpos = NULL;
847 if (any_extrastdmac) {
848 stdmacpos = extrastdmac;
849 any_extrastdmac = false;
850 } else if (do_predef) {
851 ExpInv *ei;
852 Line *pd, *l;
853 Token *head, **tail, *t;
856 * Nasty hack: here we push the contents of
857 * `predef' on to the top-level expansion stack,
858 * since this is the most convenient way to
859 * implement the pre-include and pre-define
860 * features.
862 list_for_each(pd, predef) {
863 head = NULL;
864 tail = &head;
865 list_for_each(t, pd->first) {
866 *tail = new_Token(NULL, t->type, t->text, 0);
867 tail = &(*tail)->next;
870 l = new_Line();
871 l->first = head;
872 ei = new_ExpInv(EXP_PREDEF, NULL);
873 ei->current = l;
874 ei->emitting = true;
875 ei->prev = istk->expansion;
876 istk->expansion = ei;
878 do_predef = false;
882 return line;
885 #define BUF_DELTA 512
887 * Read a line from the top file in istk, handling multiple CR/LFs
888 * at the end of the line read, and handling spurious ^Zs. Will
889 * return lines from the standard macro set if this has not already
890 * been done.
892 static char *read_line(void)
894 char *buffer, *p, *q;
895 int bufsize, continued_count;
898 * standart macros set (predefined) goes first
900 p = line_from_stdmac();
901 if (p)
902 return p;
905 * regular read from a file
907 bufsize = BUF_DELTA;
908 buffer = nasm_malloc(BUF_DELTA);
909 p = buffer;
910 continued_count = 0;
911 while (1) {
912 q = fgets(p, bufsize - (p - buffer), istk->fp);
913 if (!q)
914 break;
915 p += strlen(p);
916 if (p > buffer && p[-1] == '\n') {
918 * Convert backslash-CRLF line continuation sequences into
919 * nothing at all (for DOS and Windows)
921 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
922 p -= 3;
923 *p = 0;
924 continued_count++;
927 * Also convert backslash-LF line continuation sequences into
928 * nothing at all (for Unix)
930 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
931 p -= 2;
932 *p = 0;
933 continued_count++;
934 } else {
935 break;
938 if (p - buffer > bufsize - 10) {
939 int32_t offset = p - buffer;
940 bufsize += BUF_DELTA;
941 buffer = nasm_realloc(buffer, bufsize);
942 p = buffer + offset; /* prevent stale-pointer problems */
946 if (!q && p == buffer) {
947 nasm_free(buffer);
948 return NULL;
951 src_set_linnum(src_get_linnum() + istk->lineinc +
952 (continued_count * istk->lineinc));
955 * Play safe: remove CRs as well as LFs, if any of either are
956 * present at the end of the line.
958 while (--p >= buffer && (*p == '\n' || *p == '\r'))
959 *p = '\0';
962 * Handle spurious ^Z, which may be inserted into source files
963 * by some file transfer utilities.
965 buffer[strcspn(buffer, "\032")] = '\0';
967 list->line(LIST_READ, buffer);
969 return buffer;
973 * Tokenize a line of text. This is a very simple process since we
974 * don't need to parse the value out of e.g. numeric tokens: we
975 * simply split one string into many.
977 static Token *tokenize(char *line)
979 char c, *p = line;
980 enum pp_token_type type;
981 Token *list = NULL;
982 Token *t, **tail = &list;
983 bool verbose = true;
985 nasm_trace("Tokenize for '%s'", line);
987 if ((defining != NULL) && (defining->ignoring == true)) {
988 verbose = false;
991 while (*line) {
992 p = line;
993 if (*p == '%') {
994 p++;
995 if (*p == '+' && !nasm_isdigit(p[1])) {
996 p++;
997 type = TOK_PASTE;
998 } else if (nasm_isdigit(*p) ||
999 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
1000 do {
1001 p++;
1003 while (nasm_isdigit(*p));
1004 type = TOK_PREPROC_ID;
1005 } else if (*p == '{') {
1006 p++;
1007 while (*p && *p != '}') {
1008 p[-1] = *p;
1009 p++;
1011 p[-1] = '\0';
1012 if (*p)
1013 p++;
1014 type = TOK_PREPROC_ID;
1015 } else if (*p == '[') {
1016 int lvl = 1;
1017 line += 2; /* Skip the leading %[ */
1018 p++;
1019 while (lvl && (c = *p++)) {
1020 switch (c) {
1021 case ']':
1022 lvl--;
1023 break;
1024 case '%':
1025 if (*p == '[')
1026 lvl++;
1027 break;
1028 case '\'':
1029 case '\"':
1030 case '`':
1031 p = nasm_skip_string(p - 1) + 1;
1032 break;
1033 default:
1034 break;
1037 p--;
1038 if (*p)
1039 *p++ = '\0';
1040 if (lvl && verbose)
1041 error(ERR_NONFATAL, "unterminated %[ construct");
1042 type = TOK_INDIRECT;
1043 } else if (*p == '?') {
1044 type = TOK_PREPROC_Q; /* %? */
1045 p++;
1046 if (*p == '?') {
1047 type = TOK_PREPROC_QQ; /* %?? */
1048 p++;
1050 } else if (*p == '!') {
1051 type = TOK_PREPROC_ID;
1052 p++;
1053 if (isidchar(*p)) {
1054 do {
1055 p++;
1056 } while (isidchar(*p));
1057 } else if (*p == '\'' || *p == '\"' || *p == '`') {
1058 p = nasm_skip_string(p);
1059 if (*p)
1060 p++;
1061 else if(verbose)
1062 error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
1063 } else {
1064 /* %! without string or identifier */
1065 type = TOK_OTHER; /* Legacy behavior... */
1067 } else if (isidchar(*p) ||
1068 ((*p == '!' || *p == '%' || *p == '$') &&
1069 isidchar(p[1]))) {
1070 do {
1071 p++;
1073 while (isidchar(*p));
1074 type = TOK_PREPROC_ID;
1075 } else {
1076 type = TOK_OTHER;
1077 if (*p == '%')
1078 p++;
1080 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
1081 type = TOK_ID;
1082 p++;
1083 while (*p && isidchar(*p))
1084 p++;
1085 } else if (*p == '\'' || *p == '"' || *p == '`') {
1087 * A string token.
1089 type = TOK_STRING;
1090 p = nasm_skip_string(p);
1092 if (*p) {
1093 p++;
1094 } else if(verbose) {
1095 error(ERR_WARNING|ERR_PASS1, "unterminated string");
1096 /* Handling unterminated strings by UNV */
1097 /* type = -1; */
1099 } else if (p[0] == '$' && p[1] == '$') {
1100 type = TOK_OTHER; /* TOKEN_BASE */
1101 p += 2;
1102 } else if (isnumstart(*p)) {
1103 bool is_hex = false;
1104 bool is_float = false;
1105 bool has_e = false;
1106 char c, *r;
1109 * A numeric token.
1112 if (*p == '$') {
1113 p++;
1114 is_hex = true;
1117 for (;;) {
1118 c = *p++;
1120 if (!is_hex && (c == 'e' || c == 'E')) {
1121 has_e = true;
1122 if (*p == '+' || *p == '-') {
1124 * e can only be followed by +/- if it is either a
1125 * prefixed hex number or a floating-point number
1127 p++;
1128 is_float = true;
1130 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
1131 is_hex = true;
1132 } else if (c == 'P' || c == 'p') {
1133 is_float = true;
1134 if (*p == '+' || *p == '-')
1135 p++;
1136 } else if (isnumchar(c) || c == '_')
1137 ; /* just advance */
1138 else if (c == '.') {
1140 * we need to deal with consequences of the legacy
1141 * parser, like "1.nolist" being two tokens
1142 * (TOK_NUMBER, TOK_ID) here; at least give it
1143 * a shot for now. In the future, we probably need
1144 * a flex-based scanner with proper pattern matching
1145 * to do it as well as it can be done. Nothing in
1146 * the world is going to help the person who wants
1147 * 0x123.p16 interpreted as two tokens, though.
1149 r = p;
1150 while (*r == '_')
1151 r++;
1153 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
1154 (!is_hex && (*r == 'e' || *r == 'E')) ||
1155 (*r == 'p' || *r == 'P')) {
1156 p = r;
1157 is_float = true;
1158 } else
1159 break; /* Terminate the token */
1160 } else
1161 break;
1163 p--; /* Point to first character beyond number */
1165 if (p == line+1 && *line == '$') {
1166 type = TOK_OTHER; /* TOKEN_HERE */
1167 } else {
1168 if (has_e && !is_hex) {
1169 /* 1e13 is floating-point, but 1e13h is not */
1170 is_float = true;
1173 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1175 } else if (nasm_isspace(*p)) {
1176 type = TOK_WHITESPACE;
1177 p = nasm_skip_spaces(p);
1179 * Whitespace just before end-of-line is discarded by
1180 * pretending it's a comment; whitespace just before a
1181 * comment gets lumped into the comment.
1183 if (!*p || *p == ';') {
1184 type = TOK_COMMENT;
1185 while (*p)
1186 p++;
1188 } else if (*p == ';') {
1189 type = TOK_COMMENT;
1190 while (*p)
1191 p++;
1192 } else {
1194 * Anything else is an operator of some kind. We check
1195 * for all the double-character operators (>>, <<, //,
1196 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1197 * else is a single-character operator.
1199 type = TOK_OTHER;
1200 if ((p[0] == '>' && p[1] == '>') ||
1201 (p[0] == '<' && p[1] == '<') ||
1202 (p[0] == '/' && p[1] == '/') ||
1203 (p[0] == '<' && p[1] == '=') ||
1204 (p[0] == '>' && p[1] == '=') ||
1205 (p[0] == '=' && p[1] == '=') ||
1206 (p[0] == '!' && p[1] == '=') ||
1207 (p[0] == '<' && p[1] == '>') ||
1208 (p[0] == '&' && p[1] == '&') ||
1209 (p[0] == '|' && p[1] == '|') ||
1210 (p[0] == '^' && p[1] == '^')) {
1211 p++;
1213 p++;
1216 /* Handling unterminated string by UNV */
1217 /*if (type == -1)
1219 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1220 t->text[p-line] = *line;
1221 tail = &t->next;
1223 else */
1224 if (type != TOK_COMMENT) {
1225 *tail = t = new_Token(NULL, type, line, p - line);
1226 tail = &t->next;
1228 line = p;
1231 nasm_dump_token(list);
1233 return list;
1237 * this function allocates a new managed block of memory and
1238 * returns a pointer to the block. The managed blocks are
1239 * deleted only all at once by the delete_Blocks function.
1241 static void *new_Block(size_t size)
1243 Blocks *b = &blocks;
1245 /* first, get to the end of the linked list */
1246 while (b->next)
1247 b = b->next;
1249 /* now allocate the requested chunk */
1250 b->chunk = nasm_malloc(size);
1252 /* now allocate a new block for the next request */
1253 b->next = nasm_zalloc(sizeof(Blocks));
1255 return b->chunk;
1259 * this function deletes all managed blocks of memory
1261 static void delete_Blocks(void)
1263 Blocks *a, *b = &blocks;
1266 * keep in mind that the first block, pointed to by blocks
1267 * is a static and not dynamically allocated, so we don't
1268 * free it.
1270 while (b) {
1271 if (b->chunk)
1272 nasm_free(b->chunk);
1273 a = b;
1274 b = b->next;
1275 if (a != &blocks)
1276 nasm_free(a);
1281 * this function creates a new Token and passes a pointer to it
1282 * back to the caller. It sets the type and text elements, and
1283 * also the a.mac and next elements to NULL.
1285 static Token *new_Token(Token * next, enum pp_token_type type,
1286 const char *text, int txtlen)
1288 Token *t;
1289 int i;
1291 if (!freeTokens) {
1292 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1293 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1294 freeTokens[i].next = &freeTokens[i + 1];
1295 freeTokens[i].next = NULL;
1297 t = freeTokens;
1298 freeTokens = t->next;
1299 t->next = next;
1300 t->a.mac = NULL;
1301 t->type = type;
1302 if (type == TOK_WHITESPACE || !text) {
1303 t->text = NULL;
1304 } else {
1305 if (txtlen == 0)
1306 txtlen = strlen(text);
1307 t->text = nasm_malloc(txtlen+1);
1308 memcpy(t->text, text, txtlen);
1309 t->text[txtlen] = '\0';
1311 return t;
1314 static Token *copy_Token(Token * tline)
1316 Token *t, *tt, *first = NULL, *prev = NULL;
1317 int i;
1318 for (tt = tline; tt != NULL; tt = tt->next) {
1319 if (!freeTokens) {
1320 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1321 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1322 freeTokens[i].next = &freeTokens[i + 1];
1323 freeTokens[i].next = NULL;
1325 t = freeTokens;
1326 freeTokens = t->next;
1327 t->next = NULL;
1328 t->text = tt->text ? nasm_strdup(tt->text) : NULL;
1329 t->a.mac = tt->a.mac;
1330 t->a.len = tt->a.len;
1331 t->type = tt->type;
1332 if (prev != NULL) {
1333 prev->next = t;
1334 } else {
1335 first = t;
1337 prev = t;
1339 return first;
1342 static Token *delete_Token(Token * t)
1344 Token *next = t->next;
1345 nasm_free(t->text);
1346 t->next = freeTokens;
1347 freeTokens = t;
1348 return next;
1352 * Convert a line of tokens back into text.
1353 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1354 * will be transformed into ..@ctxnum.xxx
1356 static char *detoken(Token * tlist, bool expand_locals)
1358 Token *t;
1359 char *line, *p;
1360 const char *q;
1361 int len = 0;
1363 list_for_each(t, tlist) {
1364 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1365 char *v;
1366 char *q = t->text;
1368 v = t->text + 2;
1369 if (*v == '\'' || *v == '\"' || *v == '`') {
1370 size_t len = nasm_unquote(v, NULL);
1371 size_t clen = strlen(v);
1373 if (len != clen) {
1374 error(ERR_NONFATAL | ERR_PASS1,
1375 "NUL character in %! string");
1376 v = NULL;
1380 if (v) {
1381 char *p = getenv(v);
1382 if (!p) {
1383 error(ERR_NONFATAL | ERR_PASS1,
1384 "nonexistent environment variable `%s'", v);
1385 p = "";
1387 t->text = nasm_strdup(p);
1389 nasm_free(q);
1392 /* Expand local macros here and not during preprocessing */
1393 if (expand_locals &&
1394 t->type == TOK_PREPROC_ID && t->text &&
1395 t->text[0] == '%' && t->text[1] == '$') {
1396 const char *q;
1397 char *p;
1398 Context *ctx = get_ctx(t->text, &q, false);
1399 if (ctx) {
1400 char buffer[40];
1401 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1402 p = nasm_strcat(buffer, q);
1403 nasm_free(t->text);
1404 t->text = p;
1408 /* Expand %? and %?? directives */
1409 if ((istk->expansion != NULL) &&
1410 ((t->type == TOK_PREPROC_Q) ||
1411 (t->type == TOK_PREPROC_QQ))) {
1412 ExpInv *ei;
1413 for (ei = istk->expansion; ei != NULL; ei = ei->prev){
1414 if (ei->type == EXP_MMACRO) {
1415 nasm_free(t->text);
1416 if (t->type == TOK_PREPROC_Q) {
1417 t->text = nasm_strdup(ei->name);
1418 } else {
1419 t->text = nasm_strdup(ei->def->name);
1421 break;
1426 if (t->type == TOK_WHITESPACE)
1427 len++;
1428 else if (t->text)
1429 len += strlen(t->text);
1432 p = line = nasm_malloc(len + 1);
1434 list_for_each(t, tlist) {
1435 if (t->type == TOK_WHITESPACE) {
1436 *p++ = ' ';
1437 } else if (t->text) {
1438 q = t->text;
1439 while (*q)
1440 *p++ = *q++;
1443 *p = '\0';
1445 return line;
1449 * Initialize a new Line
1451 static inline Line *new_Line(void)
1453 return (Line *)nasm_zalloc(sizeof(Line));
1458 * Initialize a new Expansion Definition
1460 static ExpDef *new_ExpDef(int exp_type)
1462 ExpDef *ed = (ExpDef*)nasm_zalloc(sizeof(ExpDef));
1463 ed->type = exp_type;
1464 ed->casesense = true;
1465 ed->state = COND_NEVER;
1467 return ed;
1472 * Initialize a new Expansion Instance
1474 static ExpInv *new_ExpInv(int exp_type, ExpDef *ed)
1476 ExpInv *ei = (ExpInv*)nasm_zalloc(sizeof(ExpInv));
1477 ei->type = exp_type;
1478 ei->def = ed;
1479 ei->unique = ++unique;
1481 if ((istk->mmac_depth < 1) &&
1482 (istk->expansion == NULL) &&
1483 (ed != NULL) &&
1484 (ed->type != EXP_MMACRO) &&
1485 (ed->type != EXP_REP) &&
1486 (ed->type != EXP_WHILE)) {
1487 ei->linnum = src_get_linnum();
1488 src_set_linnum(ei->linnum - ed->linecount - 1);
1489 } else {
1490 ei->linnum = -1;
1492 if ((istk->expansion == NULL) ||
1493 (ei->type == EXP_MMACRO)) {
1494 ei->relno = 0;
1495 } else {
1496 ei->relno = istk->expansion->lineno;
1497 if (ed != NULL) {
1498 ei->relno -= (ed->linecount + 1);
1501 return ei;
1505 * A scanner, suitable for use by the expression evaluator, which
1506 * operates on a line of Tokens. Expects a pointer to a pointer to
1507 * the first token in the line to be passed in as its private_data
1508 * field.
1510 * FIX: This really needs to be unified with stdscan.
1512 static int ppscan(void *private_data, struct tokenval *tokval)
1514 Token **tlineptr = private_data;
1515 Token *tline;
1516 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1518 do {
1519 tline = *tlineptr;
1520 *tlineptr = tline ? tline->next : NULL;
1521 } while (tline && (tline->type == TOK_WHITESPACE ||
1522 tline->type == TOK_COMMENT));
1524 if (!tline)
1525 return tokval->t_type = TOKEN_EOS;
1527 tokval->t_charptr = tline->text;
1529 if (tline->text[0] == '$' && !tline->text[1])
1530 return tokval->t_type = TOKEN_HERE;
1531 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1532 return tokval->t_type = TOKEN_BASE;
1534 if (tline->type == TOK_ID) {
1535 p = tokval->t_charptr = tline->text;
1536 if (p[0] == '$') {
1537 tokval->t_charptr++;
1538 return tokval->t_type = TOKEN_ID;
1541 for (r = p, s = ourcopy; *r; r++) {
1542 if (r >= p+MAX_KEYWORD)
1543 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1544 *s++ = nasm_tolower(*r);
1546 *s = '\0';
1547 /* right, so we have an identifier sitting in temp storage. now,
1548 * is it actually a register or instruction name, or what? */
1549 return nasm_token_hash(ourcopy, tokval);
1552 if (tline->type == TOK_NUMBER) {
1553 bool rn_error;
1554 tokval->t_integer = readnum(tline->text, &rn_error);
1555 tokval->t_charptr = tline->text;
1556 if (rn_error)
1557 return tokval->t_type = TOKEN_ERRNUM;
1558 else
1559 return tokval->t_type = TOKEN_NUM;
1562 if (tline->type == TOK_FLOAT) {
1563 return tokval->t_type = TOKEN_FLOAT;
1566 if (tline->type == TOK_STRING) {
1567 char bq, *ep;
1569 bq = tline->text[0];
1570 tokval->t_charptr = tline->text;
1571 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1573 if (ep[0] != bq || ep[1] != '\0')
1574 return tokval->t_type = TOKEN_ERRSTR;
1575 else
1576 return tokval->t_type = TOKEN_STR;
1579 if (tline->type == TOK_OTHER) {
1580 if (!strcmp(tline->text, "<<"))
1581 return tokval->t_type = TOKEN_SHL;
1582 if (!strcmp(tline->text, ">>"))
1583 return tokval->t_type = TOKEN_SHR;
1584 if (!strcmp(tline->text, "//"))
1585 return tokval->t_type = TOKEN_SDIV;
1586 if (!strcmp(tline->text, "%%"))
1587 return tokval->t_type = TOKEN_SMOD;
1588 if (!strcmp(tline->text, "=="))
1589 return tokval->t_type = TOKEN_EQ;
1590 if (!strcmp(tline->text, "<>"))
1591 return tokval->t_type = TOKEN_NE;
1592 if (!strcmp(tline->text, "!="))
1593 return tokval->t_type = TOKEN_NE;
1594 if (!strcmp(tline->text, "<="))
1595 return tokval->t_type = TOKEN_LE;
1596 if (!strcmp(tline->text, ">="))
1597 return tokval->t_type = TOKEN_GE;
1598 if (!strcmp(tline->text, "&&"))
1599 return tokval->t_type = TOKEN_DBL_AND;
1600 if (!strcmp(tline->text, "^^"))
1601 return tokval->t_type = TOKEN_DBL_XOR;
1602 if (!strcmp(tline->text, "||"))
1603 return tokval->t_type = TOKEN_DBL_OR;
1607 * We have no other options: just return the first character of
1608 * the token text.
1610 return tokval->t_type = tline->text[0];
1614 * Compare a string to the name of an existing macro; this is a
1615 * simple wrapper which calls either strcmp or nasm_stricmp
1616 * depending on the value of the `casesense' parameter.
1618 static int mstrcmp(const char *p, const char *q, bool casesense)
1620 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1624 * Compare a string to the name of an existing macro; this is a
1625 * simple wrapper which calls either strcmp or nasm_stricmp
1626 * depending on the value of the `casesense' parameter.
1628 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1630 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1634 * Return the Context structure associated with a %$ token. Return
1635 * NULL, having _already_ reported an error condition, if the
1636 * context stack isn't deep enough for the supplied number of $
1637 * signs.
1638 * If all_contexts == true, contexts that enclose current are
1639 * also scanned for such smacro, until it is found; if not -
1640 * only the context that directly results from the number of $'s
1641 * in variable's name.
1643 * If "namep" is non-NULL, set it to the pointer to the macro name
1644 * tail, i.e. the part beyond %$...
1646 static Context *get_ctx(const char *name, const char **namep,
1647 bool all_contexts)
1649 Context *ctx;
1650 SMacro *m;
1651 int i;
1653 if (namep)
1654 *namep = name;
1656 if (!name || name[0] != '%' || name[1] != '$')
1657 return NULL;
1659 if (!cstk) {
1660 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1661 return NULL;
1664 name += 2;
1665 ctx = cstk;
1666 i = 0;
1667 while (ctx && *name == '$') {
1668 name++;
1669 i++;
1670 ctx = ctx->next;
1672 if (!ctx) {
1673 error(ERR_NONFATAL, "`%s': context stack is only"
1674 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1675 return NULL;
1678 if (namep)
1679 *namep = name;
1681 if (!all_contexts)
1682 return ctx;
1684 do {
1685 /* Search for this smacro in found context */
1686 m = hash_findix(&ctx->localmac, name);
1687 while (m) {
1688 if (!mstrcmp(m->name, name, m->casesense))
1689 return ctx;
1690 m = m->next;
1692 ctx = ctx->next;
1694 while (ctx);
1695 return NULL;
1699 * Check to see if a file is already in a string list
1701 static bool in_list(const StrList *list, const char *str)
1703 while (list) {
1704 if (!strcmp(list->str, str))
1705 return true;
1706 list = list->next;
1708 return false;
1712 * Open an include file. This routine must always return a valid
1713 * file pointer if it returns - it's responsible for throwing an
1714 * ERR_FATAL and bombing out completely if not. It should also try
1715 * the include path one by one until it finds the file or reaches
1716 * the end of the path.
1718 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1719 bool missing_ok)
1721 FILE *fp;
1722 char *prefix = "";
1723 IncPath *ip = ipath;
1724 int len = strlen(file);
1725 size_t prefix_len = 0;
1726 StrList *sl;
1728 while (1) {
1729 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1730 sl->next = NULL;
1731 memcpy(sl->str, prefix, prefix_len);
1732 memcpy(sl->str+prefix_len, file, len+1);
1733 fp = fopen(sl->str, "r");
1734 if (fp && dhead && !in_list(*dhead, sl->str)) {
1735 **dtail = sl;
1736 *dtail = &sl->next;
1737 } else {
1738 nasm_free(sl);
1740 if (fp)
1741 return fp;
1742 if (!ip) {
1743 if (!missing_ok)
1744 break;
1745 prefix = NULL;
1746 } else {
1747 prefix = ip->path;
1748 ip = ip->next;
1750 if (prefix) {
1751 prefix_len = strlen(prefix);
1752 } else {
1753 /* -MG given and file not found */
1754 if (dhead && !in_list(*dhead, file)) {
1755 sl = nasm_malloc(len+1+sizeof sl->next);
1756 sl->next = NULL;
1757 strcpy(sl->str, file);
1758 **dtail = sl;
1759 *dtail = &sl->next;
1761 return NULL;
1765 error(ERR_FATAL, "unable to open include file `%s'", file);
1766 return NULL;
1770 * Determine if we should warn on defining a single-line macro of
1771 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1772 * return true if _any_ single-line macro of that name is defined.
1773 * Otherwise, will return true if a single-line macro with either
1774 * `nparam' or no parameters is defined.
1776 * If a macro with precisely the right number of parameters is
1777 * defined, or nparam is -1, the address of the definition structure
1778 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1779 * is NULL, no action will be taken regarding its contents, and no
1780 * error will occur.
1782 * Note that this is also called with nparam zero to resolve
1783 * `ifdef'.
1785 * If you already know which context macro belongs to, you can pass
1786 * the context pointer as first parameter; if you won't but name begins
1787 * with %$ the context will be automatically computed. If all_contexts
1788 * is true, macro will be searched in outer contexts as well.
1790 static bool
1791 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1792 bool nocase)
1794 struct hash_table *smtbl;
1795 SMacro *m;
1797 if (ctx) {
1798 smtbl = &ctx->localmac;
1799 } else if (name[0] == '%' && name[1] == '$') {
1800 if (cstk)
1801 ctx = get_ctx(name, &name, false);
1802 if (!ctx)
1803 return false; /* got to return _something_ */
1804 smtbl = &ctx->localmac;
1805 } else {
1806 smtbl = &smacros;
1808 m = (SMacro *) hash_findix(smtbl, name);
1810 while (m) {
1811 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1812 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1813 if (defn) {
1814 if (nparam == (int) m->nparam || nparam == -1)
1815 *defn = m;
1816 else
1817 *defn = NULL;
1819 return true;
1821 m = m->next;
1824 return false;
1828 * Count and mark off the parameters in a multi-line macro call.
1829 * This is called both from within the multi-line macro expansion
1830 * code, and also to mark off the default parameters when provided
1831 * in a %macro definition line.
1833 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1835 int paramsize, brace;
1837 *nparam = paramsize = 0;
1838 *params = NULL;
1839 while (t) {
1840 /* +1: we need space for the final NULL */
1841 if (*nparam+1 >= paramsize) {
1842 paramsize += PARAM_DELTA;
1843 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1845 skip_white_(t);
1846 brace = false;
1847 if (tok_is_(t, "{"))
1848 brace = true;
1849 (*params)[(*nparam)++] = t;
1850 while (tok_isnt_(t, brace ? "}" : ","))
1851 t = t->next;
1852 if (t) { /* got a comma/brace */
1853 t = t->next;
1854 if (brace) {
1856 * Now we've found the closing brace, look further
1857 * for the comma.
1859 skip_white_(t);
1860 if (tok_isnt_(t, ",")) {
1861 error(ERR_NONFATAL,
1862 "braces do not enclose all of macro parameter");
1863 while (tok_isnt_(t, ","))
1864 t = t->next;
1866 if (t)
1867 t = t->next; /* eat the comma */
1874 * Determine whether one of the various `if' conditions is true or
1875 * not.
1877 * We must free the tline we get passed.
1879 static bool if_condition(Token * tline, enum preproc_token ct)
1881 enum pp_conditional i = PP_COND(ct);
1882 bool j;
1883 Token *t, *tt, **tptr, *origline;
1884 struct tokenval tokval;
1885 expr *evalresult;
1886 enum pp_token_type needtype;
1887 char *p;
1889 origline = tline;
1891 switch (i) {
1892 case PPC_IFCTX:
1893 j = false; /* have we matched yet? */
1894 while (true) {
1895 skip_white_(tline);
1896 if (!tline)
1897 break;
1898 if (tline->type != TOK_ID) {
1899 error(ERR_NONFATAL,
1900 "`%s' expects context identifiers", pp_directives[ct]);
1901 free_tlist(origline);
1902 return -1;
1904 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1905 j = true;
1906 tline = tline->next;
1908 break;
1910 case PPC_IFDEF:
1911 j = false; /* have we matched yet? */
1912 while (tline) {
1913 skip_white_(tline);
1914 if (!tline || (tline->type != TOK_ID &&
1915 (tline->type != TOK_PREPROC_ID ||
1916 tline->text[1] != '$'))) {
1917 error(ERR_NONFATAL,
1918 "`%s' expects macro identifiers", pp_directives[ct]);
1919 goto fail;
1921 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1922 j = true;
1923 tline = tline->next;
1925 break;
1927 case PPC_IFENV:
1928 tline = expand_smacro(tline);
1929 j = false; /* have we matched yet? */
1930 while (tline) {
1931 skip_white_(tline);
1932 if (!tline || (tline->type != TOK_ID &&
1933 tline->type != TOK_STRING &&
1934 (tline->type != TOK_PREPROC_ID ||
1935 tline->text[1] != '!'))) {
1936 error(ERR_NONFATAL,
1937 "`%s' expects environment variable names",
1938 pp_directives[ct]);
1939 goto fail;
1941 p = tline->text;
1942 if (tline->type == TOK_PREPROC_ID)
1943 p += 2; /* Skip leading %! */
1944 if (*p == '\'' || *p == '\"' || *p == '`')
1945 nasm_unquote_cstr(p, ct);
1946 if (getenv(p))
1947 j = true;
1948 tline = tline->next;
1950 break;
1952 case PPC_IFIDN:
1953 case PPC_IFIDNI:
1954 tline = expand_smacro(tline);
1955 t = tt = tline;
1956 while (tok_isnt_(tt, ","))
1957 tt = tt->next;
1958 if (!tt) {
1959 error(ERR_NONFATAL,
1960 "`%s' expects two comma-separated arguments",
1961 pp_directives[ct]);
1962 goto fail;
1964 tt = tt->next;
1965 j = true; /* assume equality unless proved not */
1966 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1967 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1968 error(ERR_NONFATAL, "`%s': more than one comma on line",
1969 pp_directives[ct]);
1970 goto fail;
1972 if (t->type == TOK_WHITESPACE) {
1973 t = t->next;
1974 continue;
1976 if (tt->type == TOK_WHITESPACE) {
1977 tt = tt->next;
1978 continue;
1980 if (tt->type != t->type) {
1981 j = false; /* found mismatching tokens */
1982 break;
1984 /* When comparing strings, need to unquote them first */
1985 if (t->type == TOK_STRING) {
1986 size_t l1 = nasm_unquote(t->text, NULL);
1987 size_t l2 = nasm_unquote(tt->text, NULL);
1989 if (l1 != l2) {
1990 j = false;
1991 break;
1993 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1994 j = false;
1995 break;
1997 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1998 j = false; /* found mismatching tokens */
1999 break;
2002 t = t->next;
2003 tt = tt->next;
2005 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
2006 j = false; /* trailing gunk on one end or other */
2007 break;
2009 case PPC_IFMACRO:
2011 bool found = false;
2012 ExpDef searching, *ed;
2014 skip_white_(tline);
2015 tline = expand_id(tline);
2016 if (!tok_type_(tline, TOK_ID)) {
2017 error(ERR_NONFATAL,
2018 "`%s' expects a macro name", pp_directives[ct]);
2019 goto fail;
2021 memset(&searching, 0, sizeof(searching));
2022 searching.name = nasm_strdup(tline->text);
2023 searching.casesense = true;
2024 searching.nparam_max = INT_MAX;
2025 tline = expand_smacro(tline->next);
2026 skip_white_(tline);
2027 if (!tline) {
2028 } else if (!tok_type_(tline, TOK_NUMBER)) {
2029 error(ERR_NONFATAL,
2030 "`%s' expects a parameter count or nothing",
2031 pp_directives[ct]);
2032 } else {
2033 searching.nparam_min = searching.nparam_max =
2034 readnum(tline->text, &j);
2035 if (j)
2036 error(ERR_NONFATAL,
2037 "unable to parse parameter count `%s'",
2038 tline->text);
2040 if (tline && tok_is_(tline->next, "-")) {
2041 tline = tline->next->next;
2042 if (tok_is_(tline, "*"))
2043 searching.nparam_max = INT_MAX;
2044 else if (!tok_type_(tline, TOK_NUMBER))
2045 error(ERR_NONFATAL,
2046 "`%s' expects a parameter count after `-'",
2047 pp_directives[ct]);
2048 else {
2049 searching.nparam_max = readnum(tline->text, &j);
2050 if (j)
2051 error(ERR_NONFATAL,
2052 "unable to parse parameter count `%s'",
2053 tline->text);
2054 if (searching.nparam_min > searching.nparam_max)
2055 error(ERR_NONFATAL,
2056 "minimum parameter count exceeds maximum");
2059 if (tline && tok_is_(tline->next, "+")) {
2060 tline = tline->next;
2061 searching.plus = true;
2063 ed = (ExpDef *) hash_findix(&expdefs, searching.name);
2064 while (ed != NULL) {
2065 if (!strcmp(ed->name, searching.name) &&
2066 (ed->nparam_min <= searching.nparam_max || searching.plus) &&
2067 (searching.nparam_min <= ed->nparam_max || ed->plus)) {
2068 found = true;
2069 break;
2071 ed = ed->next;
2073 if (tline && tline->next)
2074 error(ERR_WARNING|ERR_PASS1,
2075 "trailing garbage after %%ifmacro ignored");
2076 nasm_free(searching.name);
2077 j = found;
2078 break;
2081 case PPC_IFID:
2082 needtype = TOK_ID;
2083 goto iftype;
2084 case PPC_IFNUM:
2085 needtype = TOK_NUMBER;
2086 goto iftype;
2087 case PPC_IFSTR:
2088 needtype = TOK_STRING;
2089 goto iftype;
2091 iftype:
2092 t = tline = expand_smacro(tline);
2094 while (tok_type_(t, TOK_WHITESPACE) ||
2095 (needtype == TOK_NUMBER &&
2096 tok_type_(t, TOK_OTHER) &&
2097 (t->text[0] == '-' || t->text[0] == '+') &&
2098 !t->text[1]))
2099 t = t->next;
2101 j = tok_type_(t, needtype);
2102 break;
2104 case PPC_IFTOKEN:
2105 t = tline = expand_smacro(tline);
2106 while (tok_type_(t, TOK_WHITESPACE))
2107 t = t->next;
2109 j = false;
2110 if (t) {
2111 t = t->next; /* Skip the actual token */
2112 while (tok_type_(t, TOK_WHITESPACE))
2113 t = t->next;
2114 j = !t; /* Should be nothing left */
2116 break;
2118 case PPC_IFEMPTY:
2119 t = tline = expand_smacro(tline);
2120 while (tok_type_(t, TOK_WHITESPACE))
2121 t = t->next;
2123 j = !t; /* Should be empty */
2124 break;
2126 case PPC_IF:
2127 t = tline = expand_smacro(tline);
2128 tptr = &t;
2129 tokval.t_type = TOKEN_INVALID;
2130 evalresult = evaluate(ppscan, tptr, &tokval,
2131 NULL, pass | CRITICAL, error, NULL);
2132 if (!evalresult)
2133 return -1;
2134 if (tokval.t_type)
2135 error(ERR_WARNING|ERR_PASS1,
2136 "trailing garbage after expression ignored");
2137 if (!is_simple(evalresult)) {
2138 error(ERR_NONFATAL,
2139 "non-constant value given to `%s'", pp_directives[ct]);
2140 goto fail;
2142 j = reloc_value(evalresult) != 0;
2143 break;
2145 default:
2146 error(ERR_FATAL,
2147 "preprocessor directive `%s' not yet implemented",
2148 pp_directives[ct]);
2149 goto fail;
2152 free_tlist(origline);
2153 return j ^ PP_NEGATIVE(ct);
2155 fail:
2156 free_tlist(origline);
2157 return -1;
2161 * Common code for defining an smacro
2163 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
2164 int nparam, Token *expansion)
2166 SMacro *smac, **smhead;
2167 struct hash_table *smtbl;
2169 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
2170 if (!smac) {
2171 error(ERR_WARNING|ERR_PASS1,
2172 "single-line macro `%s' defined both with and"
2173 " without parameters", mname);
2175 * Some instances of the old code considered this a failure,
2176 * some others didn't. What is the right thing to do here?
2178 free_tlist(expansion);
2179 return false; /* Failure */
2180 } else {
2182 * We're redefining, so we have to take over an
2183 * existing SMacro structure. This means freeing
2184 * what was already in it.
2186 nasm_free(smac->name);
2187 free_tlist(smac->expansion);
2189 } else {
2190 smtbl = ctx ? &ctx->localmac : &smacros;
2191 smhead = (SMacro **) hash_findi_add(smtbl, mname);
2192 smac = nasm_zalloc(sizeof(SMacro));
2193 smac->next = *smhead;
2194 *smhead = smac;
2196 smac->name = nasm_strdup(mname);
2197 smac->casesense = casesense;
2198 smac->nparam = nparam;
2199 smac->expansion = expansion;
2200 smac->in_progress = false;
2201 return true; /* Success */
2205 * Undefine an smacro
2207 static void undef_smacro(Context *ctx, const char *mname)
2209 SMacro **smhead, *s, **sp;
2210 struct hash_table *smtbl;
2212 smtbl = ctx ? &ctx->localmac : &smacros;
2213 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
2215 if (smhead) {
2217 * We now have a macro name... go hunt for it.
2219 sp = smhead;
2220 while ((s = *sp) != NULL) {
2221 if (!mstrcmp(s->name, mname, s->casesense)) {
2222 *sp = s->next;
2223 nasm_free(s->name);
2224 free_tlist(s->expansion);
2225 nasm_free(s);
2226 } else {
2227 sp = &s->next;
2234 * Parse a mmacro specification.
2236 static bool parse_mmacro_spec(Token *tline, ExpDef *def, const char *directive)
2238 bool err;
2240 tline = tline->next;
2241 skip_white_(tline);
2242 tline = expand_id(tline);
2243 if (!tok_type_(tline, TOK_ID)) {
2244 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
2245 return false;
2248 def->name = nasm_strdup(tline->text);
2249 def->plus = false;
2250 def->nolist = false;
2251 // def->in_progress = 0;
2252 // def->rep_nest = NULL;
2253 def->nparam_min = 0;
2254 def->nparam_max = 0;
2256 tline = expand_smacro(tline->next);
2257 skip_white_(tline);
2258 if (!tok_type_(tline, TOK_NUMBER)) {
2259 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
2260 } else {
2261 def->nparam_min = def->nparam_max =
2262 readnum(tline->text, &err);
2263 if (err)
2264 error(ERR_NONFATAL,
2265 "unable to parse parameter count `%s'", tline->text);
2267 if (tline && tok_is_(tline->next, "-")) {
2268 tline = tline->next->next;
2269 if (tok_is_(tline, "*")) {
2270 def->nparam_max = INT_MAX;
2271 } else if (!tok_type_(tline, TOK_NUMBER)) {
2272 error(ERR_NONFATAL,
2273 "`%s' expects a parameter count after `-'", directive);
2274 } else {
2275 def->nparam_max = readnum(tline->text, &err);
2276 if (err) {
2277 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
2278 tline->text);
2280 if (def->nparam_min > def->nparam_max) {
2281 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
2285 if (tline && tok_is_(tline->next, "+")) {
2286 tline = tline->next;
2287 def->plus = true;
2289 if (tline && tok_type_(tline->next, TOK_ID) &&
2290 !nasm_stricmp(tline->next->text, ".nolist")) {
2291 tline = tline->next;
2292 def->nolist = true;
2296 * Handle default parameters.
2298 if (tline && tline->next) {
2299 def->dlist = tline->next;
2300 tline->next = NULL;
2301 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
2302 } else {
2303 def->dlist = NULL;
2304 def->defaults = NULL;
2306 def->line = NULL;
2308 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2309 !def->plus)
2310 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2311 "too many default macro parameters");
2313 return true;
2318 * Decode a size directive
2320 static int parse_size(const char *str) {
2321 static const char *size_names[] =
2322 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2323 static const int sizes[] =
2324 { 0, 1, 4, 16, 8, 10, 2, 32 };
2326 return sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1];
2330 * find and process preprocessor directive in passed line
2331 * Find out if a line contains a preprocessor directive, and deal
2332 * with it if so.
2334 * If a directive _is_ found, it is the responsibility of this routine
2335 * (and not the caller) to free_tlist() the line.
2337 * @param tline a pointer to the current tokeninzed line linked list
2338 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2341 static int do_directive(Token * tline)
2343 enum preproc_token i;
2344 int j;
2345 bool err;
2346 int nparam;
2347 bool nolist;
2348 bool casesense;
2349 int k, m;
2350 int offset;
2351 char *p, *pp;
2352 const char *mname;
2353 Include *inc;
2354 Context *ctx;
2355 Line *l;
2356 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2357 struct tokenval tokval;
2358 expr *evalresult;
2359 ExpDef *ed, *eed, **edhead;
2360 ExpInv *ei, *eei;
2361 int64_t count;
2362 size_t len;
2363 int severity;
2365 origline = tline;
2367 skip_white_(tline);
2368 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2369 (tline->text[1] == '%' || tline->text[1] == '$'
2370 || tline->text[1] == '!'))
2371 return NO_DIRECTIVE_FOUND;
2373 i = pp_token_hash(tline->text);
2375 switch (i) {
2376 case PP_INVALID:
2377 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2378 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2379 tline->text);
2380 return NO_DIRECTIVE_FOUND; /* didn't get it */
2382 case PP_STACKSIZE:
2383 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2384 /* Directive to tell NASM what the default stack size is. The
2385 * default is for a 16-bit stack, and this can be overriden with
2386 * %stacksize large.
2388 tline = tline->next;
2389 if (tline && tline->type == TOK_WHITESPACE)
2390 tline = tline->next;
2391 if (!tline || tline->type != TOK_ID) {
2392 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2393 free_tlist(origline);
2394 return DIRECTIVE_FOUND;
2396 if (nasm_stricmp(tline->text, "flat") == 0) {
2397 /* All subsequent ARG directives are for a 32-bit stack */
2398 StackSize = 4;
2399 StackPointer = "ebp";
2400 ArgOffset = 8;
2401 LocalOffset = 0;
2402 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2403 /* All subsequent ARG directives are for a 64-bit stack */
2404 StackSize = 8;
2405 StackPointer = "rbp";
2406 ArgOffset = 16;
2407 LocalOffset = 0;
2408 } else if (nasm_stricmp(tline->text, "large") == 0) {
2409 /* All subsequent ARG directives are for a 16-bit stack,
2410 * far function call.
2412 StackSize = 2;
2413 StackPointer = "bp";
2414 ArgOffset = 4;
2415 LocalOffset = 0;
2416 } else if (nasm_stricmp(tline->text, "small") == 0) {
2417 /* All subsequent ARG directives are for a 16-bit stack,
2418 * far function call. We don't support near functions.
2420 StackSize = 2;
2421 StackPointer = "bp";
2422 ArgOffset = 6;
2423 LocalOffset = 0;
2424 } else {
2425 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2426 free_tlist(origline);
2427 return DIRECTIVE_FOUND;
2429 free_tlist(origline);
2430 return DIRECTIVE_FOUND;
2432 case PP_ARG:
2433 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2434 /* TASM like ARG directive to define arguments to functions, in
2435 * the following form:
2437 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2439 offset = ArgOffset;
2440 do {
2441 char *arg, directive[256];
2442 int size = StackSize;
2444 /* Find the argument name */
2445 tline = tline->next;
2446 if (tline && tline->type == TOK_WHITESPACE)
2447 tline = tline->next;
2448 if (!tline || tline->type != TOK_ID) {
2449 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2450 free_tlist(origline);
2451 return DIRECTIVE_FOUND;
2453 arg = tline->text;
2455 /* Find the argument size type */
2456 tline = tline->next;
2457 if (!tline || tline->type != TOK_OTHER
2458 || tline->text[0] != ':') {
2459 error(ERR_NONFATAL,
2460 "Syntax error processing `%%arg' directive");
2461 free_tlist(origline);
2462 return DIRECTIVE_FOUND;
2464 tline = tline->next;
2465 if (!tline || tline->type != TOK_ID) {
2466 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2467 free_tlist(origline);
2468 return DIRECTIVE_FOUND;
2471 /* Allow macro expansion of type parameter */
2472 tt = tokenize(tline->text);
2473 tt = expand_smacro(tt);
2474 size = parse_size(tt->text);
2475 if (!size) {
2476 error(ERR_NONFATAL,
2477 "Invalid size type for `%%arg' missing directive");
2478 free_tlist(tt);
2479 free_tlist(origline);
2480 return DIRECTIVE_FOUND;
2482 free_tlist(tt);
2484 /* Round up to even stack slots */
2485 size = ALIGN(size, StackSize);
2487 /* Now define the macro for the argument */
2488 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2489 arg, StackPointer, offset);
2490 do_directive(tokenize(directive));
2491 offset += size;
2493 /* Move to the next argument in the list */
2494 tline = tline->next;
2495 if (tline && tline->type == TOK_WHITESPACE)
2496 tline = tline->next;
2497 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2498 ArgOffset = offset;
2499 free_tlist(origline);
2500 return DIRECTIVE_FOUND;
2502 case PP_LOCAL:
2503 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2504 /* TASM like LOCAL directive to define local variables for a
2505 * function, in the following form:
2507 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2509 * The '= LocalSize' at the end is ignored by NASM, but is
2510 * required by TASM to define the local parameter size (and used
2511 * by the TASM macro package).
2513 offset = LocalOffset;
2514 do {
2515 char *local, directive[256];
2516 int size = StackSize;
2518 /* Find the argument name */
2519 tline = tline->next;
2520 if (tline && tline->type == TOK_WHITESPACE)
2521 tline = tline->next;
2522 if (!tline || tline->type != TOK_ID) {
2523 error(ERR_NONFATAL,
2524 "`%%local' missing argument parameter");
2525 free_tlist(origline);
2526 return DIRECTIVE_FOUND;
2528 local = tline->text;
2530 /* Find the argument size type */
2531 tline = tline->next;
2532 if (!tline || tline->type != TOK_OTHER
2533 || tline->text[0] != ':') {
2534 error(ERR_NONFATAL,
2535 "Syntax error processing `%%local' directive");
2536 free_tlist(origline);
2537 return DIRECTIVE_FOUND;
2539 tline = tline->next;
2540 if (!tline || tline->type != TOK_ID) {
2541 error(ERR_NONFATAL,
2542 "`%%local' missing size type parameter");
2543 free_tlist(origline);
2544 return DIRECTIVE_FOUND;
2547 /* Allow macro expansion of type parameter */
2548 tt = tokenize(tline->text);
2549 tt = expand_smacro(tt);
2550 size = parse_size(tt->text);
2551 if (!size) {
2552 error(ERR_NONFATAL,
2553 "Invalid size type for `%%local' missing directive");
2554 free_tlist(tt);
2555 free_tlist(origline);
2556 return DIRECTIVE_FOUND;
2558 free_tlist(tt);
2560 /* Round up to even stack slots */
2561 size = ALIGN(size, StackSize);
2563 offset += size; /* Negative offset, increment before */
2565 /* Now define the macro for the argument */
2566 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2567 local, StackPointer, offset);
2568 do_directive(tokenize(directive));
2570 /* Now define the assign to setup the enter_c macro correctly */
2571 snprintf(directive, sizeof(directive),
2572 "%%assign %%$localsize %%$localsize+%d", size);
2573 do_directive(tokenize(directive));
2575 /* Move to the next argument in the list */
2576 tline = tline->next;
2577 if (tline && tline->type == TOK_WHITESPACE)
2578 tline = tline->next;
2579 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2580 LocalOffset = offset;
2581 free_tlist(origline);
2582 return DIRECTIVE_FOUND;
2584 case PP_CLEAR:
2585 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2586 if (tline->next)
2587 error(ERR_WARNING|ERR_PASS1,
2588 "trailing garbage after `%%clear' ignored");
2589 free_macros();
2590 init_macros();
2591 free_tlist(origline);
2592 return DIRECTIVE_FOUND;
2594 case PP_DEPEND:
2595 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2596 t = tline->next = expand_smacro(tline->next);
2597 skip_white_(t);
2598 if (!t || (t->type != TOK_STRING &&
2599 t->type != TOK_INTERNAL_STRING)) {
2600 error(ERR_NONFATAL, "`%%depend' expects a file name");
2601 free_tlist(origline);
2602 return DIRECTIVE_FOUND; /* but we did _something_ */
2604 if (t->next)
2605 error(ERR_WARNING|ERR_PASS1,
2606 "trailing garbage after `%%depend' ignored");
2607 p = t->text;
2608 if (t->type != TOK_INTERNAL_STRING)
2609 nasm_unquote_cstr(p, i);
2610 if (dephead && !in_list(*dephead, p)) {
2611 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2612 sl->next = NULL;
2613 strcpy(sl->str, p);
2614 *deptail = sl;
2615 deptail = &sl->next;
2617 free_tlist(origline);
2618 return DIRECTIVE_FOUND;
2620 case PP_INCLUDE:
2621 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2622 t = tline->next = expand_smacro(tline->next);
2623 skip_white_(t);
2625 if (!t || (t->type != TOK_STRING &&
2626 t->type != TOK_INTERNAL_STRING)) {
2627 error(ERR_NONFATAL, "`%%include' expects a file name");
2628 free_tlist(origline);
2629 return DIRECTIVE_FOUND; /* but we did _something_ */
2631 if (t->next)
2632 error(ERR_WARNING|ERR_PASS1,
2633 "trailing garbage after `%%include' ignored");
2634 p = t->text;
2635 if (t->type != TOK_INTERNAL_STRING)
2636 nasm_unquote_cstr(p, i);
2637 inc = nasm_zalloc(sizeof(Include));
2638 inc->next = istk;
2639 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2640 if (!inc->fp) {
2641 /* -MG given but file not found */
2642 nasm_free(inc);
2643 } else {
2644 inc->fname = src_set_fname(nasm_strdup(p));
2645 inc->lineno = src_set_linnum(0);
2646 inc->lineinc = 1;
2647 inc->expansion = NULL;
2648 istk = inc;
2649 list->uplevel(LIST_INCLUDE);
2651 free_tlist(origline);
2652 return DIRECTIVE_FOUND;
2654 case PP_USE:
2655 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2657 static macros_t *use_pkg;
2658 const char *pkg_macro = NULL;
2660 tline = tline->next;
2661 skip_white_(tline);
2662 tline = expand_id(tline);
2664 if (!tline || (tline->type != TOK_STRING &&
2665 tline->type != TOK_INTERNAL_STRING &&
2666 tline->type != TOK_ID)) {
2667 error(ERR_NONFATAL, "`%%use' expects a package name");
2668 free_tlist(origline);
2669 return DIRECTIVE_FOUND; /* but we did _something_ */
2671 if (tline->next)
2672 error(ERR_WARNING|ERR_PASS1,
2673 "trailing garbage after `%%use' ignored");
2674 if (tline->type == TOK_STRING)
2675 nasm_unquote_cstr(tline->text, i);
2676 use_pkg = nasm_stdmac_find_package(tline->text);
2677 if (!use_pkg)
2678 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2679 else
2680 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2681 if (use_pkg && ! smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2682 /* Not already included, go ahead and include it */
2683 stdmacpos = use_pkg;
2685 free_tlist(origline);
2686 return DIRECTIVE_FOUND;
2688 case PP_PUSH:
2689 case PP_REPL:
2690 case PP_POP:
2691 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2692 tline = tline->next;
2693 skip_white_(tline);
2694 tline = expand_id(tline);
2695 if (tline) {
2696 if (!tok_type_(tline, TOK_ID)) {
2697 error(ERR_NONFATAL, "`%s' expects a context identifier",
2698 pp_directives[i]);
2699 free_tlist(origline);
2700 return DIRECTIVE_FOUND; /* but we did _something_ */
2702 if (tline->next)
2703 error(ERR_WARNING|ERR_PASS1,
2704 "trailing garbage after `%s' ignored",
2705 pp_directives[i]);
2706 p = nasm_strdup(tline->text);
2707 } else {
2708 p = NULL; /* Anonymous */
2711 if (i == PP_PUSH) {
2712 ctx = nasm_zalloc(sizeof(Context));
2713 ctx->next = cstk;
2714 hash_init(&ctx->localmac, HASH_SMALL);
2715 ctx->name = p;
2716 ctx->number = unique++;
2717 cstk = ctx;
2718 } else {
2719 /* %pop or %repl */
2720 if (!cstk) {
2721 error(ERR_NONFATAL, "`%s': context stack is empty",
2722 pp_directives[i]);
2723 } else if (i == PP_POP) {
2724 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2725 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2726 "expected %s",
2727 cstk->name ? cstk->name : "anonymous", p);
2728 else
2729 ctx_pop();
2730 } else {
2731 /* i == PP_REPL */
2732 nasm_free(cstk->name);
2733 cstk->name = p;
2734 p = NULL;
2736 nasm_free(p);
2738 free_tlist(origline);
2739 return DIRECTIVE_FOUND;
2740 case PP_FATAL:
2741 severity = ERR_FATAL;
2742 goto issue_error;
2743 case PP_ERROR:
2744 severity = ERR_NONFATAL;
2745 goto issue_error;
2746 case PP_WARNING:
2747 severity = ERR_WARNING|ERR_WARN_USER;
2748 goto issue_error;
2750 issue_error:
2751 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2753 /* Only error out if this is the final pass */
2754 if (pass != 2 && i != PP_FATAL)
2755 return DIRECTIVE_FOUND;
2757 tline->next = expand_smacro(tline->next);
2758 tline = tline->next;
2759 skip_white_(tline);
2760 t = tline ? tline->next : NULL;
2761 skip_white_(t);
2762 if (tok_type_(tline, TOK_STRING) && !t) {
2763 /* The line contains only a quoted string */
2764 p = tline->text;
2765 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2766 error(severity, "%s", p);
2767 } else {
2768 /* Not a quoted string, or more than a quoted string */
2769 p = detoken(tline, false);
2770 error(severity, "%s", p);
2771 nasm_free(p);
2773 free_tlist(origline);
2774 return DIRECTIVE_FOUND;
2777 CASE_PP_IF:
2778 if (defining != NULL) {
2779 if (defining->type == EXP_IF) {
2780 defining->def_depth ++;
2782 return NO_DIRECTIVE_FOUND;
2784 if ((istk->expansion != NULL) &&
2785 (istk->expansion->emitting == false)) {
2786 j = COND_NEVER;
2787 } else {
2788 j = if_condition(tline->next, i);
2789 tline->next = NULL; /* it got freed */
2790 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
2792 ed = new_ExpDef(EXP_IF);
2793 ed->state = j;
2794 ed->nolist = NULL;
2795 ed->def_depth = 0;
2796 ed->cur_depth = 0;
2797 ed->max_depth = 0;
2798 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
2799 ed->prev = defining;
2800 defining = ed;
2801 free_tlist(origline);
2802 return DIRECTIVE_FOUND;
2804 CASE_PP_ELIF:
2805 if (defining != NULL) {
2806 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2807 return NO_DIRECTIVE_FOUND;
2810 if ((defining == NULL) || (defining->type != EXP_IF)) {
2811 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2813 switch (defining->state) {
2814 case COND_IF_TRUE:
2815 defining->state = COND_DONE;
2816 defining->ignoring = true;
2817 break;
2819 case COND_DONE:
2820 case COND_NEVER:
2821 defining->ignoring = true;
2822 break;
2824 case COND_ELSE_TRUE:
2825 case COND_ELSE_FALSE:
2826 error_precond(ERR_WARNING|ERR_PASS1,
2827 "`%%elif' after `%%else' ignored");
2828 defining->state = COND_NEVER;
2829 defining->ignoring = true;
2830 break;
2832 case COND_IF_FALSE:
2834 * IMPORTANT: In the case of %if, we will already have
2835 * called expand_mmac_params(); however, if we're
2836 * processing an %elif we must have been in a
2837 * non-emitting mode, which would have inhibited
2838 * the normal invocation of expand_mmac_params().
2839 * Therefore, we have to do it explicitly here.
2841 j = if_condition(expand_mmac_params(tline->next), i);
2842 tline->next = NULL; /* it got freed */
2843 defining->state =
2844 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2845 defining->ignoring = ((defining->state == COND_IF_TRUE) ? false : true);
2846 break;
2848 free_tlist(origline);
2849 return DIRECTIVE_FOUND;
2851 case PP_ELSE:
2852 if (defining != NULL) {
2853 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2854 return NO_DIRECTIVE_FOUND;
2857 if (tline->next)
2858 error_precond(ERR_WARNING|ERR_PASS1,
2859 "trailing garbage after `%%else' ignored");
2860 if ((defining == NULL) || (defining->type != EXP_IF)) {
2861 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2863 switch (defining->state) {
2864 case COND_IF_TRUE:
2865 case COND_DONE:
2866 defining->state = COND_ELSE_FALSE;
2867 defining->ignoring = true;
2868 break;
2870 case COND_NEVER:
2871 defining->ignoring = true;
2872 break;
2874 case COND_IF_FALSE:
2875 defining->state = COND_ELSE_TRUE;
2876 defining->ignoring = false;
2877 break;
2879 case COND_ELSE_TRUE:
2880 case COND_ELSE_FALSE:
2881 error_precond(ERR_WARNING|ERR_PASS1,
2882 "`%%else' after `%%else' ignored.");
2883 defining->state = COND_NEVER;
2884 defining->ignoring = true;
2885 break;
2887 free_tlist(origline);
2888 return DIRECTIVE_FOUND;
2890 case PP_ENDIF:
2891 if (defining != NULL) {
2892 if (defining->type == EXP_IF) {
2893 if (defining->def_depth > 0) {
2894 defining->def_depth --;
2895 return NO_DIRECTIVE_FOUND;
2897 } else {
2898 return NO_DIRECTIVE_FOUND;
2901 if (tline->next)
2902 error_precond(ERR_WARNING|ERR_PASS1,
2903 "trailing garbage after `%%endif' ignored");
2904 if ((defining == NULL) || (defining->type != EXP_IF)) {
2905 error(ERR_NONFATAL, "`%%endif': no matching `%%if'");
2906 return DIRECTIVE_FOUND;
2908 ed = defining;
2909 defining = ed->prev;
2910 ed->prev = expansions;
2911 expansions = ed;
2912 ei = new_ExpInv(EXP_IF, ed);
2913 ei->current = ed->line;
2914 ei->emitting = true;
2915 ei->prev = istk->expansion;
2916 istk->expansion = ei;
2917 free_tlist(origline);
2918 return DIRECTIVE_FOUND;
2920 case PP_RMACRO:
2921 case PP_IRMACRO:
2922 case PP_MACRO:
2923 case PP_IMACRO:
2924 if (defining != NULL) {
2925 if (defining->type == EXP_MMACRO) {
2926 defining->def_depth ++;
2928 return NO_DIRECTIVE_FOUND;
2930 ed = new_ExpDef(EXP_MMACRO);
2931 ed->max_depth =
2932 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2933 ed->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2934 if (!parse_mmacro_spec(tline, ed, pp_directives[i])) {
2935 nasm_free(ed);
2936 ed = NULL;
2937 return DIRECTIVE_FOUND;
2939 ed->def_depth = 0;
2940 ed->cur_depth = 0;
2941 ed->max_depth = (ed->max_depth + 1);
2942 ed->ignoring = false;
2943 ed->prev = defining;
2944 defining = ed;
2946 eed = (ExpDef *) hash_findix(&expdefs, ed->name);
2947 while (eed) {
2948 if (!strcmp(eed->name, ed->name) &&
2949 (eed->nparam_min <= ed->nparam_max || ed->plus) &&
2950 (ed->nparam_min <= eed->nparam_max || eed->plus)) {
2951 error(ERR_WARNING|ERR_PASS1,
2952 "redefining multi-line macro `%s'", ed->name);
2953 return DIRECTIVE_FOUND;
2955 eed = eed->next;
2957 free_tlist(origline);
2958 return DIRECTIVE_FOUND;
2960 case PP_ENDM:
2961 case PP_ENDMACRO:
2962 if (defining != NULL) {
2963 if (defining->type == EXP_MMACRO) {
2964 if (defining->def_depth > 0) {
2965 defining->def_depth --;
2966 return NO_DIRECTIVE_FOUND;
2968 } else {
2969 return NO_DIRECTIVE_FOUND;
2972 if (!(defining) || (defining->type != EXP_MMACRO)) {
2973 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2974 return DIRECTIVE_FOUND;
2976 edhead = (ExpDef **) hash_findi_add(&expdefs, defining->name);
2977 defining->next = *edhead;
2978 *edhead = defining;
2979 ed = defining;
2980 defining = ed->prev;
2981 ed->prev = expansions;
2982 expansions = ed;
2983 ed = NULL;
2984 free_tlist(origline);
2985 return DIRECTIVE_FOUND;
2987 case PP_EXITMACRO:
2988 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2990 * We must search along istk->expansion until we hit a
2991 * macro invocation. Then we disable the emitting state(s)
2992 * between exitmacro and endmacro.
2994 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
2995 if(ei->type == EXP_MMACRO) {
2996 break;
3000 if (ei != NULL) {
3002 * Set all invocations leading back to the macro
3003 * invocation to a non-emitting state.
3005 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3006 eei->emitting = false;
3008 eei->emitting = false;
3009 } else {
3010 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
3012 free_tlist(origline);
3013 return DIRECTIVE_FOUND;
3015 case PP_UNMACRO:
3016 case PP_UNIMACRO:
3017 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3019 ExpDef **ed_p;
3020 ExpDef spec;
3022 spec.casesense = (i == PP_UNMACRO);
3023 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
3024 return DIRECTIVE_FOUND;
3026 ed_p = (ExpDef **) hash_findi(&expdefs, spec.name, NULL);
3027 while (ed_p && *ed_p) {
3028 ed = *ed_p;
3029 if (ed->casesense == spec.casesense &&
3030 !mstrcmp(ed->name, spec.name, spec.casesense) &&
3031 ed->nparam_min == spec.nparam_min &&
3032 ed->nparam_max == spec.nparam_max &&
3033 ed->plus == spec.plus) {
3034 if (ed->cur_depth > 0) {
3035 error(ERR_NONFATAL, "`%s' ignored on active macro",
3036 pp_directives[i]);
3037 break;
3038 } else {
3039 *ed_p = ed->next;
3040 free_expdef(ed);
3042 } else {
3043 ed_p = &ed->next;
3046 free_tlist(origline);
3047 free_tlist(spec.dlist);
3048 return DIRECTIVE_FOUND;
3051 case PP_ROTATE:
3052 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3053 if (tline->next && tline->next->type == TOK_WHITESPACE)
3054 tline = tline->next;
3055 if (!tline->next) {
3056 free_tlist(origline);
3057 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
3058 return DIRECTIVE_FOUND;
3060 t = expand_smacro(tline->next);
3061 tline->next = NULL;
3062 free_tlist(origline);
3063 tline = t;
3064 tptr = &t;
3065 tokval.t_type = TOKEN_INVALID;
3066 evalresult =
3067 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3068 free_tlist(tline);
3069 if (!evalresult)
3070 return DIRECTIVE_FOUND;
3071 if (tokval.t_type)
3072 error(ERR_WARNING|ERR_PASS1,
3073 "trailing garbage after expression ignored");
3074 if (!is_simple(evalresult)) {
3075 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
3076 return DIRECTIVE_FOUND;
3078 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3079 if (ei->type == EXP_MMACRO) {
3080 break;
3083 if (ei == NULL) {
3084 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
3085 } else if (ei->nparam == 0) {
3086 error(ERR_NONFATAL,
3087 "`%%rotate' invoked within macro without parameters");
3088 } else {
3089 int rotate = ei->rotate + reloc_value(evalresult);
3091 rotate %= (int)ei->nparam;
3092 if (rotate < 0)
3093 rotate += ei->nparam;
3094 ei->rotate = rotate;
3096 return DIRECTIVE_FOUND;
3098 case PP_REP:
3099 if (defining != NULL) {
3100 if (defining->type == EXP_REP) {
3101 defining->def_depth ++;
3103 return NO_DIRECTIVE_FOUND;
3105 nolist = false;
3106 do {
3107 tline = tline->next;
3108 } while (tok_type_(tline, TOK_WHITESPACE));
3110 if (tok_type_(tline, TOK_ID) &&
3111 nasm_stricmp(tline->text, ".nolist") == 0) {
3112 nolist = true;
3113 do {
3114 tline = tline->next;
3115 } while (tok_type_(tline, TOK_WHITESPACE));
3118 if (tline) {
3119 t = expand_smacro(tline);
3120 tptr = &t;
3121 tokval.t_type = TOKEN_INVALID;
3122 evalresult =
3123 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3124 if (!evalresult) {
3125 free_tlist(origline);
3126 return DIRECTIVE_FOUND;
3128 if (tokval.t_type)
3129 error(ERR_WARNING|ERR_PASS1,
3130 "trailing garbage after expression ignored");
3131 if (!is_simple(evalresult)) {
3132 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
3133 return DIRECTIVE_FOUND;
3135 count = reloc_value(evalresult);
3136 if (count >= REP_LIMIT) {
3137 error(ERR_NONFATAL, "`%%rep' value exceeds limit");
3138 count = 0;
3139 } else
3140 count++;
3141 } else {
3142 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
3143 count = 0;
3145 free_tlist(origline);
3146 ed = new_ExpDef(EXP_REP);
3147 ed->nolist = nolist;
3148 ed->def_depth = 0;
3149 ed->cur_depth = 1;
3150 ed->max_depth = (count - 1);
3151 ed->ignoring = false;
3152 ed->prev = defining;
3153 defining = ed;
3154 return DIRECTIVE_FOUND;
3156 case PP_ENDREP:
3157 if (defining != NULL) {
3158 if (defining->type == EXP_REP) {
3159 if (defining->def_depth > 0) {
3160 defining->def_depth --;
3161 return NO_DIRECTIVE_FOUND;
3163 } else {
3164 return NO_DIRECTIVE_FOUND;
3167 if ((defining == NULL) || (defining->type != EXP_REP)) {
3168 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
3169 return DIRECTIVE_FOUND;
3173 * Now we have a "macro" defined - although it has no name
3174 * and we won't be entering it in the hash tables - we must
3175 * push a macro-end marker for it on to istk->expansion.
3176 * After that, it will take care of propagating itself (a
3177 * macro-end marker line for a macro which is really a %rep
3178 * block will cause the macro to be re-expanded, complete
3179 * with another macro-end marker to ensure the process
3180 * continues) until the whole expansion is forcibly removed
3181 * from istk->expansion by a %exitrep.
3183 ed = defining;
3184 defining = ed->prev;
3185 ed->prev = expansions;
3186 expansions = ed;
3187 ei = new_ExpInv(EXP_REP, ed);
3188 ei->current = ed->line;
3189 ei->emitting = ((ed->max_depth > 0) ? true : false);
3190 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
3191 ei->prev = istk->expansion;
3192 istk->expansion = ei;
3193 free_tlist(origline);
3194 return DIRECTIVE_FOUND;
3196 case PP_EXITREP:
3197 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3199 * We must search along istk->expansion until we hit a
3200 * rep invocation. Then we disable the emitting state(s)
3201 * between exitrep and endrep.
3203 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3204 if (ei->type == EXP_REP) {
3205 break;
3209 if (ei != NULL) {
3211 * Set all invocations leading back to the rep
3212 * invocation to a non-emitting state.
3214 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3215 eei->emitting = false;
3217 eei->emitting = false;
3218 eei->current = NULL;
3219 eei->def->cur_depth = eei->def->max_depth;
3220 } else {
3221 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
3223 free_tlist(origline);
3224 return DIRECTIVE_FOUND;
3226 case PP_XDEFINE:
3227 case PP_IXDEFINE:
3228 case PP_DEFINE:
3229 case PP_IDEFINE:
3230 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3231 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
3233 tline = tline->next;
3234 skip_white_(tline);
3235 tline = expand_id(tline);
3236 if (!tline || (tline->type != TOK_ID &&
3237 (tline->type != TOK_PREPROC_ID ||
3238 tline->text[1] != '$'))) {
3239 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3240 pp_directives[i]);
3241 free_tlist(origline);
3242 return DIRECTIVE_FOUND;
3245 ctx = get_ctx(tline->text, &mname, false);
3246 last = tline;
3247 param_start = tline = tline->next;
3248 nparam = 0;
3250 /* Expand the macro definition now for %xdefine and %ixdefine */
3251 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
3252 tline = expand_smacro(tline);
3254 if (tok_is_(tline, "(")) {
3256 * This macro has parameters.
3259 tline = tline->next;
3260 while (1) {
3261 skip_white_(tline);
3262 if (!tline) {
3263 error(ERR_NONFATAL, "parameter identifier expected");
3264 free_tlist(origline);
3265 return DIRECTIVE_FOUND;
3267 if (tline->type != TOK_ID) {
3268 error(ERR_NONFATAL,
3269 "`%s': parameter identifier expected",
3270 tline->text);
3271 free_tlist(origline);
3272 return DIRECTIVE_FOUND;
3274 tline->type = TOK_SMAC_PARAM + nparam++;
3275 tline = tline->next;
3276 skip_white_(tline);
3277 if (tok_is_(tline, ",")) {
3278 tline = tline->next;
3279 } else {
3280 if (!tok_is_(tline, ")")) {
3281 error(ERR_NONFATAL,
3282 "`)' expected to terminate macro template");
3283 free_tlist(origline);
3284 return DIRECTIVE_FOUND;
3286 break;
3289 last = tline;
3290 tline = tline->next;
3292 if (tok_type_(tline, TOK_WHITESPACE))
3293 last = tline, tline = tline->next;
3294 macro_start = NULL;
3295 last->next = NULL;
3296 t = tline;
3297 while (t) {
3298 if (t->type == TOK_ID) {
3299 list_for_each(tt, param_start)
3300 if (tt->type >= TOK_SMAC_PARAM &&
3301 !strcmp(tt->text, t->text))
3302 t->type = tt->type;
3304 tt = t->next;
3305 t->next = macro_start;
3306 macro_start = t;
3307 t = tt;
3310 * Good. We now have a macro name, a parameter count, and a
3311 * token list (in reverse order) for an expansion. We ought
3312 * to be OK just to create an SMacro, store it, and let
3313 * free_tlist have the rest of the line (which we have
3314 * carefully re-terminated after chopping off the expansion
3315 * from the end).
3317 define_smacro(ctx, mname, casesense, nparam, macro_start);
3318 free_tlist(origline);
3319 return DIRECTIVE_FOUND;
3321 case PP_UNDEF:
3322 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3323 tline = tline->next;
3324 skip_white_(tline);
3325 tline = expand_id(tline);
3326 if (!tline || (tline->type != TOK_ID &&
3327 (tline->type != TOK_PREPROC_ID ||
3328 tline->text[1] != '$'))) {
3329 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
3330 free_tlist(origline);
3331 return DIRECTIVE_FOUND;
3333 if (tline->next) {
3334 error(ERR_WARNING|ERR_PASS1,
3335 "trailing garbage after macro name ignored");
3338 /* Find the context that symbol belongs to */
3339 ctx = get_ctx(tline->text, &mname, false);
3340 undef_smacro(ctx, mname);
3341 free_tlist(origline);
3342 return DIRECTIVE_FOUND;
3344 case PP_DEFSTR:
3345 case PP_IDEFSTR:
3346 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3347 casesense = (i == PP_DEFSTR);
3349 tline = tline->next;
3350 skip_white_(tline);
3351 tline = expand_id(tline);
3352 if (!tline || (tline->type != TOK_ID &&
3353 (tline->type != TOK_PREPROC_ID ||
3354 tline->text[1] != '$'))) {
3355 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3356 pp_directives[i]);
3357 free_tlist(origline);
3358 return DIRECTIVE_FOUND;
3361 ctx = get_ctx(tline->text, &mname, false);
3362 last = tline;
3363 tline = expand_smacro(tline->next);
3364 last->next = NULL;
3366 while (tok_type_(tline, TOK_WHITESPACE))
3367 tline = delete_Token(tline);
3369 p = detoken(tline, false);
3370 macro_start = nasm_zalloc(sizeof(*macro_start));
3371 macro_start->text = nasm_quote(p, strlen(p));
3372 macro_start->type = TOK_STRING;
3373 nasm_free(p);
3376 * We now have a macro name, an implicit parameter count of
3377 * zero, and a string token to use as an expansion. Create
3378 * and store an SMacro.
3380 define_smacro(ctx, mname, casesense, 0, macro_start);
3381 free_tlist(origline);
3382 return DIRECTIVE_FOUND;
3384 case PP_DEFTOK:
3385 case PP_IDEFTOK:
3386 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3387 casesense = (i == PP_DEFTOK);
3389 tline = tline->next;
3390 skip_white_(tline);
3391 tline = expand_id(tline);
3392 if (!tline || (tline->type != TOK_ID &&
3393 (tline->type != TOK_PREPROC_ID ||
3394 tline->text[1] != '$'))) {
3395 error(ERR_NONFATAL,
3396 "`%s' expects a macro identifier as first parameter",
3397 pp_directives[i]);
3398 free_tlist(origline);
3399 return DIRECTIVE_FOUND;
3401 ctx = get_ctx(tline->text, &mname, false);
3402 last = tline;
3403 tline = expand_smacro(tline->next);
3404 last->next = NULL;
3406 t = tline;
3407 while (tok_type_(t, TOK_WHITESPACE))
3408 t = t->next;
3409 /* t should now point to the string */
3410 if (!tok_type_(t, TOK_STRING)) {
3411 error(ERR_NONFATAL,
3412 "`%s` requires string as second parameter",
3413 pp_directives[i]);
3414 free_tlist(tline);
3415 free_tlist(origline);
3416 return DIRECTIVE_FOUND;
3420 * Convert the string to a token stream. Note that smacros
3421 * are stored with the token stream reversed, so we have to
3422 * reverse the output of tokenize().
3424 nasm_unquote_cstr(t->text, i);
3425 macro_start = reverse_tokens(tokenize(t->text));
3428 * We now have a macro name, an implicit parameter count of
3429 * zero, and a numeric token to use as an expansion. Create
3430 * and store an SMacro.
3432 define_smacro(ctx, mname, casesense, 0, macro_start);
3433 free_tlist(tline);
3434 free_tlist(origline);
3435 return DIRECTIVE_FOUND;
3437 case PP_PATHSEARCH:
3438 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3440 FILE *fp;
3441 StrList *xsl = NULL;
3442 StrList **xst = &xsl;
3444 casesense = true;
3446 tline = tline->next;
3447 skip_white_(tline);
3448 tline = expand_id(tline);
3449 if (!tline || (tline->type != TOK_ID &&
3450 (tline->type != TOK_PREPROC_ID ||
3451 tline->text[1] != '$'))) {
3452 error(ERR_NONFATAL,
3453 "`%%pathsearch' expects a macro identifier as first parameter");
3454 free_tlist(origline);
3455 return DIRECTIVE_FOUND;
3457 ctx = get_ctx(tline->text, &mname, false);
3458 last = tline;
3459 tline = expand_smacro(tline->next);
3460 last->next = NULL;
3462 t = tline;
3463 while (tok_type_(t, TOK_WHITESPACE))
3464 t = t->next;
3466 if (!t || (t->type != TOK_STRING &&
3467 t->type != TOK_INTERNAL_STRING)) {
3468 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3469 free_tlist(tline);
3470 free_tlist(origline);
3471 return DIRECTIVE_FOUND; /* but we did _something_ */
3473 if (t->next)
3474 error(ERR_WARNING|ERR_PASS1,
3475 "trailing garbage after `%%pathsearch' ignored");
3476 p = t->text;
3477 if (t->type != TOK_INTERNAL_STRING)
3478 nasm_unquote(p, NULL);
3480 fp = inc_fopen(p, &xsl, &xst, true);
3481 if (fp) {
3482 p = xsl->str;
3483 fclose(fp); /* Don't actually care about the file */
3485 macro_start = nasm_zalloc(sizeof(*macro_start));
3486 macro_start->text = nasm_quote(p, strlen(p));
3487 macro_start->type = TOK_STRING;
3488 if (xsl)
3489 nasm_free(xsl);
3492 * We now have a macro name, an implicit parameter count of
3493 * zero, and a string token to use as an expansion. Create
3494 * and store an SMacro.
3496 define_smacro(ctx, mname, casesense, 0, macro_start);
3497 free_tlist(tline);
3498 free_tlist(origline);
3499 return DIRECTIVE_FOUND;
3502 case PP_STRLEN:
3503 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3504 casesense = true;
3506 tline = tline->next;
3507 skip_white_(tline);
3508 tline = expand_id(tline);
3509 if (!tline || (tline->type != TOK_ID &&
3510 (tline->type != TOK_PREPROC_ID ||
3511 tline->text[1] != '$'))) {
3512 error(ERR_NONFATAL,
3513 "`%%strlen' expects a macro identifier as first parameter");
3514 free_tlist(origline);
3515 return DIRECTIVE_FOUND;
3517 ctx = get_ctx(tline->text, &mname, false);
3518 last = tline;
3519 tline = expand_smacro(tline->next);
3520 last->next = NULL;
3522 t = tline;
3523 while (tok_type_(t, TOK_WHITESPACE))
3524 t = t->next;
3525 /* t should now point to the string */
3526 if (!tok_type_(t, TOK_STRING)) {
3527 error(ERR_NONFATAL,
3528 "`%%strlen` requires string as second parameter");
3529 free_tlist(tline);
3530 free_tlist(origline);
3531 return DIRECTIVE_FOUND;
3534 macro_start = nasm_zalloc(sizeof(*macro_start));
3535 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3538 * We now have a macro name, an implicit parameter count of
3539 * zero, and a numeric token to use as an expansion. Create
3540 * and store an SMacro.
3542 define_smacro(ctx, mname, casesense, 0, macro_start);
3543 free_tlist(tline);
3544 free_tlist(origline);
3545 return DIRECTIVE_FOUND;
3547 case PP_STRCAT:
3548 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3549 casesense = true;
3551 tline = tline->next;
3552 skip_white_(tline);
3553 tline = expand_id(tline);
3554 if (!tline || (tline->type != TOK_ID &&
3555 (tline->type != TOK_PREPROC_ID ||
3556 tline->text[1] != '$'))) {
3557 error(ERR_NONFATAL,
3558 "`%%strcat' expects a macro identifier as first parameter");
3559 free_tlist(origline);
3560 return DIRECTIVE_FOUND;
3562 ctx = get_ctx(tline->text, &mname, false);
3563 last = tline;
3564 tline = expand_smacro(tline->next);
3565 last->next = NULL;
3567 len = 0;
3568 list_for_each(t, tline) {
3569 switch (t->type) {
3570 case TOK_WHITESPACE:
3571 break;
3572 case TOK_STRING:
3573 len += t->a.len = nasm_unquote(t->text, NULL);
3574 break;
3575 case TOK_OTHER:
3576 if (!strcmp(t->text, ",")) /* permit comma separators */
3577 break;
3578 /* else fall through */
3579 default:
3580 error(ERR_NONFATAL,
3581 "non-string passed to `%%strcat' (%d)", t->type);
3582 free_tlist(tline);
3583 free_tlist(origline);
3584 return DIRECTIVE_FOUND;
3588 p = pp = nasm_malloc(len);
3589 list_for_each(t, tline) {
3590 if (t->type == TOK_STRING) {
3591 memcpy(p, t->text, t->a.len);
3592 p += t->a.len;
3597 * We now have a macro name, an implicit parameter count of
3598 * zero, and a numeric token to use as an expansion. Create
3599 * and store an SMacro.
3601 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3602 macro_start->text = nasm_quote(pp, len);
3603 nasm_free(pp);
3604 define_smacro(ctx, mname, casesense, 0, macro_start);
3605 free_tlist(tline);
3606 free_tlist(origline);
3607 return DIRECTIVE_FOUND;
3609 case PP_SUBSTR:
3610 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3612 int64_t start, count;
3613 size_t len;
3615 casesense = true;
3617 tline = tline->next;
3618 skip_white_(tline);
3619 tline = expand_id(tline);
3620 if (!tline || (tline->type != TOK_ID &&
3621 (tline->type != TOK_PREPROC_ID ||
3622 tline->text[1] != '$'))) {
3623 error(ERR_NONFATAL,
3624 "`%%substr' expects a macro identifier as first parameter");
3625 free_tlist(origline);
3626 return DIRECTIVE_FOUND;
3628 ctx = get_ctx(tline->text, &mname, false);
3629 last = tline;
3630 tline = expand_smacro(tline->next);
3631 last->next = NULL;
3633 if (tline) /* skip expanded id */
3634 t = tline->next;
3635 while (tok_type_(t, TOK_WHITESPACE))
3636 t = t->next;
3638 /* t should now point to the string */
3639 if (!tok_type_(t, TOK_STRING)) {
3640 error(ERR_NONFATAL,
3641 "`%%substr` requires string as second parameter");
3642 free_tlist(tline);
3643 free_tlist(origline);
3644 return DIRECTIVE_FOUND;
3647 tt = t->next;
3648 tptr = &tt;
3649 tokval.t_type = TOKEN_INVALID;
3650 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3651 pass, error, NULL);
3652 if (!evalresult) {
3653 free_tlist(tline);
3654 free_tlist(origline);
3655 return DIRECTIVE_FOUND;
3656 } else if (!is_simple(evalresult)) {
3657 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3658 free_tlist(tline);
3659 free_tlist(origline);
3660 return DIRECTIVE_FOUND;
3662 start = evalresult->value - 1;
3664 while (tok_type_(tt, TOK_WHITESPACE))
3665 tt = tt->next;
3666 if (!tt) {
3667 count = 1; /* Backwards compatibility: one character */
3668 } else {
3669 tokval.t_type = TOKEN_INVALID;
3670 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3671 pass, error, NULL);
3672 if (!evalresult) {
3673 free_tlist(tline);
3674 free_tlist(origline);
3675 return DIRECTIVE_FOUND;
3676 } else if (!is_simple(evalresult)) {
3677 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3678 free_tlist(tline);
3679 free_tlist(origline);
3680 return DIRECTIVE_FOUND;
3682 count = evalresult->value;
3685 len = nasm_unquote(t->text, NULL);
3686 /* make start and count being in range */
3687 if (start < 0)
3688 start = 0;
3689 if (count < 0)
3690 count = len + count + 1 - start;
3691 if (start + count > (int64_t)len)
3692 count = len - start;
3693 if (!len || count < 0 || start >=(int64_t)len)
3694 start = -1, count = 0; /* empty string */
3696 macro_start = nasm_zalloc(sizeof(*macro_start));
3697 macro_start->text = nasm_quote((start < 0) ? "" : t->text + start, count);
3698 macro_start->type = TOK_STRING;
3701 * We now have a macro name, an implicit parameter count of
3702 * zero, and a numeric token to use as an expansion. Create
3703 * and store an SMacro.
3705 define_smacro(ctx, mname, casesense, 0, macro_start);
3706 free_tlist(tline);
3707 free_tlist(origline);
3708 return DIRECTIVE_FOUND;
3711 case PP_ASSIGN:
3712 case PP_IASSIGN:
3713 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3714 casesense = (i == PP_ASSIGN);
3716 tline = tline->next;
3717 skip_white_(tline);
3718 tline = expand_id(tline);
3719 if (!tline || (tline->type != TOK_ID &&
3720 (tline->type != TOK_PREPROC_ID ||
3721 tline->text[1] != '$'))) {
3722 error(ERR_NONFATAL,
3723 "`%%%sassign' expects a macro identifier",
3724 (i == PP_IASSIGN ? "i" : ""));
3725 free_tlist(origline);
3726 return DIRECTIVE_FOUND;
3728 ctx = get_ctx(tline->text, &mname, false);
3729 last = tline;
3730 tline = expand_smacro(tline->next);
3731 last->next = NULL;
3733 t = tline;
3734 tptr = &t;
3735 tokval.t_type = TOKEN_INVALID;
3736 evalresult =
3737 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3738 free_tlist(tline);
3739 if (!evalresult) {
3740 free_tlist(origline);
3741 return DIRECTIVE_FOUND;
3744 if (tokval.t_type)
3745 error(ERR_WARNING|ERR_PASS1,
3746 "trailing garbage after expression ignored");
3748 if (!is_simple(evalresult)) {
3749 error(ERR_NONFATAL,
3750 "non-constant value given to `%%%sassign'",
3751 (i == PP_IASSIGN ? "i" : ""));
3752 free_tlist(origline);
3753 return DIRECTIVE_FOUND;
3756 macro_start = nasm_zalloc(sizeof(*macro_start));
3757 make_tok_num(macro_start, reloc_value(evalresult));
3760 * We now have a macro name, an implicit parameter count of
3761 * zero, and a numeric token to use as an expansion. Create
3762 * and store an SMacro.
3764 define_smacro(ctx, mname, casesense, 0, macro_start);
3765 free_tlist(origline);
3766 return DIRECTIVE_FOUND;
3768 case PP_LINE:
3769 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3771 * Syntax is `%line nnn[+mmm] [filename]'
3773 tline = tline->next;
3774 skip_white_(tline);
3775 if (!tok_type_(tline, TOK_NUMBER)) {
3776 error(ERR_NONFATAL, "`%%line' expects line number");
3777 free_tlist(origline);
3778 return DIRECTIVE_FOUND;
3780 k = readnum(tline->text, &err);
3781 m = 1;
3782 tline = tline->next;
3783 if (tok_is_(tline, "+")) {
3784 tline = tline->next;
3785 if (!tok_type_(tline, TOK_NUMBER)) {
3786 error(ERR_NONFATAL, "`%%line' expects line increment");
3787 free_tlist(origline);
3788 return DIRECTIVE_FOUND;
3790 m = readnum(tline->text, &err);
3791 tline = tline->next;
3793 skip_white_(tline);
3794 src_set_linnum(k);
3795 istk->lineinc = m;
3796 if (tline) {
3797 nasm_free(src_set_fname(detoken(tline, false)));
3799 free_tlist(origline);
3800 return DIRECTIVE_FOUND;
3802 case PP_WHILE:
3803 if (defining != NULL) {
3804 if (defining->type == EXP_WHILE) {
3805 defining->def_depth ++;
3807 return NO_DIRECTIVE_FOUND;
3809 l = NULL;
3810 if ((istk->expansion != NULL) &&
3811 (istk->expansion->emitting == false)) {
3812 j = COND_NEVER;
3813 } else {
3814 l = new_Line();
3815 l->first = copy_Token(tline->next);
3816 j = if_condition(tline->next, i);
3817 tline->next = NULL; /* it got freed */
3818 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
3820 ed = new_ExpDef(EXP_WHILE);
3821 ed->state = j;
3822 ed->cur_depth = 1;
3823 ed->max_depth = DEADMAN_LIMIT;
3824 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
3825 if (ed->ignoring == false) {
3826 ed->line = l;
3827 ed->last = l;
3828 } else if (l != NULL) {
3829 delete_Token(l->first);
3830 nasm_free(l);
3831 l = NULL;
3833 ed->prev = defining;
3834 defining = ed;
3835 free_tlist(origline);
3836 return DIRECTIVE_FOUND;
3838 case PP_ENDWHILE:
3839 if (defining != NULL) {
3840 if (defining->type == EXP_WHILE) {
3841 if (defining->def_depth > 0) {
3842 defining->def_depth --;
3843 return NO_DIRECTIVE_FOUND;
3845 } else {
3846 return NO_DIRECTIVE_FOUND;
3849 if (tline->next != NULL) {
3850 error_precond(ERR_WARNING|ERR_PASS1,
3851 "trailing garbage after `%%endwhile' ignored");
3853 if ((defining == NULL) || (defining->type != EXP_WHILE)) {
3854 error(ERR_NONFATAL, "`%%endwhile': no matching `%%while'");
3855 return DIRECTIVE_FOUND;
3857 ed = defining;
3858 defining = ed->prev;
3859 if (ed->ignoring == false) {
3860 ed->prev = expansions;
3861 expansions = ed;
3862 ei = new_ExpInv(EXP_WHILE, ed);
3863 ei->current = ed->line->next;
3864 ei->emitting = true;
3865 ei->prev = istk->expansion;
3866 istk->expansion = ei;
3867 } else {
3868 nasm_free(ed);
3870 free_tlist(origline);
3871 return DIRECTIVE_FOUND;
3873 case PP_EXITWHILE:
3874 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3876 * We must search along istk->expansion until we hit a
3877 * while invocation. Then we disable the emitting state(s)
3878 * between exitwhile and endwhile.
3880 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3881 if (ei->type == EXP_WHILE) {
3882 break;
3886 if (ei != NULL) {
3888 * Set all invocations leading back to the while
3889 * invocation to a non-emitting state.
3891 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3892 eei->emitting = false;
3894 eei->emitting = false;
3895 eei->current = NULL;
3896 eei->def->cur_depth = eei->def->max_depth;
3897 } else {
3898 error(ERR_NONFATAL, "`%%exitwhile' not within `%%while' block");
3900 free_tlist(origline);
3901 return DIRECTIVE_FOUND;
3903 case PP_COMMENT:
3904 if (defining != NULL) {
3905 if (defining->type == EXP_COMMENT) {
3906 defining->def_depth ++;
3908 return NO_DIRECTIVE_FOUND;
3910 ed = new_ExpDef(EXP_COMMENT);
3911 ed->ignoring = true;
3912 ed->prev = defining;
3913 defining = ed;
3914 free_tlist(origline);
3915 return DIRECTIVE_FOUND;
3917 case PP_ENDCOMMENT:
3918 if (defining != NULL) {
3919 if (defining->type == EXP_COMMENT) {
3920 if (defining->def_depth > 0) {
3921 defining->def_depth --;
3922 return NO_DIRECTIVE_FOUND;
3924 } else {
3925 return NO_DIRECTIVE_FOUND;
3928 if ((defining == NULL) || (defining->type != EXP_COMMENT)) {
3929 error(ERR_NONFATAL, "`%%endcomment': no matching `%%comment'");
3930 return DIRECTIVE_FOUND;
3932 ed = defining;
3933 defining = ed->prev;
3934 nasm_free(ed);
3935 free_tlist(origline);
3936 return DIRECTIVE_FOUND;
3938 case PP_FINAL:
3939 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3940 if (in_final != false) {
3941 error(ERR_FATAL, "`%%final' cannot be used recursively");
3943 tline = tline->next;
3944 skip_white_(tline);
3945 if (tline == NULL) {
3946 error(ERR_NONFATAL, "`%%final' expects at least one parameter");
3947 } else {
3948 l = new_Line();
3949 l->first = copy_Token(tline);
3950 l->next = finals;
3951 finals = l;
3953 free_tlist(origline);
3954 return DIRECTIVE_FOUND;
3956 default:
3957 error(ERR_FATAL,
3958 "preprocessor directive `%s' not yet implemented",
3959 pp_directives[i]);
3960 return DIRECTIVE_FOUND;
3965 * Ensure that a macro parameter contains a condition code and
3966 * nothing else. Return the condition code index if so, or -1
3967 * otherwise.
3969 static int find_cc(Token * t)
3971 Token *tt;
3972 int i, j, k, m;
3974 if (!t)
3975 return -1; /* Probably a %+ without a space */
3977 skip_white_(t);
3978 if (t->type != TOK_ID)
3979 return -1;
3980 tt = t->next;
3981 skip_white_(tt);
3982 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3983 return -1;
3985 i = -1;
3986 j = ARRAY_SIZE(conditions);
3987 while (j - i > 1) {
3988 k = (j + i) / 2;
3989 m = nasm_stricmp(t->text, conditions[k]);
3990 if (m == 0) {
3991 i = k;
3992 j = -2;
3993 break;
3994 } else if (m < 0) {
3995 j = k;
3996 } else
3997 i = k;
3999 if (j != -2)
4000 return -1;
4001 return i;
4004 static bool paste_tokens(Token **head, const struct tokseq_match *m,
4005 int mnum, bool handle_paste_tokens)
4007 Token **tail, *t, *tt;
4008 Token **paste_head;
4009 bool did_paste = false;
4010 char *tmp;
4011 int i;
4013 /* Now handle token pasting... */
4014 paste_head = NULL;
4015 tail = head;
4016 while ((t = *tail) && (tt = t->next)) {
4017 switch (t->type) {
4018 case TOK_WHITESPACE:
4019 if (tt->type == TOK_WHITESPACE) {
4020 /* Zap adjacent whitespace tokens */
4021 t->next = delete_Token(tt);
4022 } else {
4023 /* Do not advance paste_head here */
4024 tail = &t->next;
4026 break;
4027 case TOK_PASTE: /* %+ */
4028 if (handle_paste_tokens) {
4029 /* Zap %+ and whitespace tokens to the right */
4030 while (t && (t->type == TOK_WHITESPACE ||
4031 t->type == TOK_PASTE))
4032 t = *tail = delete_Token(t);
4033 if (!paste_head || !t)
4034 break; /* Nothing to paste with */
4035 tail = paste_head;
4036 t = *tail;
4037 tt = t->next;
4038 while (tok_type_(tt, TOK_WHITESPACE))
4039 tt = t->next = delete_Token(tt);
4040 if (tt) {
4041 tmp = nasm_strcat(t->text, tt->text);
4042 delete_Token(t);
4043 tt = delete_Token(tt);
4044 t = *tail = tokenize(tmp);
4045 nasm_free(tmp);
4046 while (t->next) {
4047 tail = &t->next;
4048 t = t->next;
4050 t->next = tt; /* Attach the remaining token chain */
4051 did_paste = true;
4053 paste_head = tail;
4054 tail = &t->next;
4055 break;
4057 /* else fall through */
4058 default:
4060 * Concatenation of tokens might look nontrivial
4061 * but in real it's pretty simple -- the caller
4062 * prepares the masks of token types to be concatenated
4063 * and we simply find matched sequences and slip
4064 * them together
4066 for (i = 0; i < mnum; i++) {
4067 if (PP_CONCAT_MASK(t->type) & m[i].mask_head) {
4068 size_t len = 0;
4069 char *tmp, *p;
4071 while (tt && (PP_CONCAT_MASK(tt->type) & m[i].mask_tail)) {
4072 len += strlen(tt->text);
4073 tt = tt->next;
4076 nasm_dump_token(tt);
4079 * Now tt points to the first token after
4080 * the potential paste area...
4082 if (tt != t->next) {
4083 /* We have at least two tokens... */
4084 len += strlen(t->text);
4085 p = tmp = nasm_malloc(len+1);
4086 while (t != tt) {
4087 strcpy(p, t->text);
4088 p = strchr(p, '\0');
4089 t = delete_Token(t);
4091 t = *tail = tokenize(tmp);
4092 nasm_free(tmp);
4093 while (t->next) {
4094 tail = &t->next;
4095 t = t->next;
4097 t->next = tt; /* Attach the remaining token chain */
4098 did_paste = true;
4100 paste_head = tail;
4101 tail = &t->next;
4102 break;
4105 if (i >= mnum) { /* no match */
4106 tail = &t->next;
4107 if (!tok_type_(t->next, TOK_WHITESPACE))
4108 paste_head = tail;
4110 break;
4113 return did_paste;
4117 * expands to a list of tokens from %{x:y}
4119 static Token *expand_mmac_params_range(ExpInv *ei, Token *tline, Token ***last)
4121 Token *t = tline, **tt, *tm, *head;
4122 char *pos;
4123 int fst, lst, j, i;
4125 pos = strchr(tline->text, ':');
4126 nasm_assert(pos);
4128 lst = atoi(pos + 1);
4129 fst = atoi(tline->text + 1);
4132 * only macros params are accounted so
4133 * if someone passes %0 -- we reject such
4134 * value(s)
4136 if (lst == 0 || fst == 0)
4137 goto err;
4139 /* the values should be sane */
4140 if ((fst > (int)ei->nparam || fst < (-(int)ei->nparam)) ||
4141 (lst > (int)ei->nparam || lst < (-(int)ei->nparam)))
4142 goto err;
4144 fst = fst < 0 ? fst + (int)ei->nparam + 1: fst;
4145 lst = lst < 0 ? lst + (int)ei->nparam + 1: lst;
4147 /* counted from zero */
4148 fst--, lst--;
4151 * it will be at least one token
4153 tm = ei->params[(fst + ei->rotate) % ei->nparam];
4154 t = new_Token(NULL, tm->type, tm->text, 0);
4155 head = t, tt = &t->next;
4156 if (fst < lst) {
4157 for (i = fst + 1; i <= lst; i++) {
4158 t = new_Token(NULL, TOK_OTHER, ",", 0);
4159 *tt = t, tt = &t->next;
4160 j = (i + ei->rotate) % ei->nparam;
4161 tm = ei->params[j];
4162 t = new_Token(NULL, tm->type, tm->text, 0);
4163 *tt = t, tt = &t->next;
4165 } else {
4166 for (i = fst - 1; i >= lst; i--) {
4167 t = new_Token(NULL, TOK_OTHER, ",", 0);
4168 *tt = t, tt = &t->next;
4169 j = (i + ei->rotate) % ei->nparam;
4170 tm = ei->params[j];
4171 t = new_Token(NULL, tm->type, tm->text, 0);
4172 *tt = t, tt = &t->next;
4176 *last = tt;
4177 return head;
4179 err:
4180 error(ERR_NONFATAL, "`%%{%s}': macro parameters out of range",
4181 &tline->text[1]);
4182 return tline;
4186 * Expand MMacro-local things: parameter references (%0, %n, %+n,
4187 * %-n) and MMacro-local identifiers (%%foo) as well as
4188 * macro indirection (%[...]) and range (%{..:..}).
4190 static Token *expand_mmac_params(Token * tline)
4192 Token *t, *tt, **tail, *thead;
4193 bool changed = false;
4194 char *pos;
4196 tail = &thead;
4197 thead = NULL;
4199 nasm_dump_stream(tline);
4201 while (tline) {
4202 if (tline->type == TOK_PREPROC_ID &&
4203 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text[2]) ||
4204 (tline->text[1] >= '0' && tline->text[1] <= '9') ||
4205 tline->text[1] == '%')) {
4206 char *text = NULL;
4207 int type = 0, cc; /* type = 0 to placate optimisers */
4208 char tmpbuf[30];
4209 unsigned int n;
4210 int i;
4211 ExpInv *ei;
4213 t = tline;
4214 tline = tline->next;
4216 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
4217 if (ei->type == EXP_MMACRO) {
4218 break;
4221 if (ei == NULL) {
4222 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
4223 } else {
4224 pos = strchr(t->text, ':');
4225 if (!pos) {
4226 switch (t->text[1]) {
4228 * We have to make a substitution of one of the
4229 * forms %1, %-1, %+1, %%foo, %0.
4231 case '0':
4232 if ((strlen(t->text) > 2) && (t->text[2] == '0')) {
4233 type = TOK_ID;
4234 text = nasm_strdup(ei->label_text);
4235 } else {
4236 type = TOK_NUMBER;
4237 snprintf(tmpbuf, sizeof(tmpbuf), "%d", ei->nparam);
4238 text = nasm_strdup(tmpbuf);
4240 break;
4241 case '%':
4242 type = TOK_ID;
4243 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
4244 ei->unique);
4245 text = nasm_strcat(tmpbuf, t->text + 2);
4246 break;
4247 case '-':
4248 n = atoi(t->text + 2) - 1;
4249 if (n >= ei->nparam)
4250 tt = NULL;
4251 else {
4252 if (ei->nparam > 1)
4253 n = (n + ei->rotate) % ei->nparam;
4254 tt = ei->params[n];
4256 cc = find_cc(tt);
4257 if (cc == -1) {
4258 error(ERR_NONFATAL,
4259 "macro parameter %d is not a condition code",
4260 n + 1);
4261 text = NULL;
4262 } else {
4263 type = TOK_ID;
4264 if (inverse_ccs[cc] == -1) {
4265 error(ERR_NONFATAL,
4266 "condition code `%s' is not invertible",
4267 conditions[cc]);
4268 text = NULL;
4269 } else
4270 text = nasm_strdup(conditions[inverse_ccs[cc]]);
4272 break;
4273 case '+':
4274 n = atoi(t->text + 2) - 1;
4275 if (n >= ei->nparam)
4276 tt = NULL;
4277 else {
4278 if (ei->nparam > 1)
4279 n = (n + ei->rotate) % ei->nparam;
4280 tt = ei->params[n];
4282 cc = find_cc(tt);
4283 if (cc == -1) {
4284 error(ERR_NONFATAL,
4285 "macro parameter %d is not a condition code",
4286 n + 1);
4287 text = NULL;
4288 } else {
4289 type = TOK_ID;
4290 text = nasm_strdup(conditions[cc]);
4292 break;
4293 default:
4294 n = atoi(t->text + 1) - 1;
4295 if (n >= ei->nparam)
4296 tt = NULL;
4297 else {
4298 if (ei->nparam > 1)
4299 n = (n + ei->rotate) % ei->nparam;
4300 tt = ei->params[n];
4302 if (tt) {
4303 for (i = 0; i < ei->paramlen[n]; i++) {
4304 *tail = new_Token(NULL, tt->type, tt->text, 0);
4305 tail = &(*tail)->next;
4306 tt = tt->next;
4309 text = NULL; /* we've done it here */
4310 break;
4312 } else {
4314 * seems we have a parameters range here
4316 Token *head, **last;
4317 head = expand_mmac_params_range(ei, t, &last);
4318 if (head != t) {
4319 *tail = head;
4320 *last = tline;
4321 tline = head;
4322 text = NULL;
4326 if (!text) {
4327 delete_Token(t);
4328 } else {
4329 *tail = t;
4330 tail = &t->next;
4331 t->type = type;
4332 nasm_free(t->text);
4333 t->text = text;
4334 t->a.mac = NULL;
4336 changed = true;
4337 continue;
4338 } else if (tline->type == TOK_INDIRECT) {
4339 t = tline;
4340 tline = tline->next;
4341 tt = tokenize(t->text);
4342 tt = expand_mmac_params(tt);
4343 tt = expand_smacro(tt);
4344 *tail = tt;
4345 while (tt) {
4346 tt->a.mac = NULL; /* Necessary? */
4347 tail = &tt->next;
4348 tt = tt->next;
4350 delete_Token(t);
4351 changed = true;
4352 } else {
4353 t = *tail = tline;
4354 tline = tline->next;
4355 t->a.mac = NULL;
4356 tail = &t->next;
4359 *tail = NULL;
4361 if (changed) {
4362 const struct tokseq_match t[] = {
4364 PP_CONCAT_MASK(TOK_ID) |
4365 PP_CONCAT_MASK(TOK_FLOAT), /* head */
4366 PP_CONCAT_MASK(TOK_ID) |
4367 PP_CONCAT_MASK(TOK_NUMBER) |
4368 PP_CONCAT_MASK(TOK_FLOAT) |
4369 PP_CONCAT_MASK(TOK_OTHER) /* tail */
4372 PP_CONCAT_MASK(TOK_NUMBER), /* head */
4373 PP_CONCAT_MASK(TOK_NUMBER) /* tail */
4376 paste_tokens(&thead, t, ARRAY_SIZE(t), false);
4379 nasm_dump_token(thead);
4381 return thead;
4385 * Expand all single-line macro calls made in the given line.
4386 * Return the expanded version of the line. The original is deemed
4387 * to be destroyed in the process. (In reality we'll just move
4388 * Tokens from input to output a lot of the time, rather than
4389 * actually bothering to destroy and replicate.)
4392 static Token *expand_smacro(Token * tline)
4394 Token *t, *tt, *mstart, **tail, *thead;
4395 SMacro *head = NULL, *m;
4396 Token **params;
4397 int *paramsize;
4398 unsigned int nparam, sparam;
4399 int brackets;
4400 Token *org_tline = tline;
4401 Context *ctx;
4402 const char *mname;
4403 int deadman = DEADMAN_LIMIT;
4404 bool expanded;
4407 * Trick: we should avoid changing the start token pointer since it can
4408 * be contained in "next" field of other token. Because of this
4409 * we allocate a copy of first token and work with it; at the end of
4410 * routine we copy it back
4412 if (org_tline) {
4413 tline = new_Token(org_tline->next, org_tline->type,
4414 org_tline->text, 0);
4415 tline->a.mac = org_tline->a.mac;
4416 nasm_free(org_tline->text);
4417 org_tline->text = NULL;
4420 expanded = true; /* Always expand %+ at least once */
4422 again:
4423 thead = NULL;
4424 tail = &thead;
4426 while (tline) { /* main token loop */
4427 if (!--deadman) {
4428 error(ERR_NONFATAL, "interminable macro recursion");
4429 goto err;
4432 if ((mname = tline->text)) {
4433 /* if this token is a local macro, look in local context */
4434 if (tline->type == TOK_ID) {
4435 head = (SMacro *)hash_findix(&smacros, mname);
4436 } else if (tline->type == TOK_PREPROC_ID) {
4437 ctx = get_ctx(mname, &mname, false);
4438 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
4439 } else
4440 head = NULL;
4443 * We've hit an identifier. As in is_mmacro below, we first
4444 * check whether the identifier is a single-line macro at
4445 * all, then think about checking for parameters if
4446 * necessary.
4448 list_for_each(m, head)
4449 if (!mstrcmp(m->name, mname, m->casesense))
4450 break;
4451 if (m) {
4452 mstart = tline;
4453 params = NULL;
4454 paramsize = NULL;
4455 if (m->nparam == 0) {
4457 * Simple case: the macro is parameterless. Discard the
4458 * one token that the macro call took, and push the
4459 * expansion back on the to-do stack.
4461 if (!m->expansion) {
4462 if (!strcmp("__FILE__", m->name)) {
4463 int32_t num = 0;
4464 char *file = NULL;
4465 src_get(&num, &file);
4466 tline->text = nasm_quote(file, strlen(file));
4467 tline->type = TOK_STRING;
4468 nasm_free(file);
4469 continue;
4471 if (!strcmp("__LINE__", m->name)) {
4472 nasm_free(tline->text);
4473 make_tok_num(tline, src_get_linnum());
4474 continue;
4476 if (!strcmp("__BITS__", m->name)) {
4477 nasm_free(tline->text);
4478 make_tok_num(tline, globalbits);
4479 continue;
4481 tline = delete_Token(tline);
4482 continue;
4484 } else {
4486 * Complicated case: at least one macro with this name
4487 * exists and takes parameters. We must find the
4488 * parameters in the call, count them, find the SMacro
4489 * that corresponds to that form of the macro call, and
4490 * substitute for the parameters when we expand. What a
4491 * pain.
4493 /*tline = tline->next;
4494 skip_white_(tline); */
4495 do {
4496 t = tline->next;
4497 while (tok_type_(t, TOK_SMAC_END)) {
4498 t->a.mac->in_progress = false;
4499 t->text = NULL;
4500 t = tline->next = delete_Token(t);
4502 tline = t;
4503 } while (tok_type_(tline, TOK_WHITESPACE));
4504 if (!tok_is_(tline, "(")) {
4506 * This macro wasn't called with parameters: ignore
4507 * the call. (Behaviour borrowed from gnu cpp.)
4509 tline = mstart;
4510 m = NULL;
4511 } else {
4512 int paren = 0;
4513 int white = 0;
4514 brackets = 0;
4515 nparam = 0;
4516 sparam = PARAM_DELTA;
4517 params = nasm_malloc(sparam * sizeof(Token *));
4518 params[0] = tline->next;
4519 paramsize = nasm_malloc(sparam * sizeof(int));
4520 paramsize[0] = 0;
4521 while (true) { /* parameter loop */
4523 * For some unusual expansions
4524 * which concatenates function call
4526 t = tline->next;
4527 while (tok_type_(t, TOK_SMAC_END)) {
4528 t->a.mac->in_progress = false;
4529 t->text = NULL;
4530 t = tline->next = delete_Token(t);
4532 tline = t;
4534 if (!tline) {
4535 error(ERR_NONFATAL,
4536 "macro call expects terminating `)'");
4537 break;
4539 if (tline->type == TOK_WHITESPACE
4540 && brackets <= 0) {
4541 if (paramsize[nparam])
4542 white++;
4543 else
4544 params[nparam] = tline->next;
4545 continue; /* parameter loop */
4547 if (tline->type == TOK_OTHER
4548 && tline->text[1] == 0) {
4549 char ch = tline->text[0];
4550 if (ch == ',' && !paren && brackets <= 0) {
4551 if (++nparam >= sparam) {
4552 sparam += PARAM_DELTA;
4553 params = nasm_realloc(params,
4554 sparam * sizeof(Token *));
4555 paramsize = nasm_realloc(paramsize,
4556 sparam * sizeof(int));
4558 params[nparam] = tline->next;
4559 paramsize[nparam] = 0;
4560 white = 0;
4561 continue; /* parameter loop */
4563 if (ch == '{' &&
4564 (brackets > 0 || (brackets == 0 &&
4565 !paramsize[nparam])))
4567 if (!(brackets++)) {
4568 params[nparam] = tline->next;
4569 continue; /* parameter loop */
4572 if (ch == '}' && brackets > 0)
4573 if (--brackets == 0) {
4574 brackets = -1;
4575 continue; /* parameter loop */
4577 if (ch == '(' && !brackets)
4578 paren++;
4579 if (ch == ')' && brackets <= 0)
4580 if (--paren < 0)
4581 break;
4583 if (brackets < 0) {
4584 brackets = 0;
4585 error(ERR_NONFATAL, "braces do not "
4586 "enclose all of macro parameter");
4588 paramsize[nparam] += white + 1;
4589 white = 0;
4590 } /* parameter loop */
4591 nparam++;
4592 while (m && (m->nparam != nparam ||
4593 mstrcmp(m->name, mname,
4594 m->casesense)))
4595 m = m->next;
4596 if (!m)
4597 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4598 "macro `%s' exists, "
4599 "but not taking %d parameters",
4600 mstart->text, nparam);
4603 if (m && m->in_progress)
4604 m = NULL;
4605 if (!m) { /* in progess or didn't find '(' or wrong nparam */
4607 * Design question: should we handle !tline, which
4608 * indicates missing ')' here, or expand those
4609 * macros anyway, which requires the (t) test a few
4610 * lines down?
4612 nasm_free(params);
4613 nasm_free(paramsize);
4614 tline = mstart;
4615 } else {
4617 * Expand the macro: we are placed on the last token of the
4618 * call, so that we can easily split the call from the
4619 * following tokens. We also start by pushing an SMAC_END
4620 * token for the cycle removal.
4622 t = tline;
4623 if (t) {
4624 tline = t->next;
4625 t->next = NULL;
4627 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4628 tt->a.mac = m;
4629 m->in_progress = true;
4630 tline = tt;
4631 list_for_each(t, m->expansion) {
4632 if (t->type >= TOK_SMAC_PARAM) {
4633 Token *pcopy = tline, **ptail = &pcopy;
4634 Token *ttt, *pt;
4635 int i;
4637 ttt = params[t->type - TOK_SMAC_PARAM];
4638 i = paramsize[t->type - TOK_SMAC_PARAM];
4639 while (--i >= 0) {
4640 pt = *ptail = new_Token(tline, ttt->type,
4641 ttt->text, 0);
4642 ptail = &pt->next;
4643 ttt = ttt->next;
4645 tline = pcopy;
4646 } else if (t->type == TOK_PREPROC_Q) {
4647 tt = new_Token(tline, TOK_ID, mname, 0);
4648 tline = tt;
4649 } else if (t->type == TOK_PREPROC_QQ) {
4650 tt = new_Token(tline, TOK_ID, m->name, 0);
4651 tline = tt;
4652 } else {
4653 tt = new_Token(tline, t->type, t->text, 0);
4654 tline = tt;
4659 * Having done that, get rid of the macro call, and clean
4660 * up the parameters.
4662 nasm_free(params);
4663 nasm_free(paramsize);
4664 free_tlist(mstart);
4665 expanded = true;
4666 continue; /* main token loop */
4671 if (tline->type == TOK_SMAC_END) {
4672 tline->a.mac->in_progress = false;
4673 tline = delete_Token(tline);
4674 } else {
4675 t = *tail = tline;
4676 tline = tline->next;
4677 t->a.mac = NULL;
4678 t->next = NULL;
4679 tail = &t->next;
4684 * Now scan the entire line and look for successive TOK_IDs that resulted
4685 * after expansion (they can't be produced by tokenize()). The successive
4686 * TOK_IDs should be concatenated.
4687 * Also we look for %+ tokens and concatenate the tokens before and after
4688 * them (without white spaces in between).
4690 if (expanded) {
4691 const struct tokseq_match t[] = {
4693 PP_CONCAT_MASK(TOK_ID) |
4694 PP_CONCAT_MASK(TOK_PREPROC_ID), /* head */
4695 PP_CONCAT_MASK(TOK_ID) |
4696 PP_CONCAT_MASK(TOK_PREPROC_ID) |
4697 PP_CONCAT_MASK(TOK_NUMBER) /* tail */
4700 if (paste_tokens(&thead, t, ARRAY_SIZE(t), true)) {
4702 * If we concatenated something, *and* we had previously expanded
4703 * an actual macro, scan the lines again for macros...
4705 tline = thead;
4706 expanded = false;
4707 goto again;
4711 err:
4712 if (org_tline) {
4713 if (thead) {
4714 *org_tline = *thead;
4715 /* since we just gave text to org_line, don't free it */
4716 thead->text = NULL;
4717 delete_Token(thead);
4718 } else {
4719 /* the expression expanded to empty line;
4720 we can't return NULL for some reasons
4721 we just set the line to a single WHITESPACE token. */
4722 memset(org_tline, 0, sizeof(*org_tline));
4723 org_tline->text = NULL;
4724 org_tline->type = TOK_WHITESPACE;
4726 thead = org_tline;
4729 return thead;
4733 * Similar to expand_smacro but used exclusively with macro identifiers
4734 * right before they are fetched in. The reason is that there can be
4735 * identifiers consisting of several subparts. We consider that if there
4736 * are more than one element forming the name, user wants a expansion,
4737 * otherwise it will be left as-is. Example:
4739 * %define %$abc cde
4741 * the identifier %$abc will be left as-is so that the handler for %define
4742 * will suck it and define the corresponding value. Other case:
4744 * %define _%$abc cde
4746 * In this case user wants name to be expanded *before* %define starts
4747 * working, so we'll expand %$abc into something (if it has a value;
4748 * otherwise it will be left as-is) then concatenate all successive
4749 * PP_IDs into one.
4751 static Token *expand_id(Token * tline)
4753 Token *cur, *oldnext = NULL;
4755 if (!tline || !tline->next)
4756 return tline;
4758 cur = tline;
4759 while (cur->next &&
4760 (cur->next->type == TOK_ID ||
4761 cur->next->type == TOK_PREPROC_ID
4762 || cur->next->type == TOK_NUMBER))
4763 cur = cur->next;
4765 /* If identifier consists of just one token, don't expand */
4766 if (cur == tline)
4767 return tline;
4769 if (cur) {
4770 oldnext = cur->next; /* Detach the tail past identifier */
4771 cur->next = NULL; /* so that expand_smacro stops here */
4774 tline = expand_smacro(tline);
4776 if (cur) {
4777 /* expand_smacro possibly changhed tline; re-scan for EOL */
4778 cur = tline;
4779 while (cur && cur->next)
4780 cur = cur->next;
4781 if (cur)
4782 cur->next = oldnext;
4785 return tline;
4789 * Determine whether the given line constitutes a multi-line macro
4790 * call, and return the ExpDef structure called if so. Doesn't have
4791 * to check for an initial label - that's taken care of in
4792 * expand_mmacro - but must check numbers of parameters. Guaranteed
4793 * to be called with tline->type == TOK_ID, so the putative macro
4794 * name is easy to find.
4796 static ExpDef *is_mmacro(Token * tline, Token *** params_array)
4798 ExpDef *head, *ed;
4799 Token **params;
4800 int nparam;
4802 head = (ExpDef *) hash_findix(&expdefs, tline->text);
4805 * Efficiency: first we see if any macro exists with the given
4806 * name. If not, we can return NULL immediately. _Then_ we
4807 * count the parameters, and then we look further along the
4808 * list if necessary to find the proper ExpDef.
4810 list_for_each(ed, head)
4811 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4812 break;
4813 if (!ed)
4814 return NULL;
4817 * OK, we have a potential macro. Count and demarcate the
4818 * parameters.
4820 count_mmac_params(tline->next, &nparam, &params);
4823 * So we know how many parameters we've got. Find the ExpDef
4824 * structure that handles this number.
4826 while (ed) {
4827 if (ed->nparam_min <= nparam
4828 && (ed->plus || nparam <= ed->nparam_max)) {
4830 * It's right, and we can use it. Add its default
4831 * parameters to the end of our list if necessary.
4833 if (ed->defaults && nparam < ed->nparam_min + ed->ndefs) {
4834 params =
4835 nasm_realloc(params,
4836 ((ed->nparam_min + ed->ndefs +
4837 1) * sizeof(*params)));
4838 while (nparam < ed->nparam_min + ed->ndefs) {
4839 params[nparam] = ed->defaults[nparam - ed->nparam_min];
4840 nparam++;
4844 * If we've gone over the maximum parameter count (and
4845 * we're in Plus mode), ignore parameters beyond
4846 * nparam_max.
4848 if (ed->plus && nparam > ed->nparam_max)
4849 nparam = ed->nparam_max;
4851 * Then terminate the parameter list, and leave.
4853 if (!params) { /* need this special case */
4854 params = nasm_malloc(sizeof(*params));
4855 nparam = 0;
4857 params[nparam] = NULL;
4858 *params_array = params;
4859 return ed;
4862 * This one wasn't right: look for the next one with the
4863 * same name.
4865 list_for_each(ed, ed->next)
4866 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4867 break;
4871 * After all that, we didn't find one with the right number of
4872 * parameters. Issue a warning, and fail to expand the macro.
4874 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4875 "macro `%s' exists, but not taking %d parameters",
4876 tline->text, nparam);
4877 nasm_free(params);
4878 return NULL;
4882 * Expand the multi-line macro call made by the given line, if
4883 * there is one to be expanded. If there is, push the expansion on
4884 * istk->expansion and return true. Otherwise return false.
4886 static bool expand_mmacro(Token * tline)
4888 Token *label = NULL;
4889 int dont_prepend = 0;
4890 Token **params, *t;
4891 Line *l = NULL;
4892 ExpDef *ed;
4893 ExpInv *ei;
4894 int i, nparam, *paramlen;
4895 const char *mname;
4897 t = tline;
4898 skip_white_(t);
4899 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4900 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4901 return false;
4902 ed = is_mmacro(t, &params);
4903 if (ed != NULL) {
4904 mname = t->text;
4905 } else {
4906 Token *last;
4908 * We have an id which isn't a macro call. We'll assume
4909 * it might be a label; we'll also check to see if a
4910 * colon follows it. Then, if there's another id after
4911 * that lot, we'll check it again for macro-hood.
4913 label = last = t;
4914 t = t->next;
4915 if (tok_type_(t, TOK_WHITESPACE))
4916 last = t, t = t->next;
4917 if (tok_is_(t, ":")) {
4918 dont_prepend = 1;
4919 last = t, t = t->next;
4920 if (tok_type_(t, TOK_WHITESPACE))
4921 last = t, t = t->next;
4923 if (!tok_type_(t, TOK_ID) || !(ed = is_mmacro(t, &params)))
4924 return false;
4925 last->next = NULL;
4926 mname = t->text;
4927 tline = t;
4931 * Fix up the parameters: this involves stripping leading and
4932 * trailing whitespace, then stripping braces if they are
4933 * present.
4935 for (nparam = 0; params[nparam]; nparam++) ;
4936 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4938 for (i = 0; params[i]; i++) {
4939 int brace = false;
4940 int comma = (!ed->plus || i < nparam - 1);
4942 t = params[i];
4943 skip_white_(t);
4944 if (tok_is_(t, "{"))
4945 t = t->next, brace = true, comma = false;
4946 params[i] = t;
4947 paramlen[i] = 0;
4948 while (t) {
4949 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4950 break; /* ... because we have hit a comma */
4951 if (comma && t->type == TOK_WHITESPACE
4952 && tok_is_(t->next, ","))
4953 break; /* ... or a space then a comma */
4954 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4955 break; /* ... or a brace */
4956 t = t->next;
4957 paramlen[i]++;
4961 if (ed->cur_depth >= ed->max_depth) {
4962 if (ed->max_depth > 1) {
4963 error(ERR_WARNING,
4964 "reached maximum macro recursion depth of %i for %s",
4965 ed->max_depth,ed->name);
4967 return false;
4968 } else {
4969 ed->cur_depth ++;
4973 * OK, we have found a ExpDef structure representing a
4974 * previously defined mmacro. Create an expansion invocation
4975 * and point it back to the expansion definition. Substitution of
4976 * parameter tokens and macro-local tokens doesn't get done
4977 * until the single-line macro substitution process; this is
4978 * because delaying them allows us to change the semantics
4979 * later through %rotate.
4981 ei = new_ExpInv(EXP_MMACRO, ed);
4982 ei->name = nasm_strdup(mname);
4983 //ei->label = label;
4984 //ei->label_text = detoken(label, false);
4985 ei->current = ed->line;
4986 ei->emitting = true;
4987 //ei->iline = tline;
4988 ei->params = params;
4989 ei->nparam = nparam;
4990 ei->rotate = 0;
4991 ei->paramlen = paramlen;
4992 ei->lineno = 0;
4994 ei->prev = istk->expansion;
4995 istk->expansion = ei;
4998 * Special case: detect %00 on first invocation; if found,
4999 * avoid emitting any labels that precede the mmacro call.
5000 * ed->prepend is set to -1 when %00 is detected, else 1.
5002 if (ed->prepend == 0) {
5003 for (l = ed->line; l != NULL; l = l->next) {
5004 for (t = l->first; t != NULL; t = t->next) {
5005 if ((t->type == TOK_PREPROC_ID) &&
5006 (strlen(t->text) == 3) &&
5007 (t->text[1] == '0') && (t->text[2] == '0')) {
5008 dont_prepend = -1;
5009 break;
5012 if (dont_prepend < 0) {
5013 break;
5016 ed->prepend = ((dont_prepend < 0) ? -1 : 1);
5020 * If we had a label, push it on as the first line of
5021 * the macro expansion.
5023 if (label != NULL) {
5024 if (ed->prepend < 0) {
5025 ei->label_text = detoken(label, false);
5026 } else {
5027 if (dont_prepend == 0) {
5028 t = label;
5029 while (t->next != NULL) {
5030 t = t->next;
5032 t->next = new_Token(NULL, TOK_OTHER, ":", 0);
5034 l = new_Line();
5035 l->first = copy_Token(label);
5036 l->next = ei->current;
5037 ei->current = l;
5041 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
5043 istk->mmac_depth++;
5044 return true;
5047 /* The function that actually does the error reporting */
5048 static void verror(int severity, const char *fmt, va_list arg)
5050 char buff[1024];
5052 vsnprintf(buff, sizeof(buff), fmt, arg);
5054 if (istk && istk->mmac_depth > 0) {
5055 ExpInv *ei = istk->expansion;
5056 int lineno = ei->lineno;
5057 while (ei) {
5058 if (ei->type == EXP_MMACRO)
5059 break;
5060 lineno += ei->relno;
5061 ei = ei->prev;
5063 nasm_error(severity, "(%s:%d) %s", ei->def->name,
5064 lineno, buff);
5065 } else
5066 nasm_error(severity, "%s", buff);
5070 * Since preprocessor always operate only on the line that didn't
5071 * arrived yet, we should always use ERR_OFFBY1.
5073 static void error(int severity, const char *fmt, ...)
5075 va_list arg;
5076 va_start(arg, fmt);
5077 verror(severity, fmt, arg);
5078 va_end(arg);
5082 * Because %else etc are evaluated in the state context
5083 * of the previous branch, errors might get lost with error():
5084 * %if 0 ... %else trailing garbage ... %endif
5085 * So %else etc should report errors with this function.
5087 static void error_precond(int severity, const char *fmt, ...)
5089 va_list arg;
5091 /* Only ignore the error if it's really in a dead branch */
5092 if ((istk != NULL) &&
5093 (istk->expansion != NULL) &&
5094 (istk->expansion->type == EXP_IF) &&
5095 (istk->expansion->def->state == COND_NEVER))
5096 return;
5098 va_start(arg, fmt);
5099 verror(severity, fmt, arg);
5100 va_end(arg);
5103 static void
5104 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
5106 Token *t;
5108 cstk = NULL;
5109 istk = nasm_zalloc(sizeof(Include));
5110 istk->fp = fopen(file, "r");
5111 src_set_fname(nasm_strdup(file));
5112 src_set_linnum(0);
5113 istk->lineinc = 1;
5114 if (!istk->fp)
5115 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
5116 file);
5117 defining = NULL;
5118 finals = NULL;
5119 in_final = false;
5120 nested_mac_count = 0;
5121 nested_rep_count = 0;
5122 init_macros();
5123 unique = 0;
5124 if (tasm_compatible_mode) {
5125 stdmacpos = nasm_stdmac;
5126 } else {
5127 stdmacpos = nasm_stdmac_after_tasm;
5129 any_extrastdmac = extrastdmac && *extrastdmac;
5130 do_predef = true;
5131 list = listgen;
5134 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
5135 * The caller, however, will also pass in 3 for preprocess-only so
5136 * we can set __PASS__ accordingly.
5138 pass = apass > 2 ? 2 : apass;
5140 dephead = deptail = deplist;
5141 if (deplist) {
5142 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
5143 sl->next = NULL;
5144 strcpy(sl->str, file);
5145 *deptail = sl;
5146 deptail = &sl->next;
5150 * Define the __PASS__ macro. This is defined here unlike
5151 * all the other builtins, because it is special -- it varies between
5152 * passes.
5154 t = nasm_zalloc(sizeof(*t));
5155 make_tok_num(t, apass);
5156 define_smacro(NULL, "__PASS__", true, 0, t);
5159 static char *pp_getline(void)
5161 char *line;
5162 Token *tline;
5163 ExpDef *ed;
5164 ExpInv *ei;
5165 Line *l;
5166 int j;
5168 while (1) {
5170 * Fetch a tokenized line, either from the expansion
5171 * buffer or from the input file.
5173 tline = NULL;
5175 while (1) { /* until we get a line we can use */
5177 * Fetch a tokenized line from the expansion buffer
5179 if (istk->expansion != NULL) {
5180 ei = istk->expansion;
5181 if (ei->current != NULL) {
5182 if (ei->emitting == false) {
5183 ei->current = NULL;
5184 continue;
5186 l = ei->current;
5187 ei->current = l->next;
5188 ei->lineno++;
5189 tline = copy_Token(l->first);
5190 if (((ei->type == EXP_REP) ||
5191 (ei->type == EXP_MMACRO) ||
5192 (ei->type == EXP_WHILE))
5193 && (ei->def->nolist == false)) {
5194 char *p = detoken(tline, false);
5195 list->line(LIST_MACRO, p);
5196 nasm_free(p);
5198 if (ei->linnum > -1) {
5199 src_set_linnum(src_get_linnum() + 1);
5201 break;
5202 } else if ((ei->type == EXP_REP) &&
5203 (ei->def->cur_depth < ei->def->max_depth)) {
5204 ei->def->cur_depth ++;
5205 ei->current = ei->def->line;
5206 ei->lineno = 0;
5207 continue;
5208 } else if ((ei->type == EXP_WHILE) &&
5209 (ei->def->cur_depth < ei->def->max_depth)) {
5210 ei->current = ei->def->line;
5211 ei->lineno = 0;
5212 tline = copy_Token(ei->current->first);
5213 j = if_condition(tline, PP_WHILE);
5214 tline = NULL;
5215 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
5216 if (j == COND_IF_TRUE) {
5217 ei->current = ei->current->next;
5218 ei->def->cur_depth ++;
5219 } else {
5220 ei->emitting = false;
5221 ei->current = NULL;
5222 ei->def->cur_depth = ei->def->max_depth;
5224 continue;
5225 } else {
5226 istk->expansion = ei->prev;
5227 ed = ei->def;
5228 if (ed != NULL) {
5229 if ((ei->emitting == true) &&
5230 (ed->max_depth == DEADMAN_LIMIT) &&
5231 (ed->cur_depth == DEADMAN_LIMIT)
5233 error(ERR_FATAL, "runaway expansion detected, aborting");
5235 if (ed->cur_depth > 0) {
5236 ed->cur_depth --;
5237 } else if (ed->type != EXP_MMACRO) {
5238 expansions = ed->prev;
5239 free_expdef(ed);
5241 if ((ei->type == EXP_REP) ||
5242 (ei->type == EXP_MMACRO) ||
5243 (ei->type == EXP_WHILE)) {
5244 list->downlevel(LIST_MACRO);
5245 if (ei->type == EXP_MMACRO) {
5246 istk->mmac_depth--;
5250 if (ei->linnum > -1) {
5251 src_set_linnum(ei->linnum);
5253 free_expinv(ei);
5254 continue;
5259 * Read in line from input and tokenize
5261 line = read_line();
5262 if (line) { /* from the current input file */
5263 line = prepreproc(line);
5264 tline = tokenize(line);
5265 nasm_free(line);
5266 break;
5270 * The current file has ended; work down the istk
5273 Include *i = istk;
5274 fclose(i->fp);
5275 if (i->expansion != NULL) {
5276 error(ERR_FATAL,
5277 "end of file while still in an expansion");
5279 /* only set line and file name if there's a next node */
5280 if (i->next) {
5281 src_set_linnum(i->lineno);
5282 nasm_free(src_set_fname(nasm_strdup(i->fname)));
5284 if ((i->next == NULL) && (finals != NULL)) {
5285 in_final = true;
5286 ei = new_ExpInv(EXP_FINAL, NULL);
5287 ei->emitting = true;
5288 ei->current = finals;
5289 istk->expansion = ei;
5290 finals = NULL;
5291 continue;
5293 istk = i->next;
5294 list->downlevel(LIST_INCLUDE);
5295 nasm_free(i);
5296 if (istk == NULL) {
5297 if (finals != NULL) {
5298 in_final = true;
5299 } else {
5300 return NULL;
5303 continue;
5307 if (defining == NULL) {
5308 tline = expand_mmac_params(tline);
5312 * Check the line to see if it's a preprocessor directive.
5314 if (do_directive(tline) == DIRECTIVE_FOUND) {
5315 continue;
5316 } else if (defining != NULL) {
5318 * We're defining an expansion. We emit nothing at all,
5319 * and just shove the tokenized line on to the definition.
5321 if (defining->ignoring == false) {
5322 Line *l = new_Line();
5323 l->first = tline;
5324 if (defining->line == NULL) {
5325 defining->line = l;
5326 defining->last = l;
5327 } else {
5328 defining->last->next = l;
5329 defining->last = l;
5331 } else {
5332 free_tlist(tline);
5334 defining->linecount++;
5335 continue;
5336 } else if ((istk->expansion != NULL) &&
5337 (istk->expansion->emitting != true)) {
5339 * We're in a non-emitting branch of an expansion.
5340 * Emit nothing at all, not even a blank line: when we
5341 * emerge from the expansion we'll give a line-number
5342 * directive so we keep our place correctly.
5344 free_tlist(tline);
5345 continue;
5346 } else {
5347 tline = expand_smacro(tline);
5348 if (expand_mmacro(tline) != true) {
5350 * De-tokenize the line again, and emit it.
5352 line = detoken(tline, true);
5353 free_tlist(tline);
5354 break;
5355 } else {
5356 continue;
5360 return line;
5363 static void pp_cleanup(int pass)
5365 if (defining != NULL) {
5366 error(ERR_NONFATAL, "end of file while still defining an expansion");
5367 while (defining != NULL) {
5368 ExpDef *ed = defining;
5369 defining = ed->prev;
5370 free_expdef(ed);
5372 defining = NULL;
5374 while (cstk != NULL)
5375 ctx_pop();
5376 free_macros();
5377 while (istk != NULL) {
5378 Include *i = istk;
5379 istk = istk->next;
5380 fclose(i->fp);
5381 nasm_free(i->fname);
5382 while (i->expansion != NULL) {
5383 ExpInv *ei = i->expansion;
5384 i->expansion = ei->prev;
5385 free_expinv(ei);
5387 nasm_free(i);
5389 while (cstk)
5390 ctx_pop();
5391 nasm_free(src_set_fname(NULL));
5392 if (pass == 0) {
5393 IncPath *i;
5394 free_llist(predef);
5395 delete_Blocks();
5396 while ((i = ipath)) {
5397 ipath = i->next;
5398 if (i->path)
5399 nasm_free(i->path);
5400 nasm_free(i);
5405 void pp_include_path(char *path)
5407 IncPath *i = nasm_zalloc(sizeof(IncPath));
5409 if (path)
5410 i->path = nasm_strdup(path);
5412 if (ipath) {
5413 IncPath *j = ipath;
5414 while (j->next)
5415 j = j->next;
5416 j->next = i;
5417 } else {
5418 ipath = i;
5422 void pp_pre_include(char *fname)
5424 Token *inc, *space, *name;
5425 Line *l;
5427 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
5428 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
5429 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
5431 l = new_Line();
5432 l->next = predef;
5433 l->first = inc;
5434 predef = l;
5437 void pp_pre_define(char *definition)
5439 Token *def, *space;
5440 Line *l;
5441 char *equals;
5443 equals = strchr(definition, '=');
5444 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5445 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
5446 if (equals)
5447 *equals = ' ';
5448 space->next = tokenize(definition);
5449 if (equals)
5450 *equals = '=';
5452 l = new_Line();
5453 l->next = predef;
5454 l->first = def;
5455 predef = l;
5458 void pp_pre_undefine(char *definition)
5460 Token *def, *space;
5461 Line *l;
5463 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5464 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
5465 space->next = tokenize(definition);
5467 l = new_Line();
5468 l->next = predef;
5469 l->first = def;
5470 predef = l;
5474 * This function is used to assist with "runtime" preprocessor
5475 * directives, e.g. pp_runtime("%define __BITS__ 64");
5477 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5478 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5481 void pp_runtime(char *definition)
5483 Token *def;
5485 def = tokenize(definition);
5486 if (do_directive(def) == NO_DIRECTIVE_FOUND)
5487 free_tlist(def);
5491 void pp_extra_stdmac(macros_t *macros)
5493 extrastdmac = macros;
5496 static void make_tok_num(Token * tok, int64_t val)
5498 char numbuf[20];
5499 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
5500 tok->text = nasm_strdup(numbuf);
5501 tok->type = TOK_NUMBER;
5504 Preproc nasmpp = {
5505 pp_reset,
5506 pp_getline,
5507 pp_cleanup