preproc: Add trace point into paste_tokens
[nasm-cyr.git] / preproc.c
blob3f4f900aa1a81d5628ea02d83fbfb713775dad60
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))
340 const struct tokseq_match pp_concat_match[] = {
342 PP_CONCAT_MASK(TOK_ID) |
343 PP_CONCAT_MASK(TOK_PREPROC_ID) |
344 PP_CONCAT_MASK(TOK_NUMBER) |
345 PP_CONCAT_MASK(TOK_FLOAT) |
346 PP_CONCAT_MASK(TOK_OTHER),
348 PP_CONCAT_MASK(TOK_ID) |
349 PP_CONCAT_MASK(TOK_PREPROC_ID) |
350 PP_CONCAT_MASK(TOK_NUMBER) |
351 PP_CONCAT_MASK(TOK_FLOAT) |
352 PP_CONCAT_MASK(TOK_OTHER)
357 * Condition codes. Note that we use c_ prefix not C_ because C_ is
358 * used in nasm.h for the "real" condition codes. At _this_ level,
359 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
360 * ones, so we need a different enum...
362 static const char * const conditions[] = {
363 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
364 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
365 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
367 enum pp_conds {
368 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
369 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
370 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
371 c_none = -1
373 static const enum pp_conds inverse_ccs[] = {
374 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
375 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,
376 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
379 /* For TASM compatibility we need to be able to recognise TASM compatible
380 * conditional compilation directives. Using the NASM pre-processor does
381 * not work, so we look for them specifically from the following list and
382 * then jam in the equivalent NASM directive into the input stream.
385 enum {
386 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
387 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
390 static const char * const tasm_directives[] = {
391 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
392 "ifndef", "include", "local"
395 static int StackSize = 4;
396 static char *StackPointer = "ebp";
397 static int ArgOffset = 8;
398 static int LocalOffset = 0;
400 static Context *cstk;
401 static Include *istk;
402 static IncPath *ipath = NULL;
404 static int pass; /* HACK: pass 0 = generate dependencies only */
405 static StrList **dephead, **deptail; /* Dependency list */
407 static uint64_t unique; /* unique identifier numbers */
409 static Line *predef = NULL;
410 static bool do_predef;
412 static ListGen *list;
415 * The current set of expansion definitions we have defined.
417 static struct hash_table expdefs;
420 * The current set of single-line macros we have defined.
422 static struct hash_table smacros;
425 * Linked List of all active expansion definitions
427 struct ExpDef *expansions = NULL;
430 * The expansion we are currently defining
432 static ExpDef *defining = NULL;
434 static uint64_t nested_mac_count;
435 static uint64_t nested_rep_count;
438 * Linked-list of lines to preprocess, prior to cleanup
440 static Line *finals = NULL;
441 static bool in_final = false;
444 * The number of macro parameters to allocate space for at a time.
446 #define PARAM_DELTA 16
449 * The standard macro set: defined in macros.c in the array nasm_stdmac.
450 * This gives our position in the macro set, when we're processing it.
452 static macros_t *stdmacpos;
455 * The extra standard macros that come from the object format, if
456 * any.
458 static macros_t *extrastdmac = NULL;
459 static bool any_extrastdmac;
462 * Tokens are allocated in blocks to improve speed
464 #define TOKEN_BLOCKSIZE 4096
465 static Token *freeTokens = NULL;
466 struct Blocks {
467 Blocks *next;
468 void *chunk;
471 static Blocks blocks = { NULL, NULL };
474 * Forward declarations.
476 static Token *expand_mmac_params(Token * tline);
477 static Token *expand_smacro(Token * tline);
478 static Token *expand_id(Token * tline);
479 static Context *get_ctx(const char *name, const char **namep,
480 bool all_contexts);
481 static void make_tok_num(Token * tok, int64_t val);
482 static void error(int severity, const char *fmt, ...);
483 static void error_precond(int severity, const char *fmt, ...);
484 static void *new_Block(size_t size);
485 static void delete_Blocks(void);
486 static Token *new_Token(Token * next, enum pp_token_type type,
487 const char *text, int txtlen);
488 static Token *copy_Token(Token * tline);
489 static Token *delete_Token(Token * t);
490 static Line *new_Line(void);
491 static ExpDef *new_ExpDef(int exp_type);
492 static ExpInv *new_ExpInv(int exp_type, ExpDef *ed);
495 * Macros for safe checking of token pointers, avoid *(NULL)
497 #define tok_type_(x,t) ((x) && (x)->type == (t))
498 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
499 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
500 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
502 #ifdef NASM_TRACE
504 #define stringify(x) #x
506 #define nasm_trace(msg, ...) printf("(%s:%d): " msg "\n", __func__, __LINE__, ##__VA_ARGS__)
507 #define nasm_dump_token(t) nasm_raw_dump_token(t, __FILE__, __LINE__, __func__);
508 #define nasm_dump_stream(t) nasm_raw_dump_stream(t, __FILE__, __LINE__, __func__);
510 /* FIXME: we really need some compound type here instead of inplace code */
511 static const char *nasm_get_tok_type_str(enum pp_token_type type)
513 #define SWITCH_TOK_NAME(type) \
514 case (type): \
515 return stringify(type)
517 switch (type) {
518 SWITCH_TOK_NAME(TOK_NONE);
519 SWITCH_TOK_NAME(TOK_WHITESPACE);
520 SWITCH_TOK_NAME(TOK_COMMENT);
521 SWITCH_TOK_NAME(TOK_ID);
522 SWITCH_TOK_NAME(TOK_PREPROC_ID);
523 SWITCH_TOK_NAME(TOK_STRING);
524 SWITCH_TOK_NAME(TOK_NUMBER);
525 SWITCH_TOK_NAME(TOK_FLOAT);
526 SWITCH_TOK_NAME(TOK_SMAC_END);
527 SWITCH_TOK_NAME(TOK_OTHER);
528 SWITCH_TOK_NAME(TOK_INTERNAL_STRING);
529 SWITCH_TOK_NAME(TOK_PREPROC_Q);
530 SWITCH_TOK_NAME(TOK_PREPROC_QQ);
531 SWITCH_TOK_NAME(TOK_PASTE);
532 SWITCH_TOK_NAME(TOK_INDIRECT);
533 SWITCH_TOK_NAME(TOK_SMAC_PARAM);
534 SWITCH_TOK_NAME(TOK_MAX);
537 return NULL;
540 static void nasm_raw_dump_token(Token *token, const char *file, int line, const char *func)
542 printf("---[%s (%s:%d): %p]---\n", func, file, line, (void *)token);
543 if (token) {
544 Token *t;
545 list_for_each(t, token) {
546 if (t->text)
547 printf("'%s'(%s) ", t->text,
548 nasm_get_tok_type_str(t->type));
550 printf("\n\n");
554 static void nasm_raw_dump_stream(Token *token, const char *file, int line, const char *func)
556 printf("---[%s (%s:%d): %p]---\n", func, file, line, (void *)token);
557 if (token) {
558 Token *t;
559 list_for_each(t, token)
560 printf("%s", t->text ? t->text : " ");
561 printf("\n\n");
565 #else
566 #define nasm_trace(msg, ...)
567 #define nasm_dump_token(t)
568 #define nasm_dump_stream(t)
569 #endif
572 * nasm_unquote with error if the string contains NUL characters.
573 * If the string contains NUL characters, issue an error and return
574 * the C len, i.e. truncate at the NUL.
576 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
578 size_t len = nasm_unquote(qstr, NULL);
579 size_t clen = strlen(qstr);
581 if (len != clen)
582 error(ERR_NONFATAL, "NUL character in `%s' directive",
583 pp_directives[directive]);
585 return clen;
589 * In-place reverse a list of tokens.
591 static Token *reverse_tokens(Token *t)
593 Token *prev, *next;
595 list_reverse(t, prev, next);
597 return t;
601 * Handle TASM specific directives, which do not contain a % in
602 * front of them. We do it here because I could not find any other
603 * place to do it for the moment, and it is a hack (ideally it would
604 * be nice to be able to use the NASM pre-processor to do it).
606 static char *check_tasm_directive(char *line)
608 int32_t i, j, k, m, len;
609 char *p, *q, *oldline, oldchar;
611 p = nasm_skip_spaces(line);
613 /* Binary search for the directive name */
614 i = -1;
615 j = ARRAY_SIZE(tasm_directives);
616 q = nasm_skip_word(p);
617 len = q - p;
618 if (len) {
619 oldchar = p[len];
620 p[len] = 0;
621 while (j - i > 1) {
622 k = (j + i) / 2;
623 m = nasm_stricmp(p, tasm_directives[k]);
624 if (m == 0) {
625 /* We have found a directive, so jam a % in front of it
626 * so that NASM will then recognise it as one if it's own.
628 p[len] = oldchar;
629 len = strlen(p);
630 oldline = line;
631 line = nasm_malloc(len + 2);
632 line[0] = '%';
633 if (k == TM_IFDIFI) {
635 * NASM does not recognise IFDIFI, so we convert
636 * it to %if 0. This is not used in NASM
637 * compatible code, but does need to parse for the
638 * TASM macro package.
640 strcpy(line + 1, "if 0");
641 } else {
642 memcpy(line + 1, p, len + 1);
644 nasm_free(oldline);
645 return line;
646 } else if (m < 0) {
647 j = k;
648 } else
649 i = k;
651 p[len] = oldchar;
653 return line;
657 * The pre-preprocessing stage... This function translates line
658 * number indications as they emerge from GNU cpp (`# lineno "file"
659 * flags') into NASM preprocessor line number indications (`%line
660 * lineno file').
662 static char *prepreproc(char *line)
664 int lineno, fnlen;
665 char *fname, *oldline;
667 if (line[0] == '#' && line[1] == ' ') {
668 oldline = line;
669 fname = oldline + 2;
670 lineno = atoi(fname);
671 fname += strspn(fname, "0123456789 ");
672 if (*fname == '"')
673 fname++;
674 fnlen = strcspn(fname, "\"");
675 line = nasm_malloc(20 + fnlen);
676 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
677 nasm_free(oldline);
679 if (tasm_compatible_mode)
680 return check_tasm_directive(line);
681 return line;
685 * Free a linked list of tokens.
687 static void free_tlist(Token * list)
689 while (list)
690 list = delete_Token(list);
694 * Free a linked list of lines.
696 static void free_llist(Line * list)
698 Line *l, *tmp;
699 list_for_each_safe(l, tmp, list) {
700 free_tlist(l->first);
701 nasm_free(l);
706 * Free an ExpDef
708 static void free_expdef(ExpDef * ed)
710 nasm_free(ed->name);
711 free_tlist(ed->dlist);
712 nasm_free(ed->defaults);
713 free_llist(ed->line);
714 nasm_free(ed);
718 * Free an ExpInv
720 static void free_expinv(ExpInv * ei)
722 if (ei->name != NULL)
723 nasm_free(ei->name);
724 if (ei->label_text != NULL)
725 nasm_free(ei->label_text);
726 nasm_free(ei);
730 * Free all currently defined macros, and free the hash tables
732 static void free_smacro_table(struct hash_table *smt)
734 SMacro *s, *tmp;
735 const char *key;
736 struct hash_tbl_node *it = NULL;
738 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
739 nasm_free((void *)key);
740 list_for_each_safe(s, tmp, s) {
741 nasm_free(s->name);
742 free_tlist(s->expansion);
743 nasm_free(s);
746 hash_free(smt);
749 static void free_expdef_table(struct hash_table *edt)
751 ExpDef *ed, *tmp;
752 const char *key;
753 struct hash_tbl_node *it = NULL;
755 it = NULL;
756 while ((ed = hash_iterate(edt, &it, &key)) != NULL) {
757 nasm_free((void *)key);
758 list_for_each_safe(ed ,tmp, ed)
759 free_expdef(ed);
761 hash_free(edt);
764 static void free_macros(void)
766 free_smacro_table(&smacros);
767 free_expdef_table(&expdefs);
771 * Initialize the hash tables
773 static void init_macros(void)
775 hash_init(&smacros, HASH_LARGE);
776 hash_init(&expdefs, HASH_LARGE);
780 * Pop the context stack.
782 static void ctx_pop(void)
784 Context *c = cstk;
786 cstk = cstk->next;
787 free_smacro_table(&c->localmac);
788 nasm_free(c->name);
789 nasm_free(c);
793 * Search for a key in the hash index; adding it if necessary
794 * (in which case we initialize the data pointer to NULL.)
796 static void **
797 hash_findi_add(struct hash_table *hash, const char *str)
799 struct hash_insert hi;
800 void **r;
801 char *strx;
803 r = hash_findi(hash, str, &hi);
804 if (r)
805 return r;
807 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
808 return hash_add(&hi, strx, NULL);
812 * Like hash_findi, but returns the data element rather than a pointer
813 * to it. Used only when not adding a new element, hence no third
814 * argument.
816 static void *
817 hash_findix(struct hash_table *hash, const char *str)
819 void **p;
821 p = hash_findi(hash, str, NULL);
822 return p ? *p : NULL;
826 * read line from standard macros set,
827 * if there no more left -- return NULL
829 static char *line_from_stdmac(void)
831 unsigned char c;
832 const unsigned char *p = stdmacpos;
833 char *line, *q;
834 size_t len = 0;
836 if (!stdmacpos)
837 return NULL;
839 while ((c = *p++)) {
840 if (c >= 0x80)
841 len += pp_directives_len[c - 0x80] + 1;
842 else
843 len++;
846 line = nasm_malloc(len + 1);
847 q = line;
848 while ((c = *stdmacpos++)) {
849 if (c >= 0x80) {
850 memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
851 q += pp_directives_len[c - 0x80];
852 *q++ = ' ';
853 } else {
854 *q++ = c;
857 stdmacpos = p;
858 *q = '\0';
860 if (!*stdmacpos) {
861 /* This was the last of the standard macro chain... */
862 stdmacpos = NULL;
863 if (any_extrastdmac) {
864 stdmacpos = extrastdmac;
865 any_extrastdmac = false;
866 } else if (do_predef) {
867 ExpInv *ei;
868 Line *pd, *l;
869 Token *head, **tail, *t;
872 * Nasty hack: here we push the contents of
873 * `predef' on to the top-level expansion stack,
874 * since this is the most convenient way to
875 * implement the pre-include and pre-define
876 * features.
878 list_for_each(pd, predef) {
879 head = NULL;
880 tail = &head;
881 list_for_each(t, pd->first) {
882 *tail = new_Token(NULL, t->type, t->text, 0);
883 tail = &(*tail)->next;
886 l = new_Line();
887 l->first = head;
888 ei = new_ExpInv(EXP_PREDEF, NULL);
889 ei->current = l;
890 ei->emitting = true;
891 ei->prev = istk->expansion;
892 istk->expansion = ei;
894 do_predef = false;
898 return line;
901 #define BUF_DELTA 512
903 * Read a line from the top file in istk, handling multiple CR/LFs
904 * at the end of the line read, and handling spurious ^Zs. Will
905 * return lines from the standard macro set if this has not already
906 * been done.
908 static char *read_line(void)
910 char *buffer, *p, *q;
911 int bufsize, continued_count;
914 * standart macros set (predefined) goes first
916 p = line_from_stdmac();
917 if (p)
918 return p;
921 * regular read from a file
923 bufsize = BUF_DELTA;
924 buffer = nasm_malloc(BUF_DELTA);
925 p = buffer;
926 continued_count = 0;
927 while (1) {
928 q = fgets(p, bufsize - (p - buffer), istk->fp);
929 if (!q)
930 break;
931 p += strlen(p);
932 if (p > buffer && p[-1] == '\n') {
934 * Convert backslash-CRLF line continuation sequences into
935 * nothing at all (for DOS and Windows)
937 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
938 p -= 3;
939 *p = 0;
940 continued_count++;
943 * Also convert backslash-LF line continuation sequences into
944 * nothing at all (for Unix)
946 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
947 p -= 2;
948 *p = 0;
949 continued_count++;
950 } else {
951 break;
954 if (p - buffer > bufsize - 10) {
955 int32_t offset = p - buffer;
956 bufsize += BUF_DELTA;
957 buffer = nasm_realloc(buffer, bufsize);
958 p = buffer + offset; /* prevent stale-pointer problems */
962 if (!q && p == buffer) {
963 nasm_free(buffer);
964 return NULL;
967 src_set_linnum(src_get_linnum() + istk->lineinc +
968 (continued_count * istk->lineinc));
971 * Play safe: remove CRs as well as LFs, if any of either are
972 * present at the end of the line.
974 while (--p >= buffer && (*p == '\n' || *p == '\r'))
975 *p = '\0';
978 * Handle spurious ^Z, which may be inserted into source files
979 * by some file transfer utilities.
981 buffer[strcspn(buffer, "\032")] = '\0';
983 list->line(LIST_READ, buffer);
985 return buffer;
989 * Tokenize a line of text. This is a very simple process since we
990 * don't need to parse the value out of e.g. numeric tokens: we
991 * simply split one string into many.
993 static Token *tokenize(char *line)
995 char c, *p = line;
996 enum pp_token_type type;
997 Token *list = NULL;
998 Token *t, **tail = &list;
999 bool verbose = true;
1001 nasm_trace("Tokenize for '%s'", line);
1003 if ((defining != NULL) && (defining->ignoring == true)) {
1004 verbose = false;
1007 while (*line) {
1008 p = line;
1009 if (*p == '%') {
1010 p++;
1011 if (*p == '+' && !nasm_isdigit(p[1])) {
1012 p++;
1013 type = TOK_PASTE;
1014 } else if (nasm_isdigit(*p) ||
1015 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
1016 do {
1017 p++;
1019 while (nasm_isdigit(*p));
1020 type = TOK_PREPROC_ID;
1021 } else if (*p == '{') {
1022 p++;
1023 while (*p && *p != '}') {
1024 p[-1] = *p;
1025 p++;
1027 p[-1] = '\0';
1028 if (*p)
1029 p++;
1030 type = TOK_PREPROC_ID;
1031 } else if (*p == '[') {
1032 int lvl = 1;
1033 line += 2; /* Skip the leading %[ */
1034 p++;
1035 while (lvl && (c = *p++)) {
1036 switch (c) {
1037 case ']':
1038 lvl--;
1039 break;
1040 case '%':
1041 if (*p == '[')
1042 lvl++;
1043 break;
1044 case '\'':
1045 case '\"':
1046 case '`':
1047 p = nasm_skip_string(p - 1) + 1;
1048 break;
1049 default:
1050 break;
1053 p--;
1054 if (*p)
1055 *p++ = '\0';
1056 if (lvl && verbose)
1057 error(ERR_NONFATAL, "unterminated %[ construct");
1058 type = TOK_INDIRECT;
1059 } else if (*p == '?') {
1060 type = TOK_PREPROC_Q; /* %? */
1061 p++;
1062 if (*p == '?') {
1063 type = TOK_PREPROC_QQ; /* %?? */
1064 p++;
1066 } else if (*p == '!') {
1067 type = TOK_PREPROC_ID;
1068 p++;
1069 if (isidchar(*p)) {
1070 do {
1071 p++;
1072 } while (isidchar(*p));
1073 } else if (*p == '\'' || *p == '\"' || *p == '`') {
1074 p = nasm_skip_string(p);
1075 if (*p)
1076 p++;
1077 else if(verbose)
1078 error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
1079 } else {
1080 /* %! without string or identifier */
1081 type = TOK_OTHER; /* Legacy behavior... */
1083 } else if (isidchar(*p) ||
1084 ((*p == '!' || *p == '%' || *p == '$') &&
1085 isidchar(p[1]))) {
1086 do {
1087 p++;
1089 while (isidchar(*p));
1090 type = TOK_PREPROC_ID;
1091 } else {
1092 type = TOK_OTHER;
1093 if (*p == '%')
1094 p++;
1096 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
1097 type = TOK_ID;
1098 p++;
1099 while (*p && isidchar(*p))
1100 p++;
1101 } else if (*p == '\'' || *p == '"' || *p == '`') {
1103 * A string token.
1105 type = TOK_STRING;
1106 p = nasm_skip_string(p);
1108 if (*p) {
1109 p++;
1110 } else if(verbose) {
1111 error(ERR_WARNING|ERR_PASS1, "unterminated string");
1112 /* Handling unterminated strings by UNV */
1113 /* type = -1; */
1115 } else if (p[0] == '$' && p[1] == '$') {
1116 type = TOK_OTHER; /* TOKEN_BASE */
1117 p += 2;
1118 } else if (isnumstart(*p)) {
1119 bool is_hex = false;
1120 bool is_float = false;
1121 bool has_e = false;
1122 char c, *r;
1125 * A numeric token.
1128 if (*p == '$') {
1129 p++;
1130 is_hex = true;
1133 for (;;) {
1134 c = *p++;
1136 if (!is_hex && (c == 'e' || c == 'E')) {
1137 has_e = true;
1138 if (*p == '+' || *p == '-') {
1140 * e can only be followed by +/- if it is either a
1141 * prefixed hex number or a floating-point number
1143 p++;
1144 is_float = true;
1146 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
1147 is_hex = true;
1148 } else if (c == 'P' || c == 'p') {
1149 is_float = true;
1150 if (*p == '+' || *p == '-')
1151 p++;
1152 } else if (isnumchar(c) || c == '_')
1153 ; /* just advance */
1154 else if (c == '.') {
1156 * we need to deal with consequences of the legacy
1157 * parser, like "1.nolist" being two tokens
1158 * (TOK_NUMBER, TOK_ID) here; at least give it
1159 * a shot for now. In the future, we probably need
1160 * a flex-based scanner with proper pattern matching
1161 * to do it as well as it can be done. Nothing in
1162 * the world is going to help the person who wants
1163 * 0x123.p16 interpreted as two tokens, though.
1165 r = p;
1166 while (*r == '_')
1167 r++;
1169 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
1170 (!is_hex && (*r == 'e' || *r == 'E')) ||
1171 (*r == 'p' || *r == 'P')) {
1172 p = r;
1173 is_float = true;
1174 } else
1175 break; /* Terminate the token */
1176 } else
1177 break;
1179 p--; /* Point to first character beyond number */
1181 if (p == line+1 && *line == '$') {
1182 type = TOK_OTHER; /* TOKEN_HERE */
1183 } else {
1184 if (has_e && !is_hex) {
1185 /* 1e13 is floating-point, but 1e13h is not */
1186 is_float = true;
1189 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1191 } else if (nasm_isspace(*p)) {
1192 type = TOK_WHITESPACE;
1193 p = nasm_skip_spaces(p);
1195 * Whitespace just before end-of-line is discarded by
1196 * pretending it's a comment; whitespace just before a
1197 * comment gets lumped into the comment.
1199 if (!*p || *p == ';') {
1200 type = TOK_COMMENT;
1201 while (*p)
1202 p++;
1204 } else if (*p == ';') {
1205 type = TOK_COMMENT;
1206 while (*p)
1207 p++;
1208 } else {
1210 * Anything else is an operator of some kind. We check
1211 * for all the double-character operators (>>, <<, //,
1212 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1213 * else is a single-character operator.
1215 type = TOK_OTHER;
1216 if ((p[0] == '>' && p[1] == '>') ||
1217 (p[0] == '<' && p[1] == '<') ||
1218 (p[0] == '/' && p[1] == '/') ||
1219 (p[0] == '<' && p[1] == '=') ||
1220 (p[0] == '>' && p[1] == '=') ||
1221 (p[0] == '=' && p[1] == '=') ||
1222 (p[0] == '!' && p[1] == '=') ||
1223 (p[0] == '<' && p[1] == '>') ||
1224 (p[0] == '&' && p[1] == '&') ||
1225 (p[0] == '|' && p[1] == '|') ||
1226 (p[0] == '^' && p[1] == '^')) {
1227 p++;
1229 p++;
1232 /* Handling unterminated string by UNV */
1233 /*if (type == -1)
1235 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1236 t->text[p-line] = *line;
1237 tail = &t->next;
1239 else */
1240 if (type != TOK_COMMENT) {
1241 *tail = t = new_Token(NULL, type, line, p - line);
1242 tail = &t->next;
1244 line = p;
1247 nasm_dump_token(list);
1249 return list;
1253 * this function allocates a new managed block of memory and
1254 * returns a pointer to the block. The managed blocks are
1255 * deleted only all at once by the delete_Blocks function.
1257 static void *new_Block(size_t size)
1259 Blocks *b = &blocks;
1261 /* first, get to the end of the linked list */
1262 while (b->next)
1263 b = b->next;
1265 /* now allocate the requested chunk */
1266 b->chunk = nasm_malloc(size);
1268 /* now allocate a new block for the next request */
1269 b->next = nasm_zalloc(sizeof(Blocks));
1271 return b->chunk;
1275 * this function deletes all managed blocks of memory
1277 static void delete_Blocks(void)
1279 Blocks *a, *b = &blocks;
1282 * keep in mind that the first block, pointed to by blocks
1283 * is a static and not dynamically allocated, so we don't
1284 * free it.
1286 while (b) {
1287 if (b->chunk)
1288 nasm_free(b->chunk);
1289 a = b;
1290 b = b->next;
1291 if (a != &blocks)
1292 nasm_free(a);
1297 * this function creates a new Token and passes a pointer to it
1298 * back to the caller. It sets the type and text elements, and
1299 * also the a.mac and next elements to NULL.
1301 static Token *new_Token(Token * next, enum pp_token_type type,
1302 const char *text, int txtlen)
1304 Token *t;
1305 int i;
1307 if (!freeTokens) {
1308 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1309 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1310 freeTokens[i].next = &freeTokens[i + 1];
1311 freeTokens[i].next = NULL;
1313 t = freeTokens;
1314 freeTokens = t->next;
1315 t->next = next;
1316 t->a.mac = NULL;
1317 t->type = type;
1318 if (type == TOK_WHITESPACE || !text) {
1319 t->text = NULL;
1320 } else {
1321 if (txtlen == 0)
1322 txtlen = strlen(text);
1323 t->text = nasm_malloc(txtlen+1);
1324 memcpy(t->text, text, txtlen);
1325 t->text[txtlen] = '\0';
1327 return t;
1330 static Token *copy_Token(Token * tline)
1332 Token *t, *tt, *first = NULL, *prev = NULL;
1333 int i;
1334 for (tt = tline; tt != NULL; tt = tt->next) {
1335 if (!freeTokens) {
1336 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1337 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1338 freeTokens[i].next = &freeTokens[i + 1];
1339 freeTokens[i].next = NULL;
1341 t = freeTokens;
1342 freeTokens = t->next;
1343 t->next = NULL;
1344 t->text = tt->text ? nasm_strdup(tt->text) : NULL;
1345 t->a.mac = tt->a.mac;
1346 t->a.len = tt->a.len;
1347 t->type = tt->type;
1348 if (prev != NULL) {
1349 prev->next = t;
1350 } else {
1351 first = t;
1353 prev = t;
1355 return first;
1358 static Token *delete_Token(Token * t)
1360 Token *next = t->next;
1361 nasm_free(t->text);
1362 t->next = freeTokens;
1363 freeTokens = t;
1364 return next;
1368 * Convert a line of tokens back into text.
1369 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1370 * will be transformed into ..@ctxnum.xxx
1372 static char *detoken(Token * tlist, bool expand_locals)
1374 Token *t;
1375 char *line, *p;
1376 const char *q;
1377 int len = 0;
1379 list_for_each(t, tlist) {
1380 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1381 char *v;
1382 char *q = t->text;
1384 v = t->text + 2;
1385 if (*v == '\'' || *v == '\"' || *v == '`') {
1386 size_t len = nasm_unquote(v, NULL);
1387 size_t clen = strlen(v);
1389 if (len != clen) {
1390 error(ERR_NONFATAL | ERR_PASS1,
1391 "NUL character in %! string");
1392 v = NULL;
1396 if (v) {
1397 char *p = getenv(v);
1398 if (!p) {
1399 error(ERR_NONFATAL | ERR_PASS1,
1400 "nonexistent environment variable `%s'", v);
1401 p = "";
1403 t->text = nasm_strdup(p);
1405 nasm_free(q);
1408 /* Expand local macros here and not during preprocessing */
1409 if (expand_locals &&
1410 t->type == TOK_PREPROC_ID && t->text &&
1411 t->text[0] == '%' && t->text[1] == '$') {
1412 const char *q;
1413 char *p;
1414 Context *ctx = get_ctx(t->text, &q, false);
1415 if (ctx) {
1416 char buffer[40];
1417 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1418 p = nasm_strcat(buffer, q);
1419 nasm_free(t->text);
1420 t->text = p;
1424 /* Expand %? and %?? directives */
1425 if ((istk->expansion != NULL) &&
1426 ((t->type == TOK_PREPROC_Q) ||
1427 (t->type == TOK_PREPROC_QQ))) {
1428 ExpInv *ei;
1429 for (ei = istk->expansion; ei != NULL; ei = ei->prev){
1430 if (ei->type == EXP_MMACRO) {
1431 nasm_free(t->text);
1432 if (t->type == TOK_PREPROC_Q) {
1433 t->text = nasm_strdup(ei->name);
1434 } else {
1435 t->text = nasm_strdup(ei->def->name);
1437 break;
1442 if (t->type == TOK_WHITESPACE)
1443 len++;
1444 else if (t->text)
1445 len += strlen(t->text);
1448 p = line = nasm_malloc(len + 1);
1450 list_for_each(t, tlist) {
1451 if (t->type == TOK_WHITESPACE) {
1452 *p++ = ' ';
1453 } else if (t->text) {
1454 q = t->text;
1455 while (*q)
1456 *p++ = *q++;
1459 *p = '\0';
1461 return line;
1465 * Initialize a new Line
1467 static inline Line *new_Line(void)
1469 return (Line *)nasm_zalloc(sizeof(Line));
1474 * Initialize a new Expansion Definition
1476 static ExpDef *new_ExpDef(int exp_type)
1478 ExpDef *ed = (ExpDef*)nasm_zalloc(sizeof(ExpDef));
1479 ed->type = exp_type;
1480 ed->casesense = true;
1481 ed->state = COND_NEVER;
1483 return ed;
1488 * Initialize a new Expansion Instance
1490 static ExpInv *new_ExpInv(int exp_type, ExpDef *ed)
1492 ExpInv *ei = (ExpInv*)nasm_zalloc(sizeof(ExpInv));
1493 ei->type = exp_type;
1494 ei->def = ed;
1495 ei->unique = ++unique;
1497 if ((istk->mmac_depth < 1) &&
1498 (istk->expansion == NULL) &&
1499 (ed != NULL) &&
1500 (ed->type != EXP_MMACRO) &&
1501 (ed->type != EXP_REP) &&
1502 (ed->type != EXP_WHILE)) {
1503 ei->linnum = src_get_linnum();
1504 src_set_linnum(ei->linnum - ed->linecount - 1);
1505 } else {
1506 ei->linnum = -1;
1508 if ((istk->expansion == NULL) ||
1509 (ei->type == EXP_MMACRO)) {
1510 ei->relno = 0;
1511 } else {
1512 ei->relno = istk->expansion->lineno;
1513 if (ed != NULL) {
1514 ei->relno -= (ed->linecount + 1);
1517 return ei;
1521 * A scanner, suitable for use by the expression evaluator, which
1522 * operates on a line of Tokens. Expects a pointer to a pointer to
1523 * the first token in the line to be passed in as its private_data
1524 * field.
1526 * FIX: This really needs to be unified with stdscan.
1528 static int ppscan(void *private_data, struct tokenval *tokval)
1530 Token **tlineptr = private_data;
1531 Token *tline;
1532 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1534 do {
1535 tline = *tlineptr;
1536 *tlineptr = tline ? tline->next : NULL;
1537 } while (tline && (tline->type == TOK_WHITESPACE ||
1538 tline->type == TOK_COMMENT));
1540 if (!tline)
1541 return tokval->t_type = TOKEN_EOS;
1543 tokval->t_charptr = tline->text;
1545 if (tline->text[0] == '$' && !tline->text[1])
1546 return tokval->t_type = TOKEN_HERE;
1547 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1548 return tokval->t_type = TOKEN_BASE;
1550 if (tline->type == TOK_ID) {
1551 p = tokval->t_charptr = tline->text;
1552 if (p[0] == '$') {
1553 tokval->t_charptr++;
1554 return tokval->t_type = TOKEN_ID;
1557 for (r = p, s = ourcopy; *r; r++) {
1558 if (r >= p+MAX_KEYWORD)
1559 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1560 *s++ = nasm_tolower(*r);
1562 *s = '\0';
1563 /* right, so we have an identifier sitting in temp storage. now,
1564 * is it actually a register or instruction name, or what? */
1565 return nasm_token_hash(ourcopy, tokval);
1568 if (tline->type == TOK_NUMBER) {
1569 bool rn_error;
1570 tokval->t_integer = readnum(tline->text, &rn_error);
1571 tokval->t_charptr = tline->text;
1572 if (rn_error)
1573 return tokval->t_type = TOKEN_ERRNUM;
1574 else
1575 return tokval->t_type = TOKEN_NUM;
1578 if (tline->type == TOK_FLOAT) {
1579 return tokval->t_type = TOKEN_FLOAT;
1582 if (tline->type == TOK_STRING) {
1583 char bq, *ep;
1585 bq = tline->text[0];
1586 tokval->t_charptr = tline->text;
1587 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1589 if (ep[0] != bq || ep[1] != '\0')
1590 return tokval->t_type = TOKEN_ERRSTR;
1591 else
1592 return tokval->t_type = TOKEN_STR;
1595 if (tline->type == TOK_OTHER) {
1596 if (!strcmp(tline->text, "<<"))
1597 return tokval->t_type = TOKEN_SHL;
1598 if (!strcmp(tline->text, ">>"))
1599 return tokval->t_type = TOKEN_SHR;
1600 if (!strcmp(tline->text, "//"))
1601 return tokval->t_type = TOKEN_SDIV;
1602 if (!strcmp(tline->text, "%%"))
1603 return tokval->t_type = TOKEN_SMOD;
1604 if (!strcmp(tline->text, "=="))
1605 return tokval->t_type = TOKEN_EQ;
1606 if (!strcmp(tline->text, "<>"))
1607 return tokval->t_type = TOKEN_NE;
1608 if (!strcmp(tline->text, "!="))
1609 return tokval->t_type = TOKEN_NE;
1610 if (!strcmp(tline->text, "<="))
1611 return tokval->t_type = TOKEN_LE;
1612 if (!strcmp(tline->text, ">="))
1613 return tokval->t_type = TOKEN_GE;
1614 if (!strcmp(tline->text, "&&"))
1615 return tokval->t_type = TOKEN_DBL_AND;
1616 if (!strcmp(tline->text, "^^"))
1617 return tokval->t_type = TOKEN_DBL_XOR;
1618 if (!strcmp(tline->text, "||"))
1619 return tokval->t_type = TOKEN_DBL_OR;
1623 * We have no other options: just return the first character of
1624 * the token text.
1626 return tokval->t_type = tline->text[0];
1630 * Compare a string to the name of an existing macro; this is a
1631 * simple wrapper which calls either strcmp or nasm_stricmp
1632 * depending on the value of the `casesense' parameter.
1634 static int mstrcmp(const char *p, const char *q, bool casesense)
1636 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1640 * Compare a string to the name of an existing macro; this is a
1641 * simple wrapper which calls either strcmp or nasm_stricmp
1642 * depending on the value of the `casesense' parameter.
1644 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1646 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1650 * Return the Context structure associated with a %$ token. Return
1651 * NULL, having _already_ reported an error condition, if the
1652 * context stack isn't deep enough for the supplied number of $
1653 * signs.
1654 * If all_contexts == true, contexts that enclose current are
1655 * also scanned for such smacro, until it is found; if not -
1656 * only the context that directly results from the number of $'s
1657 * in variable's name.
1659 * If "namep" is non-NULL, set it to the pointer to the macro name
1660 * tail, i.e. the part beyond %$...
1662 static Context *get_ctx(const char *name, const char **namep,
1663 bool all_contexts)
1665 Context *ctx;
1666 SMacro *m;
1667 int i;
1669 if (namep)
1670 *namep = name;
1672 if (!name || name[0] != '%' || name[1] != '$')
1673 return NULL;
1675 if (!cstk) {
1676 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1677 return NULL;
1680 name += 2;
1681 ctx = cstk;
1682 i = 0;
1683 while (ctx && *name == '$') {
1684 name++;
1685 i++;
1686 ctx = ctx->next;
1688 if (!ctx) {
1689 error(ERR_NONFATAL, "`%s': context stack is only"
1690 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1691 return NULL;
1694 if (namep)
1695 *namep = name;
1697 if (!all_contexts)
1698 return ctx;
1700 do {
1701 /* Search for this smacro in found context */
1702 m = hash_findix(&ctx->localmac, name);
1703 while (m) {
1704 if (!mstrcmp(m->name, name, m->casesense))
1705 return ctx;
1706 m = m->next;
1708 ctx = ctx->next;
1710 while (ctx);
1711 return NULL;
1715 * Check to see if a file is already in a string list
1717 static bool in_list(const StrList *list, const char *str)
1719 while (list) {
1720 if (!strcmp(list->str, str))
1721 return true;
1722 list = list->next;
1724 return false;
1728 * Open an include file. This routine must always return a valid
1729 * file pointer if it returns - it's responsible for throwing an
1730 * ERR_FATAL and bombing out completely if not. It should also try
1731 * the include path one by one until it finds the file or reaches
1732 * the end of the path.
1734 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1735 bool missing_ok)
1737 FILE *fp;
1738 char *prefix = "";
1739 IncPath *ip = ipath;
1740 int len = strlen(file);
1741 size_t prefix_len = 0;
1742 StrList *sl;
1744 while (1) {
1745 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1746 sl->next = NULL;
1747 memcpy(sl->str, prefix, prefix_len);
1748 memcpy(sl->str+prefix_len, file, len+1);
1749 fp = fopen(sl->str, "r");
1750 if (fp && dhead && !in_list(*dhead, sl->str)) {
1751 **dtail = sl;
1752 *dtail = &sl->next;
1753 } else {
1754 nasm_free(sl);
1756 if (fp)
1757 return fp;
1758 if (!ip) {
1759 if (!missing_ok)
1760 break;
1761 prefix = NULL;
1762 } else {
1763 prefix = ip->path;
1764 ip = ip->next;
1766 if (prefix) {
1767 prefix_len = strlen(prefix);
1768 } else {
1769 /* -MG given and file not found */
1770 if (dhead && !in_list(*dhead, file)) {
1771 sl = nasm_malloc(len+1+sizeof sl->next);
1772 sl->next = NULL;
1773 strcpy(sl->str, file);
1774 **dtail = sl;
1775 *dtail = &sl->next;
1777 return NULL;
1781 error(ERR_FATAL, "unable to open include file `%s'", file);
1782 return NULL;
1786 * Determine if we should warn on defining a single-line macro of
1787 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1788 * return true if _any_ single-line macro of that name is defined.
1789 * Otherwise, will return true if a single-line macro with either
1790 * `nparam' or no parameters is defined.
1792 * If a macro with precisely the right number of parameters is
1793 * defined, or nparam is -1, the address of the definition structure
1794 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1795 * is NULL, no action will be taken regarding its contents, and no
1796 * error will occur.
1798 * Note that this is also called with nparam zero to resolve
1799 * `ifdef'.
1801 * If you already know which context macro belongs to, you can pass
1802 * the context pointer as first parameter; if you won't but name begins
1803 * with %$ the context will be automatically computed. If all_contexts
1804 * is true, macro will be searched in outer contexts as well.
1806 static bool
1807 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1808 bool nocase)
1810 struct hash_table *smtbl;
1811 SMacro *m;
1813 if (ctx) {
1814 smtbl = &ctx->localmac;
1815 } else if (name[0] == '%' && name[1] == '$') {
1816 if (cstk)
1817 ctx = get_ctx(name, &name, false);
1818 if (!ctx)
1819 return false; /* got to return _something_ */
1820 smtbl = &ctx->localmac;
1821 } else {
1822 smtbl = &smacros;
1824 m = (SMacro *) hash_findix(smtbl, name);
1826 while (m) {
1827 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1828 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1829 if (defn) {
1830 if (nparam == (int) m->nparam || nparam == -1)
1831 *defn = m;
1832 else
1833 *defn = NULL;
1835 return true;
1837 m = m->next;
1840 return false;
1844 * Count and mark off the parameters in a multi-line macro call.
1845 * This is called both from within the multi-line macro expansion
1846 * code, and also to mark off the default parameters when provided
1847 * in a %macro definition line.
1849 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1851 int paramsize, brace;
1853 *nparam = paramsize = 0;
1854 *params = NULL;
1855 while (t) {
1856 /* +1: we need space for the final NULL */
1857 if (*nparam+1 >= paramsize) {
1858 paramsize += PARAM_DELTA;
1859 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1861 skip_white_(t);
1862 brace = false;
1863 if (tok_is_(t, "{"))
1864 brace = true;
1865 (*params)[(*nparam)++] = t;
1866 while (tok_isnt_(t, brace ? "}" : ","))
1867 t = t->next;
1868 if (t) { /* got a comma/brace */
1869 t = t->next;
1870 if (brace) {
1872 * Now we've found the closing brace, look further
1873 * for the comma.
1875 skip_white_(t);
1876 if (tok_isnt_(t, ",")) {
1877 error(ERR_NONFATAL,
1878 "braces do not enclose all of macro parameter");
1879 while (tok_isnt_(t, ","))
1880 t = t->next;
1882 if (t)
1883 t = t->next; /* eat the comma */
1890 * Determine whether one of the various `if' conditions is true or
1891 * not.
1893 * We must free the tline we get passed.
1895 static bool if_condition(Token * tline, enum preproc_token ct)
1897 enum pp_conditional i = PP_COND(ct);
1898 bool j;
1899 Token *t, *tt, **tptr, *origline;
1900 struct tokenval tokval;
1901 expr *evalresult;
1902 enum pp_token_type needtype;
1903 char *p;
1905 origline = tline;
1907 switch (i) {
1908 case PPC_IFCTX:
1909 j = false; /* have we matched yet? */
1910 while (true) {
1911 skip_white_(tline);
1912 if (!tline)
1913 break;
1914 if (tline->type != TOK_ID) {
1915 error(ERR_NONFATAL,
1916 "`%s' expects context identifiers", pp_directives[ct]);
1917 free_tlist(origline);
1918 return -1;
1920 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1921 j = true;
1922 tline = tline->next;
1924 break;
1926 case PPC_IFDEF:
1927 j = false; /* have we matched yet? */
1928 while (tline) {
1929 skip_white_(tline);
1930 if (!tline || (tline->type != TOK_ID &&
1931 (tline->type != TOK_PREPROC_ID ||
1932 tline->text[1] != '$'))) {
1933 error(ERR_NONFATAL,
1934 "`%s' expects macro identifiers", pp_directives[ct]);
1935 goto fail;
1937 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1938 j = true;
1939 tline = tline->next;
1941 break;
1943 case PPC_IFENV:
1944 tline = expand_smacro(tline);
1945 j = false; /* have we matched yet? */
1946 while (tline) {
1947 skip_white_(tline);
1948 if (!tline || (tline->type != TOK_ID &&
1949 tline->type != TOK_STRING &&
1950 (tline->type != TOK_PREPROC_ID ||
1951 tline->text[1] != '!'))) {
1952 error(ERR_NONFATAL,
1953 "`%s' expects environment variable names",
1954 pp_directives[ct]);
1955 goto fail;
1957 p = tline->text;
1958 if (tline->type == TOK_PREPROC_ID)
1959 p += 2; /* Skip leading %! */
1960 if (*p == '\'' || *p == '\"' || *p == '`')
1961 nasm_unquote_cstr(p, ct);
1962 if (getenv(p))
1963 j = true;
1964 tline = tline->next;
1966 break;
1968 case PPC_IFIDN:
1969 case PPC_IFIDNI:
1970 tline = expand_smacro(tline);
1971 t = tt = tline;
1972 while (tok_isnt_(tt, ","))
1973 tt = tt->next;
1974 if (!tt) {
1975 error(ERR_NONFATAL,
1976 "`%s' expects two comma-separated arguments",
1977 pp_directives[ct]);
1978 goto fail;
1980 tt = tt->next;
1981 j = true; /* assume equality unless proved not */
1982 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1983 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1984 error(ERR_NONFATAL, "`%s': more than one comma on line",
1985 pp_directives[ct]);
1986 goto fail;
1988 if (t->type == TOK_WHITESPACE) {
1989 t = t->next;
1990 continue;
1992 if (tt->type == TOK_WHITESPACE) {
1993 tt = tt->next;
1994 continue;
1996 if (tt->type != t->type) {
1997 j = false; /* found mismatching tokens */
1998 break;
2000 /* When comparing strings, need to unquote them first */
2001 if (t->type == TOK_STRING) {
2002 size_t l1 = nasm_unquote(t->text, NULL);
2003 size_t l2 = nasm_unquote(tt->text, NULL);
2005 if (l1 != l2) {
2006 j = false;
2007 break;
2009 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
2010 j = false;
2011 break;
2013 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
2014 j = false; /* found mismatching tokens */
2015 break;
2018 t = t->next;
2019 tt = tt->next;
2021 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
2022 j = false; /* trailing gunk on one end or other */
2023 break;
2025 case PPC_IFMACRO:
2027 bool found = false;
2028 ExpDef searching, *ed;
2030 skip_white_(tline);
2031 tline = expand_id(tline);
2032 if (!tok_type_(tline, TOK_ID)) {
2033 error(ERR_NONFATAL,
2034 "`%s' expects a macro name", pp_directives[ct]);
2035 goto fail;
2037 memset(&searching, 0, sizeof(searching));
2038 searching.name = nasm_strdup(tline->text);
2039 searching.casesense = true;
2040 searching.nparam_max = INT_MAX;
2041 tline = expand_smacro(tline->next);
2042 skip_white_(tline);
2043 if (!tline) {
2044 } else if (!tok_type_(tline, TOK_NUMBER)) {
2045 error(ERR_NONFATAL,
2046 "`%s' expects a parameter count or nothing",
2047 pp_directives[ct]);
2048 } else {
2049 searching.nparam_min = searching.nparam_max =
2050 readnum(tline->text, &j);
2051 if (j)
2052 error(ERR_NONFATAL,
2053 "unable to parse parameter count `%s'",
2054 tline->text);
2056 if (tline && tok_is_(tline->next, "-")) {
2057 tline = tline->next->next;
2058 if (tok_is_(tline, "*"))
2059 searching.nparam_max = INT_MAX;
2060 else if (!tok_type_(tline, TOK_NUMBER))
2061 error(ERR_NONFATAL,
2062 "`%s' expects a parameter count after `-'",
2063 pp_directives[ct]);
2064 else {
2065 searching.nparam_max = readnum(tline->text, &j);
2066 if (j)
2067 error(ERR_NONFATAL,
2068 "unable to parse parameter count `%s'",
2069 tline->text);
2070 if (searching.nparam_min > searching.nparam_max)
2071 error(ERR_NONFATAL,
2072 "minimum parameter count exceeds maximum");
2075 if (tline && tok_is_(tline->next, "+")) {
2076 tline = tline->next;
2077 searching.plus = true;
2079 ed = (ExpDef *) hash_findix(&expdefs, searching.name);
2080 while (ed != NULL) {
2081 if (!strcmp(ed->name, searching.name) &&
2082 (ed->nparam_min <= searching.nparam_max || searching.plus) &&
2083 (searching.nparam_min <= ed->nparam_max || ed->plus)) {
2084 found = true;
2085 break;
2087 ed = ed->next;
2089 if (tline && tline->next)
2090 error(ERR_WARNING|ERR_PASS1,
2091 "trailing garbage after %%ifmacro ignored");
2092 nasm_free(searching.name);
2093 j = found;
2094 break;
2097 case PPC_IFID:
2098 needtype = TOK_ID;
2099 goto iftype;
2100 case PPC_IFNUM:
2101 needtype = TOK_NUMBER;
2102 goto iftype;
2103 case PPC_IFSTR:
2104 needtype = TOK_STRING;
2105 goto iftype;
2107 iftype:
2108 t = tline = expand_smacro(tline);
2110 while (tok_type_(t, TOK_WHITESPACE) ||
2111 (needtype == TOK_NUMBER &&
2112 tok_type_(t, TOK_OTHER) &&
2113 (t->text[0] == '-' || t->text[0] == '+') &&
2114 !t->text[1]))
2115 t = t->next;
2117 j = tok_type_(t, needtype);
2118 break;
2120 case PPC_IFTOKEN:
2121 t = tline = expand_smacro(tline);
2122 while (tok_type_(t, TOK_WHITESPACE))
2123 t = t->next;
2125 j = false;
2126 if (t) {
2127 t = t->next; /* Skip the actual token */
2128 while (tok_type_(t, TOK_WHITESPACE))
2129 t = t->next;
2130 j = !t; /* Should be nothing left */
2132 break;
2134 case PPC_IFEMPTY:
2135 t = tline = expand_smacro(tline);
2136 while (tok_type_(t, TOK_WHITESPACE))
2137 t = t->next;
2139 j = !t; /* Should be empty */
2140 break;
2142 case PPC_IF:
2143 t = tline = expand_smacro(tline);
2144 tptr = &t;
2145 tokval.t_type = TOKEN_INVALID;
2146 evalresult = evaluate(ppscan, tptr, &tokval,
2147 NULL, pass | CRITICAL, error, NULL);
2148 if (!evalresult)
2149 return -1;
2150 if (tokval.t_type)
2151 error(ERR_WARNING|ERR_PASS1,
2152 "trailing garbage after expression ignored");
2153 if (!is_simple(evalresult)) {
2154 error(ERR_NONFATAL,
2155 "non-constant value given to `%s'", pp_directives[ct]);
2156 goto fail;
2158 j = reloc_value(evalresult) != 0;
2159 break;
2161 default:
2162 error(ERR_FATAL,
2163 "preprocessor directive `%s' not yet implemented",
2164 pp_directives[ct]);
2165 goto fail;
2168 free_tlist(origline);
2169 return j ^ PP_NEGATIVE(ct);
2171 fail:
2172 free_tlist(origline);
2173 return -1;
2177 * Common code for defining an smacro
2179 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
2180 int nparam, Token *expansion)
2182 SMacro *smac, **smhead;
2183 struct hash_table *smtbl;
2185 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
2186 if (!smac) {
2187 error(ERR_WARNING|ERR_PASS1,
2188 "single-line macro `%s' defined both with and"
2189 " without parameters", mname);
2191 * Some instances of the old code considered this a failure,
2192 * some others didn't. What is the right thing to do here?
2194 free_tlist(expansion);
2195 return false; /* Failure */
2196 } else {
2198 * We're redefining, so we have to take over an
2199 * existing SMacro structure. This means freeing
2200 * what was already in it.
2202 nasm_free(smac->name);
2203 free_tlist(smac->expansion);
2205 } else {
2206 smtbl = ctx ? &ctx->localmac : &smacros;
2207 smhead = (SMacro **) hash_findi_add(smtbl, mname);
2208 smac = nasm_zalloc(sizeof(SMacro));
2209 smac->next = *smhead;
2210 *smhead = smac;
2212 smac->name = nasm_strdup(mname);
2213 smac->casesense = casesense;
2214 smac->nparam = nparam;
2215 smac->expansion = expansion;
2216 smac->in_progress = false;
2217 return true; /* Success */
2221 * Undefine an smacro
2223 static void undef_smacro(Context *ctx, const char *mname)
2225 SMacro **smhead, *s, **sp;
2226 struct hash_table *smtbl;
2228 smtbl = ctx ? &ctx->localmac : &smacros;
2229 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
2231 if (smhead) {
2233 * We now have a macro name... go hunt for it.
2235 sp = smhead;
2236 while ((s = *sp) != NULL) {
2237 if (!mstrcmp(s->name, mname, s->casesense)) {
2238 *sp = s->next;
2239 nasm_free(s->name);
2240 free_tlist(s->expansion);
2241 nasm_free(s);
2242 } else {
2243 sp = &s->next;
2250 * Parse a mmacro specification.
2252 static bool parse_mmacro_spec(Token *tline, ExpDef *def, const char *directive)
2254 bool err;
2256 tline = tline->next;
2257 skip_white_(tline);
2258 tline = expand_id(tline);
2259 if (!tok_type_(tline, TOK_ID)) {
2260 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
2261 return false;
2264 def->name = nasm_strdup(tline->text);
2265 def->plus = false;
2266 def->nolist = false;
2267 // def->in_progress = 0;
2268 // def->rep_nest = NULL;
2269 def->nparam_min = 0;
2270 def->nparam_max = 0;
2272 tline = expand_smacro(tline->next);
2273 skip_white_(tline);
2274 if (!tok_type_(tline, TOK_NUMBER)) {
2275 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
2276 } else {
2277 def->nparam_min = def->nparam_max =
2278 readnum(tline->text, &err);
2279 if (err)
2280 error(ERR_NONFATAL,
2281 "unable to parse parameter count `%s'", tline->text);
2283 if (tline && tok_is_(tline->next, "-")) {
2284 tline = tline->next->next;
2285 if (tok_is_(tline, "*")) {
2286 def->nparam_max = INT_MAX;
2287 } else if (!tok_type_(tline, TOK_NUMBER)) {
2288 error(ERR_NONFATAL,
2289 "`%s' expects a parameter count after `-'", directive);
2290 } else {
2291 def->nparam_max = readnum(tline->text, &err);
2292 if (err) {
2293 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
2294 tline->text);
2296 if (def->nparam_min > def->nparam_max) {
2297 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
2301 if (tline && tok_is_(tline->next, "+")) {
2302 tline = tline->next;
2303 def->plus = true;
2305 if (tline && tok_type_(tline->next, TOK_ID) &&
2306 !nasm_stricmp(tline->next->text, ".nolist")) {
2307 tline = tline->next;
2308 def->nolist = true;
2312 * Handle default parameters.
2314 if (tline && tline->next) {
2315 def->dlist = tline->next;
2316 tline->next = NULL;
2317 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
2318 } else {
2319 def->dlist = NULL;
2320 def->defaults = NULL;
2322 def->line = NULL;
2324 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2325 !def->plus)
2326 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2327 "too many default macro parameters");
2329 return true;
2334 * Decode a size directive
2336 static int parse_size(const char *str) {
2337 static const char *size_names[] =
2338 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2339 static const int sizes[] =
2340 { 0, 1, 4, 16, 8, 10, 2, 32 };
2342 return sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1];
2346 * find and process preprocessor directive in passed line
2347 * Find out if a line contains a preprocessor directive, and deal
2348 * with it if so.
2350 * If a directive _is_ found, it is the responsibility of this routine
2351 * (and not the caller) to free_tlist() the line.
2353 * @param tline a pointer to the current tokeninzed line linked list
2354 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2357 static int do_directive(Token * tline)
2359 enum preproc_token i;
2360 int j;
2361 bool err;
2362 int nparam;
2363 bool nolist;
2364 bool casesense;
2365 int k, m;
2366 int offset;
2367 char *p, *pp;
2368 const char *mname;
2369 Include *inc;
2370 Context *ctx;
2371 Line *l;
2372 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2373 struct tokenval tokval;
2374 expr *evalresult;
2375 ExpDef *ed, *eed, **edhead;
2376 ExpInv *ei, *eei;
2377 int64_t count;
2378 size_t len;
2379 int severity;
2381 origline = tline;
2383 skip_white_(tline);
2384 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2385 (tline->text[1] == '%' || tline->text[1] == '$'
2386 || tline->text[1] == '!'))
2387 return NO_DIRECTIVE_FOUND;
2389 i = pp_token_hash(tline->text);
2391 switch (i) {
2392 case PP_INVALID:
2393 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2394 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2395 tline->text);
2396 return NO_DIRECTIVE_FOUND; /* didn't get it */
2398 case PP_STACKSIZE:
2399 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2400 /* Directive to tell NASM what the default stack size is. The
2401 * default is for a 16-bit stack, and this can be overriden with
2402 * %stacksize large.
2404 tline = tline->next;
2405 if (tline && tline->type == TOK_WHITESPACE)
2406 tline = tline->next;
2407 if (!tline || tline->type != TOK_ID) {
2408 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2409 free_tlist(origline);
2410 return DIRECTIVE_FOUND;
2412 if (nasm_stricmp(tline->text, "flat") == 0) {
2413 /* All subsequent ARG directives are for a 32-bit stack */
2414 StackSize = 4;
2415 StackPointer = "ebp";
2416 ArgOffset = 8;
2417 LocalOffset = 0;
2418 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2419 /* All subsequent ARG directives are for a 64-bit stack */
2420 StackSize = 8;
2421 StackPointer = "rbp";
2422 ArgOffset = 16;
2423 LocalOffset = 0;
2424 } else if (nasm_stricmp(tline->text, "large") == 0) {
2425 /* All subsequent ARG directives are for a 16-bit stack,
2426 * far function call.
2428 StackSize = 2;
2429 StackPointer = "bp";
2430 ArgOffset = 4;
2431 LocalOffset = 0;
2432 } else if (nasm_stricmp(tline->text, "small") == 0) {
2433 /* All subsequent ARG directives are for a 16-bit stack,
2434 * far function call. We don't support near functions.
2436 StackSize = 2;
2437 StackPointer = "bp";
2438 ArgOffset = 6;
2439 LocalOffset = 0;
2440 } else {
2441 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2442 free_tlist(origline);
2443 return DIRECTIVE_FOUND;
2445 free_tlist(origline);
2446 return DIRECTIVE_FOUND;
2448 case PP_ARG:
2449 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2450 /* TASM like ARG directive to define arguments to functions, in
2451 * the following form:
2453 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2455 offset = ArgOffset;
2456 do {
2457 char *arg, directive[256];
2458 int size = StackSize;
2460 /* Find the argument name */
2461 tline = tline->next;
2462 if (tline && tline->type == TOK_WHITESPACE)
2463 tline = tline->next;
2464 if (!tline || tline->type != TOK_ID) {
2465 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2466 free_tlist(origline);
2467 return DIRECTIVE_FOUND;
2469 arg = tline->text;
2471 /* Find the argument size type */
2472 tline = tline->next;
2473 if (!tline || tline->type != TOK_OTHER
2474 || tline->text[0] != ':') {
2475 error(ERR_NONFATAL,
2476 "Syntax error processing `%%arg' directive");
2477 free_tlist(origline);
2478 return DIRECTIVE_FOUND;
2480 tline = tline->next;
2481 if (!tline || tline->type != TOK_ID) {
2482 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2483 free_tlist(origline);
2484 return DIRECTIVE_FOUND;
2487 /* Allow macro expansion of type parameter */
2488 tt = tokenize(tline->text);
2489 tt = expand_smacro(tt);
2490 size = parse_size(tt->text);
2491 if (!size) {
2492 error(ERR_NONFATAL,
2493 "Invalid size type for `%%arg' missing directive");
2494 free_tlist(tt);
2495 free_tlist(origline);
2496 return DIRECTIVE_FOUND;
2498 free_tlist(tt);
2500 /* Round up to even stack slots */
2501 size = ALIGN(size, StackSize);
2503 /* Now define the macro for the argument */
2504 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2505 arg, StackPointer, offset);
2506 do_directive(tokenize(directive));
2507 offset += size;
2509 /* Move to the next argument in the list */
2510 tline = tline->next;
2511 if (tline && tline->type == TOK_WHITESPACE)
2512 tline = tline->next;
2513 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2514 ArgOffset = offset;
2515 free_tlist(origline);
2516 return DIRECTIVE_FOUND;
2518 case PP_LOCAL:
2519 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2520 /* TASM like LOCAL directive to define local variables for a
2521 * function, in the following form:
2523 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2525 * The '= LocalSize' at the end is ignored by NASM, but is
2526 * required by TASM to define the local parameter size (and used
2527 * by the TASM macro package).
2529 offset = LocalOffset;
2530 do {
2531 char *local, directive[256];
2532 int size = StackSize;
2534 /* Find the argument name */
2535 tline = tline->next;
2536 if (tline && tline->type == TOK_WHITESPACE)
2537 tline = tline->next;
2538 if (!tline || tline->type != TOK_ID) {
2539 error(ERR_NONFATAL,
2540 "`%%local' missing argument parameter");
2541 free_tlist(origline);
2542 return DIRECTIVE_FOUND;
2544 local = tline->text;
2546 /* Find the argument size type */
2547 tline = tline->next;
2548 if (!tline || tline->type != TOK_OTHER
2549 || tline->text[0] != ':') {
2550 error(ERR_NONFATAL,
2551 "Syntax error processing `%%local' directive");
2552 free_tlist(origline);
2553 return DIRECTIVE_FOUND;
2555 tline = tline->next;
2556 if (!tline || tline->type != TOK_ID) {
2557 error(ERR_NONFATAL,
2558 "`%%local' missing size type parameter");
2559 free_tlist(origline);
2560 return DIRECTIVE_FOUND;
2563 /* Allow macro expansion of type parameter */
2564 tt = tokenize(tline->text);
2565 tt = expand_smacro(tt);
2566 size = parse_size(tt->text);
2567 if (!size) {
2568 error(ERR_NONFATAL,
2569 "Invalid size type for `%%local' missing directive");
2570 free_tlist(tt);
2571 free_tlist(origline);
2572 return DIRECTIVE_FOUND;
2574 free_tlist(tt);
2576 /* Round up to even stack slots */
2577 size = ALIGN(size, StackSize);
2579 offset += size; /* Negative offset, increment before */
2581 /* Now define the macro for the argument */
2582 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2583 local, StackPointer, offset);
2584 do_directive(tokenize(directive));
2586 /* Now define the assign to setup the enter_c macro correctly */
2587 snprintf(directive, sizeof(directive),
2588 "%%assign %%$localsize %%$localsize+%d", size);
2589 do_directive(tokenize(directive));
2591 /* Move to the next argument in the list */
2592 tline = tline->next;
2593 if (tline && tline->type == TOK_WHITESPACE)
2594 tline = tline->next;
2595 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2596 LocalOffset = offset;
2597 free_tlist(origline);
2598 return DIRECTIVE_FOUND;
2600 case PP_CLEAR:
2601 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2602 if (tline->next)
2603 error(ERR_WARNING|ERR_PASS1,
2604 "trailing garbage after `%%clear' ignored");
2605 free_macros();
2606 init_macros();
2607 free_tlist(origline);
2608 return DIRECTIVE_FOUND;
2610 case PP_DEPEND:
2611 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2612 t = tline->next = expand_smacro(tline->next);
2613 skip_white_(t);
2614 if (!t || (t->type != TOK_STRING &&
2615 t->type != TOK_INTERNAL_STRING)) {
2616 error(ERR_NONFATAL, "`%%depend' expects a file name");
2617 free_tlist(origline);
2618 return DIRECTIVE_FOUND; /* but we did _something_ */
2620 if (t->next)
2621 error(ERR_WARNING|ERR_PASS1,
2622 "trailing garbage after `%%depend' ignored");
2623 p = t->text;
2624 if (t->type != TOK_INTERNAL_STRING)
2625 nasm_unquote_cstr(p, i);
2626 if (dephead && !in_list(*dephead, p)) {
2627 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2628 sl->next = NULL;
2629 strcpy(sl->str, p);
2630 *deptail = sl;
2631 deptail = &sl->next;
2633 free_tlist(origline);
2634 return DIRECTIVE_FOUND;
2636 case PP_INCLUDE:
2637 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2638 t = tline->next = expand_smacro(tline->next);
2639 skip_white_(t);
2641 if (!t || (t->type != TOK_STRING &&
2642 t->type != TOK_INTERNAL_STRING)) {
2643 error(ERR_NONFATAL, "`%%include' expects a file name");
2644 free_tlist(origline);
2645 return DIRECTIVE_FOUND; /* but we did _something_ */
2647 if (t->next)
2648 error(ERR_WARNING|ERR_PASS1,
2649 "trailing garbage after `%%include' ignored");
2650 p = t->text;
2651 if (t->type != TOK_INTERNAL_STRING)
2652 nasm_unquote_cstr(p, i);
2653 inc = nasm_zalloc(sizeof(Include));
2654 inc->next = istk;
2655 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2656 if (!inc->fp) {
2657 /* -MG given but file not found */
2658 nasm_free(inc);
2659 } else {
2660 inc->fname = src_set_fname(nasm_strdup(p));
2661 inc->lineno = src_set_linnum(0);
2662 inc->lineinc = 1;
2663 inc->expansion = NULL;
2664 istk = inc;
2665 list->uplevel(LIST_INCLUDE);
2667 free_tlist(origline);
2668 return DIRECTIVE_FOUND;
2670 case PP_USE:
2671 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2673 static macros_t *use_pkg;
2674 const char *pkg_macro = NULL;
2676 tline = tline->next;
2677 skip_white_(tline);
2678 tline = expand_id(tline);
2680 if (!tline || (tline->type != TOK_STRING &&
2681 tline->type != TOK_INTERNAL_STRING &&
2682 tline->type != TOK_ID)) {
2683 error(ERR_NONFATAL, "`%%use' expects a package name");
2684 free_tlist(origline);
2685 return DIRECTIVE_FOUND; /* but we did _something_ */
2687 if (tline->next)
2688 error(ERR_WARNING|ERR_PASS1,
2689 "trailing garbage after `%%use' ignored");
2690 if (tline->type == TOK_STRING)
2691 nasm_unquote_cstr(tline->text, i);
2692 use_pkg = nasm_stdmac_find_package(tline->text);
2693 if (!use_pkg)
2694 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2695 else
2696 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2697 if (use_pkg && ! smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2698 /* Not already included, go ahead and include it */
2699 stdmacpos = use_pkg;
2701 free_tlist(origline);
2702 return DIRECTIVE_FOUND;
2704 case PP_PUSH:
2705 case PP_REPL:
2706 case PP_POP:
2707 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2708 tline = tline->next;
2709 skip_white_(tline);
2710 tline = expand_id(tline);
2711 if (tline) {
2712 if (!tok_type_(tline, TOK_ID)) {
2713 error(ERR_NONFATAL, "`%s' expects a context identifier",
2714 pp_directives[i]);
2715 free_tlist(origline);
2716 return DIRECTIVE_FOUND; /* but we did _something_ */
2718 if (tline->next)
2719 error(ERR_WARNING|ERR_PASS1,
2720 "trailing garbage after `%s' ignored",
2721 pp_directives[i]);
2722 p = nasm_strdup(tline->text);
2723 } else {
2724 p = NULL; /* Anonymous */
2727 if (i == PP_PUSH) {
2728 ctx = nasm_zalloc(sizeof(Context));
2729 ctx->next = cstk;
2730 hash_init(&ctx->localmac, HASH_SMALL);
2731 ctx->name = p;
2732 ctx->number = unique++;
2733 cstk = ctx;
2734 } else {
2735 /* %pop or %repl */
2736 if (!cstk) {
2737 error(ERR_NONFATAL, "`%s': context stack is empty",
2738 pp_directives[i]);
2739 } else if (i == PP_POP) {
2740 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2741 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2742 "expected %s",
2743 cstk->name ? cstk->name : "anonymous", p);
2744 else
2745 ctx_pop();
2746 } else {
2747 /* i == PP_REPL */
2748 nasm_free(cstk->name);
2749 cstk->name = p;
2750 p = NULL;
2752 nasm_free(p);
2754 free_tlist(origline);
2755 return DIRECTIVE_FOUND;
2756 case PP_FATAL:
2757 severity = ERR_FATAL;
2758 goto issue_error;
2759 case PP_ERROR:
2760 severity = ERR_NONFATAL;
2761 goto issue_error;
2762 case PP_WARNING:
2763 severity = ERR_WARNING|ERR_WARN_USER;
2764 goto issue_error;
2766 issue_error:
2767 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2769 /* Only error out if this is the final pass */
2770 if (pass != 2 && i != PP_FATAL)
2771 return DIRECTIVE_FOUND;
2773 tline->next = expand_smacro(tline->next);
2774 tline = tline->next;
2775 skip_white_(tline);
2776 t = tline ? tline->next : NULL;
2777 skip_white_(t);
2778 if (tok_type_(tline, TOK_STRING) && !t) {
2779 /* The line contains only a quoted string */
2780 p = tline->text;
2781 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2782 error(severity, "%s", p);
2783 } else {
2784 /* Not a quoted string, or more than a quoted string */
2785 p = detoken(tline, false);
2786 error(severity, "%s", p);
2787 nasm_free(p);
2789 free_tlist(origline);
2790 return DIRECTIVE_FOUND;
2793 CASE_PP_IF:
2794 if (defining != NULL) {
2795 if (defining->type == EXP_IF) {
2796 defining->def_depth ++;
2798 return NO_DIRECTIVE_FOUND;
2800 if ((istk->expansion != NULL) &&
2801 (istk->expansion->emitting == false)) {
2802 j = COND_NEVER;
2803 } else {
2804 j = if_condition(tline->next, i);
2805 tline->next = NULL; /* it got freed */
2806 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
2808 ed = new_ExpDef(EXP_IF);
2809 ed->state = j;
2810 ed->nolist = NULL;
2811 ed->def_depth = 0;
2812 ed->cur_depth = 0;
2813 ed->max_depth = 0;
2814 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
2815 ed->prev = defining;
2816 defining = ed;
2817 free_tlist(origline);
2818 return DIRECTIVE_FOUND;
2820 CASE_PP_ELIF:
2821 if (defining != NULL) {
2822 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2823 return NO_DIRECTIVE_FOUND;
2826 if ((defining == NULL) || (defining->type != EXP_IF)) {
2827 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2829 switch (defining->state) {
2830 case COND_IF_TRUE:
2831 defining->state = COND_DONE;
2832 defining->ignoring = true;
2833 break;
2835 case COND_DONE:
2836 case COND_NEVER:
2837 defining->ignoring = true;
2838 break;
2840 case COND_ELSE_TRUE:
2841 case COND_ELSE_FALSE:
2842 error_precond(ERR_WARNING|ERR_PASS1,
2843 "`%%elif' after `%%else' ignored");
2844 defining->state = COND_NEVER;
2845 defining->ignoring = true;
2846 break;
2848 case COND_IF_FALSE:
2850 * IMPORTANT: In the case of %if, we will already have
2851 * called expand_mmac_params(); however, if we're
2852 * processing an %elif we must have been in a
2853 * non-emitting mode, which would have inhibited
2854 * the normal invocation of expand_mmac_params().
2855 * Therefore, we have to do it explicitly here.
2857 j = if_condition(expand_mmac_params(tline->next), i);
2858 tline->next = NULL; /* it got freed */
2859 defining->state =
2860 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2861 defining->ignoring = ((defining->state == COND_IF_TRUE) ? false : true);
2862 break;
2864 free_tlist(origline);
2865 return DIRECTIVE_FOUND;
2867 case PP_ELSE:
2868 if (defining != NULL) {
2869 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2870 return NO_DIRECTIVE_FOUND;
2873 if (tline->next)
2874 error_precond(ERR_WARNING|ERR_PASS1,
2875 "trailing garbage after `%%else' ignored");
2876 if ((defining == NULL) || (defining->type != EXP_IF)) {
2877 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2879 switch (defining->state) {
2880 case COND_IF_TRUE:
2881 case COND_DONE:
2882 defining->state = COND_ELSE_FALSE;
2883 defining->ignoring = true;
2884 break;
2886 case COND_NEVER:
2887 defining->ignoring = true;
2888 break;
2890 case COND_IF_FALSE:
2891 defining->state = COND_ELSE_TRUE;
2892 defining->ignoring = false;
2893 break;
2895 case COND_ELSE_TRUE:
2896 case COND_ELSE_FALSE:
2897 error_precond(ERR_WARNING|ERR_PASS1,
2898 "`%%else' after `%%else' ignored.");
2899 defining->state = COND_NEVER;
2900 defining->ignoring = true;
2901 break;
2903 free_tlist(origline);
2904 return DIRECTIVE_FOUND;
2906 case PP_ENDIF:
2907 if (defining != NULL) {
2908 if (defining->type == EXP_IF) {
2909 if (defining->def_depth > 0) {
2910 defining->def_depth --;
2911 return NO_DIRECTIVE_FOUND;
2913 } else {
2914 return NO_DIRECTIVE_FOUND;
2917 if (tline->next)
2918 error_precond(ERR_WARNING|ERR_PASS1,
2919 "trailing garbage after `%%endif' ignored");
2920 if ((defining == NULL) || (defining->type != EXP_IF)) {
2921 error(ERR_NONFATAL, "`%%endif': no matching `%%if'");
2922 return DIRECTIVE_FOUND;
2924 ed = defining;
2925 defining = ed->prev;
2926 ed->prev = expansions;
2927 expansions = ed;
2928 ei = new_ExpInv(EXP_IF, ed);
2929 ei->current = ed->line;
2930 ei->emitting = true;
2931 ei->prev = istk->expansion;
2932 istk->expansion = ei;
2933 free_tlist(origline);
2934 return DIRECTIVE_FOUND;
2936 case PP_RMACRO:
2937 case PP_IRMACRO:
2938 case PP_MACRO:
2939 case PP_IMACRO:
2940 if (defining != NULL) {
2941 if (defining->type == EXP_MMACRO) {
2942 defining->def_depth ++;
2944 return NO_DIRECTIVE_FOUND;
2946 ed = new_ExpDef(EXP_MMACRO);
2947 ed->max_depth =
2948 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2949 ed->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2950 if (!parse_mmacro_spec(tline, ed, pp_directives[i])) {
2951 nasm_free(ed);
2952 ed = NULL;
2953 return DIRECTIVE_FOUND;
2955 ed->def_depth = 0;
2956 ed->cur_depth = 0;
2957 ed->max_depth = (ed->max_depth + 1);
2958 ed->ignoring = false;
2959 ed->prev = defining;
2960 defining = ed;
2962 eed = (ExpDef *) hash_findix(&expdefs, ed->name);
2963 while (eed) {
2964 if (!strcmp(eed->name, ed->name) &&
2965 (eed->nparam_min <= ed->nparam_max || ed->plus) &&
2966 (ed->nparam_min <= eed->nparam_max || eed->plus)) {
2967 error(ERR_WARNING|ERR_PASS1,
2968 "redefining multi-line macro `%s'", ed->name);
2969 return DIRECTIVE_FOUND;
2971 eed = eed->next;
2973 free_tlist(origline);
2974 return DIRECTIVE_FOUND;
2976 case PP_ENDM:
2977 case PP_ENDMACRO:
2978 if (defining != NULL) {
2979 if (defining->type == EXP_MMACRO) {
2980 if (defining->def_depth > 0) {
2981 defining->def_depth --;
2982 return NO_DIRECTIVE_FOUND;
2984 } else {
2985 return NO_DIRECTIVE_FOUND;
2988 if (!(defining) || (defining->type != EXP_MMACRO)) {
2989 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2990 return DIRECTIVE_FOUND;
2992 edhead = (ExpDef **) hash_findi_add(&expdefs, defining->name);
2993 defining->next = *edhead;
2994 *edhead = defining;
2995 ed = defining;
2996 defining = ed->prev;
2997 ed->prev = expansions;
2998 expansions = ed;
2999 ed = NULL;
3000 free_tlist(origline);
3001 return DIRECTIVE_FOUND;
3003 case PP_EXITMACRO:
3004 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3006 * We must search along istk->expansion until we hit a
3007 * macro invocation. Then we disable the emitting state(s)
3008 * between exitmacro and endmacro.
3010 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3011 if(ei->type == EXP_MMACRO) {
3012 break;
3016 if (ei != NULL) {
3018 * Set all invocations leading back to the macro
3019 * invocation to a non-emitting state.
3021 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3022 eei->emitting = false;
3024 eei->emitting = false;
3025 } else {
3026 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
3028 free_tlist(origline);
3029 return DIRECTIVE_FOUND;
3031 case PP_UNMACRO:
3032 case PP_UNIMACRO:
3033 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3035 ExpDef **ed_p;
3036 ExpDef spec;
3038 spec.casesense = (i == PP_UNMACRO);
3039 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
3040 return DIRECTIVE_FOUND;
3042 ed_p = (ExpDef **) hash_findi(&expdefs, spec.name, NULL);
3043 while (ed_p && *ed_p) {
3044 ed = *ed_p;
3045 if (ed->casesense == spec.casesense &&
3046 !mstrcmp(ed->name, spec.name, spec.casesense) &&
3047 ed->nparam_min == spec.nparam_min &&
3048 ed->nparam_max == spec.nparam_max &&
3049 ed->plus == spec.plus) {
3050 if (ed->cur_depth > 0) {
3051 error(ERR_NONFATAL, "`%s' ignored on active macro",
3052 pp_directives[i]);
3053 break;
3054 } else {
3055 *ed_p = ed->next;
3056 free_expdef(ed);
3058 } else {
3059 ed_p = &ed->next;
3062 free_tlist(origline);
3063 free_tlist(spec.dlist);
3064 return DIRECTIVE_FOUND;
3067 case PP_ROTATE:
3068 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3069 if (tline->next && tline->next->type == TOK_WHITESPACE)
3070 tline = tline->next;
3071 if (!tline->next) {
3072 free_tlist(origline);
3073 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
3074 return DIRECTIVE_FOUND;
3076 t = expand_smacro(tline->next);
3077 tline->next = NULL;
3078 free_tlist(origline);
3079 tline = t;
3080 tptr = &t;
3081 tokval.t_type = TOKEN_INVALID;
3082 evalresult =
3083 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3084 free_tlist(tline);
3085 if (!evalresult)
3086 return DIRECTIVE_FOUND;
3087 if (tokval.t_type)
3088 error(ERR_WARNING|ERR_PASS1,
3089 "trailing garbage after expression ignored");
3090 if (!is_simple(evalresult)) {
3091 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
3092 return DIRECTIVE_FOUND;
3094 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3095 if (ei->type == EXP_MMACRO) {
3096 break;
3099 if (ei == NULL) {
3100 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
3101 } else if (ei->nparam == 0) {
3102 error(ERR_NONFATAL,
3103 "`%%rotate' invoked within macro without parameters");
3104 } else {
3105 int rotate = ei->rotate + reloc_value(evalresult);
3107 rotate %= (int)ei->nparam;
3108 if (rotate < 0)
3109 rotate += ei->nparam;
3110 ei->rotate = rotate;
3112 return DIRECTIVE_FOUND;
3114 case PP_REP:
3115 if (defining != NULL) {
3116 if (defining->type == EXP_REP) {
3117 defining->def_depth ++;
3119 return NO_DIRECTIVE_FOUND;
3121 nolist = false;
3122 do {
3123 tline = tline->next;
3124 } while (tok_type_(tline, TOK_WHITESPACE));
3126 if (tok_type_(tline, TOK_ID) &&
3127 nasm_stricmp(tline->text, ".nolist") == 0) {
3128 nolist = true;
3129 do {
3130 tline = tline->next;
3131 } while (tok_type_(tline, TOK_WHITESPACE));
3134 if (tline) {
3135 t = expand_smacro(tline);
3136 tptr = &t;
3137 tokval.t_type = TOKEN_INVALID;
3138 evalresult =
3139 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3140 if (!evalresult) {
3141 free_tlist(origline);
3142 return DIRECTIVE_FOUND;
3144 if (tokval.t_type)
3145 error(ERR_WARNING|ERR_PASS1,
3146 "trailing garbage after expression ignored");
3147 if (!is_simple(evalresult)) {
3148 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
3149 return DIRECTIVE_FOUND;
3151 count = reloc_value(evalresult);
3152 if (count >= REP_LIMIT) {
3153 error(ERR_NONFATAL, "`%%rep' value exceeds limit");
3154 count = 0;
3155 } else
3156 count++;
3157 } else {
3158 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
3159 count = 0;
3161 free_tlist(origline);
3162 ed = new_ExpDef(EXP_REP);
3163 ed->nolist = nolist;
3164 ed->def_depth = 0;
3165 ed->cur_depth = 1;
3166 ed->max_depth = (count - 1);
3167 ed->ignoring = false;
3168 ed->prev = defining;
3169 defining = ed;
3170 return DIRECTIVE_FOUND;
3172 case PP_ENDREP:
3173 if (defining != NULL) {
3174 if (defining->type == EXP_REP) {
3175 if (defining->def_depth > 0) {
3176 defining->def_depth --;
3177 return NO_DIRECTIVE_FOUND;
3179 } else {
3180 return NO_DIRECTIVE_FOUND;
3183 if ((defining == NULL) || (defining->type != EXP_REP)) {
3184 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
3185 return DIRECTIVE_FOUND;
3189 * Now we have a "macro" defined - although it has no name
3190 * and we won't be entering it in the hash tables - we must
3191 * push a macro-end marker for it on to istk->expansion.
3192 * After that, it will take care of propagating itself (a
3193 * macro-end marker line for a macro which is really a %rep
3194 * block will cause the macro to be re-expanded, complete
3195 * with another macro-end marker to ensure the process
3196 * continues) until the whole expansion is forcibly removed
3197 * from istk->expansion by a %exitrep.
3199 ed = defining;
3200 defining = ed->prev;
3201 ed->prev = expansions;
3202 expansions = ed;
3203 ei = new_ExpInv(EXP_REP, ed);
3204 ei->current = ed->line;
3205 ei->emitting = ((ed->max_depth > 0) ? true : false);
3206 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
3207 ei->prev = istk->expansion;
3208 istk->expansion = ei;
3209 free_tlist(origline);
3210 return DIRECTIVE_FOUND;
3212 case PP_EXITREP:
3213 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3215 * We must search along istk->expansion until we hit a
3216 * rep invocation. Then we disable the emitting state(s)
3217 * between exitrep and endrep.
3219 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3220 if (ei->type == EXP_REP) {
3221 break;
3225 if (ei != NULL) {
3227 * Set all invocations leading back to the rep
3228 * invocation to a non-emitting state.
3230 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3231 eei->emitting = false;
3233 eei->emitting = false;
3234 eei->current = NULL;
3235 eei->def->cur_depth = eei->def->max_depth;
3236 } else {
3237 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
3239 free_tlist(origline);
3240 return DIRECTIVE_FOUND;
3242 case PP_XDEFINE:
3243 case PP_IXDEFINE:
3244 case PP_DEFINE:
3245 case PP_IDEFINE:
3246 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3247 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
3249 tline = tline->next;
3250 skip_white_(tline);
3251 tline = expand_id(tline);
3252 if (!tline || (tline->type != TOK_ID &&
3253 (tline->type != TOK_PREPROC_ID ||
3254 tline->text[1] != '$'))) {
3255 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3256 pp_directives[i]);
3257 free_tlist(origline);
3258 return DIRECTIVE_FOUND;
3261 ctx = get_ctx(tline->text, &mname, false);
3262 last = tline;
3263 param_start = tline = tline->next;
3264 nparam = 0;
3266 /* Expand the macro definition now for %xdefine and %ixdefine */
3267 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
3268 tline = expand_smacro(tline);
3270 if (tok_is_(tline, "(")) {
3272 * This macro has parameters.
3275 tline = tline->next;
3276 while (1) {
3277 skip_white_(tline);
3278 if (!tline) {
3279 error(ERR_NONFATAL, "parameter identifier expected");
3280 free_tlist(origline);
3281 return DIRECTIVE_FOUND;
3283 if (tline->type != TOK_ID) {
3284 error(ERR_NONFATAL,
3285 "`%s': parameter identifier expected",
3286 tline->text);
3287 free_tlist(origline);
3288 return DIRECTIVE_FOUND;
3290 tline->type = TOK_SMAC_PARAM + nparam++;
3291 tline = tline->next;
3292 skip_white_(tline);
3293 if (tok_is_(tline, ",")) {
3294 tline = tline->next;
3295 } else {
3296 if (!tok_is_(tline, ")")) {
3297 error(ERR_NONFATAL,
3298 "`)' expected to terminate macro template");
3299 free_tlist(origline);
3300 return DIRECTIVE_FOUND;
3302 break;
3305 last = tline;
3306 tline = tline->next;
3308 if (tok_type_(tline, TOK_WHITESPACE))
3309 last = tline, tline = tline->next;
3310 macro_start = NULL;
3311 last->next = NULL;
3312 t = tline;
3313 while (t) {
3314 if (t->type == TOK_ID) {
3315 list_for_each(tt, param_start)
3316 if (tt->type >= TOK_SMAC_PARAM &&
3317 !strcmp(tt->text, t->text))
3318 t->type = tt->type;
3320 tt = t->next;
3321 t->next = macro_start;
3322 macro_start = t;
3323 t = tt;
3326 * Good. We now have a macro name, a parameter count, and a
3327 * token list (in reverse order) for an expansion. We ought
3328 * to be OK just to create an SMacro, store it, and let
3329 * free_tlist have the rest of the line (which we have
3330 * carefully re-terminated after chopping off the expansion
3331 * from the end).
3333 define_smacro(ctx, mname, casesense, nparam, macro_start);
3334 free_tlist(origline);
3335 return DIRECTIVE_FOUND;
3337 case PP_UNDEF:
3338 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3339 tline = tline->next;
3340 skip_white_(tline);
3341 tline = expand_id(tline);
3342 if (!tline || (tline->type != TOK_ID &&
3343 (tline->type != TOK_PREPROC_ID ||
3344 tline->text[1] != '$'))) {
3345 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
3346 free_tlist(origline);
3347 return DIRECTIVE_FOUND;
3349 if (tline->next) {
3350 error(ERR_WARNING|ERR_PASS1,
3351 "trailing garbage after macro name ignored");
3354 /* Find the context that symbol belongs to */
3355 ctx = get_ctx(tline->text, &mname, false);
3356 undef_smacro(ctx, mname);
3357 free_tlist(origline);
3358 return DIRECTIVE_FOUND;
3360 case PP_DEFSTR:
3361 case PP_IDEFSTR:
3362 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3363 casesense = (i == PP_DEFSTR);
3365 tline = tline->next;
3366 skip_white_(tline);
3367 tline = expand_id(tline);
3368 if (!tline || (tline->type != TOK_ID &&
3369 (tline->type != TOK_PREPROC_ID ||
3370 tline->text[1] != '$'))) {
3371 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3372 pp_directives[i]);
3373 free_tlist(origline);
3374 return DIRECTIVE_FOUND;
3377 ctx = get_ctx(tline->text, &mname, false);
3378 last = tline;
3379 tline = expand_smacro(tline->next);
3380 last->next = NULL;
3382 while (tok_type_(tline, TOK_WHITESPACE))
3383 tline = delete_Token(tline);
3385 p = detoken(tline, false);
3386 macro_start = nasm_zalloc(sizeof(*macro_start));
3387 macro_start->text = nasm_quote(p, strlen(p));
3388 macro_start->type = TOK_STRING;
3389 nasm_free(p);
3392 * We now have a macro name, an implicit parameter count of
3393 * zero, and a string token to use as an expansion. Create
3394 * and store an SMacro.
3396 define_smacro(ctx, mname, casesense, 0, macro_start);
3397 free_tlist(origline);
3398 return DIRECTIVE_FOUND;
3400 case PP_DEFTOK:
3401 case PP_IDEFTOK:
3402 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3403 casesense = (i == PP_DEFTOK);
3405 tline = tline->next;
3406 skip_white_(tline);
3407 tline = expand_id(tline);
3408 if (!tline || (tline->type != TOK_ID &&
3409 (tline->type != TOK_PREPROC_ID ||
3410 tline->text[1] != '$'))) {
3411 error(ERR_NONFATAL,
3412 "`%s' expects a macro identifier as first parameter",
3413 pp_directives[i]);
3414 free_tlist(origline);
3415 return DIRECTIVE_FOUND;
3417 ctx = get_ctx(tline->text, &mname, false);
3418 last = tline;
3419 tline = expand_smacro(tline->next);
3420 last->next = NULL;
3422 t = tline;
3423 while (tok_type_(t, TOK_WHITESPACE))
3424 t = t->next;
3425 /* t should now point to the string */
3426 if (!tok_type_(t, TOK_STRING)) {
3427 error(ERR_NONFATAL,
3428 "`%s` requires string as second parameter",
3429 pp_directives[i]);
3430 free_tlist(tline);
3431 free_tlist(origline);
3432 return DIRECTIVE_FOUND;
3436 * Convert the string to a token stream. Note that smacros
3437 * are stored with the token stream reversed, so we have to
3438 * reverse the output of tokenize().
3440 nasm_unquote_cstr(t->text, i);
3441 macro_start = reverse_tokens(tokenize(t->text));
3444 * We now have a macro name, an implicit parameter count of
3445 * zero, and a numeric token to use as an expansion. Create
3446 * and store an SMacro.
3448 define_smacro(ctx, mname, casesense, 0, macro_start);
3449 free_tlist(tline);
3450 free_tlist(origline);
3451 return DIRECTIVE_FOUND;
3453 case PP_PATHSEARCH:
3454 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3456 FILE *fp;
3457 StrList *xsl = NULL;
3458 StrList **xst = &xsl;
3460 casesense = true;
3462 tline = tline->next;
3463 skip_white_(tline);
3464 tline = expand_id(tline);
3465 if (!tline || (tline->type != TOK_ID &&
3466 (tline->type != TOK_PREPROC_ID ||
3467 tline->text[1] != '$'))) {
3468 error(ERR_NONFATAL,
3469 "`%%pathsearch' expects a macro identifier as first parameter");
3470 free_tlist(origline);
3471 return DIRECTIVE_FOUND;
3473 ctx = get_ctx(tline->text, &mname, false);
3474 last = tline;
3475 tline = expand_smacro(tline->next);
3476 last->next = NULL;
3478 t = tline;
3479 while (tok_type_(t, TOK_WHITESPACE))
3480 t = t->next;
3482 if (!t || (t->type != TOK_STRING &&
3483 t->type != TOK_INTERNAL_STRING)) {
3484 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3485 free_tlist(tline);
3486 free_tlist(origline);
3487 return DIRECTIVE_FOUND; /* but we did _something_ */
3489 if (t->next)
3490 error(ERR_WARNING|ERR_PASS1,
3491 "trailing garbage after `%%pathsearch' ignored");
3492 p = t->text;
3493 if (t->type != TOK_INTERNAL_STRING)
3494 nasm_unquote(p, NULL);
3496 fp = inc_fopen(p, &xsl, &xst, true);
3497 if (fp) {
3498 p = xsl->str;
3499 fclose(fp); /* Don't actually care about the file */
3501 macro_start = nasm_zalloc(sizeof(*macro_start));
3502 macro_start->text = nasm_quote(p, strlen(p));
3503 macro_start->type = TOK_STRING;
3504 if (xsl)
3505 nasm_free(xsl);
3508 * We now have a macro name, an implicit parameter count of
3509 * zero, and a string token to use as an expansion. Create
3510 * and store an SMacro.
3512 define_smacro(ctx, mname, casesense, 0, macro_start);
3513 free_tlist(tline);
3514 free_tlist(origline);
3515 return DIRECTIVE_FOUND;
3518 case PP_STRLEN:
3519 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3520 casesense = true;
3522 tline = tline->next;
3523 skip_white_(tline);
3524 tline = expand_id(tline);
3525 if (!tline || (tline->type != TOK_ID &&
3526 (tline->type != TOK_PREPROC_ID ||
3527 tline->text[1] != '$'))) {
3528 error(ERR_NONFATAL,
3529 "`%%strlen' expects a macro identifier as first parameter");
3530 free_tlist(origline);
3531 return DIRECTIVE_FOUND;
3533 ctx = get_ctx(tline->text, &mname, false);
3534 last = tline;
3535 tline = expand_smacro(tline->next);
3536 last->next = NULL;
3538 t = tline;
3539 while (tok_type_(t, TOK_WHITESPACE))
3540 t = t->next;
3541 /* t should now point to the string */
3542 if (!tok_type_(t, TOK_STRING)) {
3543 error(ERR_NONFATAL,
3544 "`%%strlen` requires string as second parameter");
3545 free_tlist(tline);
3546 free_tlist(origline);
3547 return DIRECTIVE_FOUND;
3550 macro_start = nasm_zalloc(sizeof(*macro_start));
3551 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3554 * We now have a macro name, an implicit parameter count of
3555 * zero, and a numeric token to use as an expansion. Create
3556 * and store an SMacro.
3558 define_smacro(ctx, mname, casesense, 0, macro_start);
3559 free_tlist(tline);
3560 free_tlist(origline);
3561 return DIRECTIVE_FOUND;
3563 case PP_STRCAT:
3564 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3565 casesense = true;
3567 tline = tline->next;
3568 skip_white_(tline);
3569 tline = expand_id(tline);
3570 if (!tline || (tline->type != TOK_ID &&
3571 (tline->type != TOK_PREPROC_ID ||
3572 tline->text[1] != '$'))) {
3573 error(ERR_NONFATAL,
3574 "`%%strcat' expects a macro identifier as first parameter");
3575 free_tlist(origline);
3576 return DIRECTIVE_FOUND;
3578 ctx = get_ctx(tline->text, &mname, false);
3579 last = tline;
3580 tline = expand_smacro(tline->next);
3581 last->next = NULL;
3583 len = 0;
3584 list_for_each(t, tline) {
3585 switch (t->type) {
3586 case TOK_WHITESPACE:
3587 break;
3588 case TOK_STRING:
3589 len += t->a.len = nasm_unquote(t->text, NULL);
3590 break;
3591 case TOK_OTHER:
3592 if (!strcmp(t->text, ",")) /* permit comma separators */
3593 break;
3594 /* else fall through */
3595 default:
3596 error(ERR_NONFATAL,
3597 "non-string passed to `%%strcat' (%d)", t->type);
3598 free_tlist(tline);
3599 free_tlist(origline);
3600 return DIRECTIVE_FOUND;
3604 p = pp = nasm_malloc(len);
3605 list_for_each(t, tline) {
3606 if (t->type == TOK_STRING) {
3607 memcpy(p, t->text, t->a.len);
3608 p += t->a.len;
3613 * We now have a macro name, an implicit parameter count of
3614 * zero, and a numeric token to use as an expansion. Create
3615 * and store an SMacro.
3617 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3618 macro_start->text = nasm_quote(pp, len);
3619 nasm_free(pp);
3620 define_smacro(ctx, mname, casesense, 0, macro_start);
3621 free_tlist(tline);
3622 free_tlist(origline);
3623 return DIRECTIVE_FOUND;
3625 case PP_SUBSTR:
3626 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3628 int64_t start, count;
3629 size_t len;
3631 casesense = true;
3633 tline = tline->next;
3634 skip_white_(tline);
3635 tline = expand_id(tline);
3636 if (!tline || (tline->type != TOK_ID &&
3637 (tline->type != TOK_PREPROC_ID ||
3638 tline->text[1] != '$'))) {
3639 error(ERR_NONFATAL,
3640 "`%%substr' expects a macro identifier as first parameter");
3641 free_tlist(origline);
3642 return DIRECTIVE_FOUND;
3644 ctx = get_ctx(tline->text, &mname, false);
3645 last = tline;
3646 tline = expand_smacro(tline->next);
3647 last->next = NULL;
3649 if (tline) /* skip expanded id */
3650 t = tline->next;
3651 while (tok_type_(t, TOK_WHITESPACE))
3652 t = t->next;
3654 /* t should now point to the string */
3655 if (!tok_type_(t, TOK_STRING)) {
3656 error(ERR_NONFATAL,
3657 "`%%substr` requires string as second parameter");
3658 free_tlist(tline);
3659 free_tlist(origline);
3660 return DIRECTIVE_FOUND;
3663 tt = t->next;
3664 tptr = &tt;
3665 tokval.t_type = TOKEN_INVALID;
3666 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3667 pass, error, NULL);
3668 if (!evalresult) {
3669 free_tlist(tline);
3670 free_tlist(origline);
3671 return DIRECTIVE_FOUND;
3672 } else if (!is_simple(evalresult)) {
3673 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3674 free_tlist(tline);
3675 free_tlist(origline);
3676 return DIRECTIVE_FOUND;
3678 start = evalresult->value - 1;
3680 while (tok_type_(tt, TOK_WHITESPACE))
3681 tt = tt->next;
3682 if (!tt) {
3683 count = 1; /* Backwards compatibility: one character */
3684 } else {
3685 tokval.t_type = TOKEN_INVALID;
3686 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3687 pass, error, NULL);
3688 if (!evalresult) {
3689 free_tlist(tline);
3690 free_tlist(origline);
3691 return DIRECTIVE_FOUND;
3692 } else if (!is_simple(evalresult)) {
3693 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3694 free_tlist(tline);
3695 free_tlist(origline);
3696 return DIRECTIVE_FOUND;
3698 count = evalresult->value;
3701 len = nasm_unquote(t->text, NULL);
3702 /* make start and count being in range */
3703 if (start < 0)
3704 start = 0;
3705 if (count < 0)
3706 count = len + count + 1 - start;
3707 if (start + count > (int64_t)len)
3708 count = len - start;
3709 if (!len || count < 0 || start >=(int64_t)len)
3710 start = -1, count = 0; /* empty string */
3712 macro_start = nasm_zalloc(sizeof(*macro_start));
3713 macro_start->text = nasm_quote((start < 0) ? "" : t->text + start, count);
3714 macro_start->type = TOK_STRING;
3717 * We now have a macro name, an implicit parameter count of
3718 * zero, and a numeric token to use as an expansion. Create
3719 * and store an SMacro.
3721 define_smacro(ctx, mname, casesense, 0, macro_start);
3722 free_tlist(tline);
3723 free_tlist(origline);
3724 return DIRECTIVE_FOUND;
3727 case PP_ASSIGN:
3728 case PP_IASSIGN:
3729 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3730 casesense = (i == PP_ASSIGN);
3732 tline = tline->next;
3733 skip_white_(tline);
3734 tline = expand_id(tline);
3735 if (!tline || (tline->type != TOK_ID &&
3736 (tline->type != TOK_PREPROC_ID ||
3737 tline->text[1] != '$'))) {
3738 error(ERR_NONFATAL,
3739 "`%%%sassign' expects a macro identifier",
3740 (i == PP_IASSIGN ? "i" : ""));
3741 free_tlist(origline);
3742 return DIRECTIVE_FOUND;
3744 ctx = get_ctx(tline->text, &mname, false);
3745 last = tline;
3746 tline = expand_smacro(tline->next);
3747 last->next = NULL;
3749 t = tline;
3750 tptr = &t;
3751 tokval.t_type = TOKEN_INVALID;
3752 evalresult =
3753 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3754 free_tlist(tline);
3755 if (!evalresult) {
3756 free_tlist(origline);
3757 return DIRECTIVE_FOUND;
3760 if (tokval.t_type)
3761 error(ERR_WARNING|ERR_PASS1,
3762 "trailing garbage after expression ignored");
3764 if (!is_simple(evalresult)) {
3765 error(ERR_NONFATAL,
3766 "non-constant value given to `%%%sassign'",
3767 (i == PP_IASSIGN ? "i" : ""));
3768 free_tlist(origline);
3769 return DIRECTIVE_FOUND;
3772 macro_start = nasm_zalloc(sizeof(*macro_start));
3773 make_tok_num(macro_start, reloc_value(evalresult));
3776 * We now have a macro name, an implicit parameter count of
3777 * zero, and a numeric token to use as an expansion. Create
3778 * and store an SMacro.
3780 define_smacro(ctx, mname, casesense, 0, macro_start);
3781 free_tlist(origline);
3782 return DIRECTIVE_FOUND;
3784 case PP_LINE:
3785 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3787 * Syntax is `%line nnn[+mmm] [filename]'
3789 tline = tline->next;
3790 skip_white_(tline);
3791 if (!tok_type_(tline, TOK_NUMBER)) {
3792 error(ERR_NONFATAL, "`%%line' expects line number");
3793 free_tlist(origline);
3794 return DIRECTIVE_FOUND;
3796 k = readnum(tline->text, &err);
3797 m = 1;
3798 tline = tline->next;
3799 if (tok_is_(tline, "+")) {
3800 tline = tline->next;
3801 if (!tok_type_(tline, TOK_NUMBER)) {
3802 error(ERR_NONFATAL, "`%%line' expects line increment");
3803 free_tlist(origline);
3804 return DIRECTIVE_FOUND;
3806 m = readnum(tline->text, &err);
3807 tline = tline->next;
3809 skip_white_(tline);
3810 src_set_linnum(k);
3811 istk->lineinc = m;
3812 if (tline) {
3813 nasm_free(src_set_fname(detoken(tline, false)));
3815 free_tlist(origline);
3816 return DIRECTIVE_FOUND;
3818 case PP_WHILE:
3819 if (defining != NULL) {
3820 if (defining->type == EXP_WHILE) {
3821 defining->def_depth ++;
3823 return NO_DIRECTIVE_FOUND;
3825 l = NULL;
3826 if ((istk->expansion != NULL) &&
3827 (istk->expansion->emitting == false)) {
3828 j = COND_NEVER;
3829 } else {
3830 l = new_Line();
3831 l->first = copy_Token(tline->next);
3832 j = if_condition(tline->next, i);
3833 tline->next = NULL; /* it got freed */
3834 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
3836 ed = new_ExpDef(EXP_WHILE);
3837 ed->state = j;
3838 ed->cur_depth = 1;
3839 ed->max_depth = DEADMAN_LIMIT;
3840 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
3841 if (ed->ignoring == false) {
3842 ed->line = l;
3843 ed->last = l;
3844 } else if (l != NULL) {
3845 delete_Token(l->first);
3846 nasm_free(l);
3847 l = NULL;
3849 ed->prev = defining;
3850 defining = ed;
3851 free_tlist(origline);
3852 return DIRECTIVE_FOUND;
3854 case PP_ENDWHILE:
3855 if (defining != NULL) {
3856 if (defining->type == EXP_WHILE) {
3857 if (defining->def_depth > 0) {
3858 defining->def_depth --;
3859 return NO_DIRECTIVE_FOUND;
3861 } else {
3862 return NO_DIRECTIVE_FOUND;
3865 if (tline->next != NULL) {
3866 error_precond(ERR_WARNING|ERR_PASS1,
3867 "trailing garbage after `%%endwhile' ignored");
3869 if ((defining == NULL) || (defining->type != EXP_WHILE)) {
3870 error(ERR_NONFATAL, "`%%endwhile': no matching `%%while'");
3871 return DIRECTIVE_FOUND;
3873 ed = defining;
3874 defining = ed->prev;
3875 if (ed->ignoring == false) {
3876 ed->prev = expansions;
3877 expansions = ed;
3878 ei = new_ExpInv(EXP_WHILE, ed);
3879 ei->current = ed->line->next;
3880 ei->emitting = true;
3881 ei->prev = istk->expansion;
3882 istk->expansion = ei;
3883 } else {
3884 nasm_free(ed);
3886 free_tlist(origline);
3887 return DIRECTIVE_FOUND;
3889 case PP_EXITWHILE:
3890 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3892 * We must search along istk->expansion until we hit a
3893 * while invocation. Then we disable the emitting state(s)
3894 * between exitwhile and endwhile.
3896 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3897 if (ei->type == EXP_WHILE) {
3898 break;
3902 if (ei != NULL) {
3904 * Set all invocations leading back to the while
3905 * invocation to a non-emitting state.
3907 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3908 eei->emitting = false;
3910 eei->emitting = false;
3911 eei->current = NULL;
3912 eei->def->cur_depth = eei->def->max_depth;
3913 } else {
3914 error(ERR_NONFATAL, "`%%exitwhile' not within `%%while' block");
3916 free_tlist(origline);
3917 return DIRECTIVE_FOUND;
3919 case PP_COMMENT:
3920 if (defining != NULL) {
3921 if (defining->type == EXP_COMMENT) {
3922 defining->def_depth ++;
3924 return NO_DIRECTIVE_FOUND;
3926 ed = new_ExpDef(EXP_COMMENT);
3927 ed->ignoring = true;
3928 ed->prev = defining;
3929 defining = ed;
3930 free_tlist(origline);
3931 return DIRECTIVE_FOUND;
3933 case PP_ENDCOMMENT:
3934 if (defining != NULL) {
3935 if (defining->type == EXP_COMMENT) {
3936 if (defining->def_depth > 0) {
3937 defining->def_depth --;
3938 return NO_DIRECTIVE_FOUND;
3940 } else {
3941 return NO_DIRECTIVE_FOUND;
3944 if ((defining == NULL) || (defining->type != EXP_COMMENT)) {
3945 error(ERR_NONFATAL, "`%%endcomment': no matching `%%comment'");
3946 return DIRECTIVE_FOUND;
3948 ed = defining;
3949 defining = ed->prev;
3950 nasm_free(ed);
3951 free_tlist(origline);
3952 return DIRECTIVE_FOUND;
3954 case PP_FINAL:
3955 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3956 if (in_final != false) {
3957 error(ERR_FATAL, "`%%final' cannot be used recursively");
3959 tline = tline->next;
3960 skip_white_(tline);
3961 if (tline == NULL) {
3962 error(ERR_NONFATAL, "`%%final' expects at least one parameter");
3963 } else {
3964 l = new_Line();
3965 l->first = copy_Token(tline);
3966 l->next = finals;
3967 finals = l;
3969 free_tlist(origline);
3970 return DIRECTIVE_FOUND;
3972 default:
3973 error(ERR_FATAL,
3974 "preprocessor directive `%s' not yet implemented",
3975 pp_directives[i]);
3976 return DIRECTIVE_FOUND;
3981 * Ensure that a macro parameter contains a condition code and
3982 * nothing else. Return the condition code index if so, or -1
3983 * otherwise.
3985 static int find_cc(Token * t)
3987 Token *tt;
3988 int i, j, k, m;
3990 if (!t)
3991 return -1; /* Probably a %+ without a space */
3993 skip_white_(t);
3994 if (t->type != TOK_ID)
3995 return -1;
3996 tt = t->next;
3997 skip_white_(tt);
3998 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3999 return -1;
4001 i = -1;
4002 j = ARRAY_SIZE(conditions);
4003 while (j - i > 1) {
4004 k = (j + i) / 2;
4005 m = nasm_stricmp(t->text, conditions[k]);
4006 if (m == 0) {
4007 i = k;
4008 j = -2;
4009 break;
4010 } else if (m < 0) {
4011 j = k;
4012 } else
4013 i = k;
4015 if (j != -2)
4016 return -1;
4017 return i;
4020 static bool paste_tokens(Token **head, const struct tokseq_match *m,
4021 int mnum, bool handle_paste_tokens)
4023 Token **tail, *t, *tt;
4024 Token **paste_head;
4025 bool did_paste = false;
4026 char *tmp;
4027 int i;
4029 /* Now handle token pasting... */
4030 paste_head = NULL;
4031 tail = head;
4032 while ((t = *tail) && (tt = t->next)) {
4033 switch (t->type) {
4034 case TOK_WHITESPACE:
4035 if (tt->type == TOK_WHITESPACE) {
4036 /* Zap adjacent whitespace tokens */
4037 t->next = delete_Token(tt);
4038 } else {
4039 /* Do not advance paste_head here */
4040 tail = &t->next;
4042 break;
4043 case TOK_PASTE: /* %+ */
4044 if (handle_paste_tokens) {
4045 /* Zap %+ and whitespace tokens to the right */
4046 while (t && (t->type == TOK_WHITESPACE ||
4047 t->type == TOK_PASTE))
4048 t = *tail = delete_Token(t);
4049 if (!paste_head || !t)
4050 break; /* Nothing to paste with */
4051 tail = paste_head;
4052 t = *tail;
4053 tt = t->next;
4054 while (tok_type_(tt, TOK_WHITESPACE))
4055 tt = t->next = delete_Token(tt);
4056 if (tt) {
4057 tmp = nasm_strcat(t->text, tt->text);
4058 delete_Token(t);
4059 tt = delete_Token(tt);
4060 t = *tail = tokenize(tmp);
4061 nasm_free(tmp);
4062 while (t->next) {
4063 tail = &t->next;
4064 t = t->next;
4066 t->next = tt; /* Attach the remaining token chain */
4067 did_paste = true;
4069 paste_head = tail;
4070 tail = &t->next;
4071 break;
4073 /* else fall through */
4074 default:
4076 * Concatenation of tokens might look nontrivial
4077 * but in real it's pretty simple -- the caller
4078 * prepares the masks of token types to be concatenated
4079 * and we simply find matched sequences and slip
4080 * them together
4082 for (i = 0; i < mnum; i++) {
4083 if (PP_CONCAT_MASK(t->type) & m[i].mask_head) {
4084 size_t len = 0;
4085 char *tmp, *p;
4087 while (tt && (PP_CONCAT_MASK(tt->type) & m[i].mask_tail)) {
4088 len += strlen(tt->text);
4089 tt = tt->next;
4092 nasm_dump_token(tt);
4095 * Now tt points to the first token after
4096 * the potential paste area...
4098 if (tt != t->next) {
4099 /* We have at least two tokens... */
4100 len += strlen(t->text);
4101 p = tmp = nasm_malloc(len+1);
4102 while (t != tt) {
4103 strcpy(p, t->text);
4104 p = strchr(p, '\0');
4105 t = delete_Token(t);
4107 t = *tail = tokenize(tmp);
4108 nasm_free(tmp);
4109 while (t->next) {
4110 tail = &t->next;
4111 t = t->next;
4113 t->next = tt; /* Attach the remaining token chain */
4114 did_paste = true;
4116 paste_head = tail;
4117 tail = &t->next;
4118 break;
4121 if (i >= mnum) { /* no match */
4122 tail = &t->next;
4123 if (!tok_type_(t->next, TOK_WHITESPACE))
4124 paste_head = tail;
4126 break;
4129 return did_paste;
4133 * expands to a list of tokens from %{x:y}
4135 static Token *expand_mmac_params_range(ExpInv *ei, Token *tline, Token ***last)
4137 Token *t = tline, **tt, *tm, *head;
4138 char *pos;
4139 int fst, lst, j, i;
4141 pos = strchr(tline->text, ':');
4142 nasm_assert(pos);
4144 lst = atoi(pos + 1);
4145 fst = atoi(tline->text + 1);
4148 * only macros params are accounted so
4149 * if someone passes %0 -- we reject such
4150 * value(s)
4152 if (lst == 0 || fst == 0)
4153 goto err;
4155 /* the values should be sane */
4156 if ((fst > (int)ei->nparam || fst < (-(int)ei->nparam)) ||
4157 (lst > (int)ei->nparam || lst < (-(int)ei->nparam)))
4158 goto err;
4160 fst = fst < 0 ? fst + (int)ei->nparam + 1: fst;
4161 lst = lst < 0 ? lst + (int)ei->nparam + 1: lst;
4163 /* counted from zero */
4164 fst--, lst--;
4167 * it will be at least one token
4169 tm = ei->params[(fst + ei->rotate) % ei->nparam];
4170 t = new_Token(NULL, tm->type, tm->text, 0);
4171 head = t, tt = &t->next;
4172 if (fst < lst) {
4173 for (i = fst + 1; i <= lst; i++) {
4174 t = new_Token(NULL, TOK_OTHER, ",", 0);
4175 *tt = t, tt = &t->next;
4176 j = (i + ei->rotate) % ei->nparam;
4177 tm = ei->params[j];
4178 t = new_Token(NULL, tm->type, tm->text, 0);
4179 *tt = t, tt = &t->next;
4181 } else {
4182 for (i = fst - 1; i >= lst; i--) {
4183 t = new_Token(NULL, TOK_OTHER, ",", 0);
4184 *tt = t, tt = &t->next;
4185 j = (i + ei->rotate) % ei->nparam;
4186 tm = ei->params[j];
4187 t = new_Token(NULL, tm->type, tm->text, 0);
4188 *tt = t, tt = &t->next;
4192 *last = tt;
4193 return head;
4195 err:
4196 error(ERR_NONFATAL, "`%%{%s}': macro parameters out of range",
4197 &tline->text[1]);
4198 return tline;
4202 * Expand MMacro-local things: parameter references (%0, %n, %+n,
4203 * %-n) and MMacro-local identifiers (%%foo) as well as
4204 * macro indirection (%[...]) and range (%{..:..}).
4206 static Token *expand_mmac_params(Token * tline)
4208 Token *t, *tt, **tail, *thead;
4209 bool changed = false;
4210 char *pos;
4212 tail = &thead;
4213 thead = NULL;
4215 nasm_dump_stream(tline);
4217 while (tline) {
4218 if (tline->type == TOK_PREPROC_ID &&
4219 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text[2]) ||
4220 (tline->text[1] >= '0' && tline->text[1] <= '9') ||
4221 tline->text[1] == '%')) {
4222 char *text = NULL;
4223 int type = 0, cc; /* type = 0 to placate optimisers */
4224 char tmpbuf[30];
4225 unsigned int n;
4226 int i;
4227 ExpInv *ei;
4229 t = tline;
4230 tline = tline->next;
4232 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
4233 if (ei->type == EXP_MMACRO) {
4234 break;
4237 if (ei == NULL) {
4238 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
4239 } else {
4240 pos = strchr(t->text, ':');
4241 if (!pos) {
4242 switch (t->text[1]) {
4244 * We have to make a substitution of one of the
4245 * forms %1, %-1, %+1, %%foo, %0.
4247 case '0':
4248 if ((strlen(t->text) > 2) && (t->text[2] == '0')) {
4249 type = TOK_ID;
4250 text = nasm_strdup(ei->label_text);
4251 } else {
4252 type = TOK_NUMBER;
4253 snprintf(tmpbuf, sizeof(tmpbuf), "%d", ei->nparam);
4254 text = nasm_strdup(tmpbuf);
4256 break;
4257 case '%':
4258 type = TOK_ID;
4259 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
4260 ei->unique);
4261 text = nasm_strcat(tmpbuf, t->text + 2);
4262 break;
4263 case '-':
4264 n = atoi(t->text + 2) - 1;
4265 if (n >= ei->nparam)
4266 tt = NULL;
4267 else {
4268 if (ei->nparam > 1)
4269 n = (n + ei->rotate) % ei->nparam;
4270 tt = ei->params[n];
4272 cc = find_cc(tt);
4273 if (cc == -1) {
4274 error(ERR_NONFATAL,
4275 "macro parameter %d is not a condition code",
4276 n + 1);
4277 text = NULL;
4278 } else {
4279 type = TOK_ID;
4280 if (inverse_ccs[cc] == -1) {
4281 error(ERR_NONFATAL,
4282 "condition code `%s' is not invertible",
4283 conditions[cc]);
4284 text = NULL;
4285 } else
4286 text = nasm_strdup(conditions[inverse_ccs[cc]]);
4288 break;
4289 case '+':
4290 n = atoi(t->text + 2) - 1;
4291 if (n >= ei->nparam)
4292 tt = NULL;
4293 else {
4294 if (ei->nparam > 1)
4295 n = (n + ei->rotate) % ei->nparam;
4296 tt = ei->params[n];
4298 cc = find_cc(tt);
4299 if (cc == -1) {
4300 error(ERR_NONFATAL,
4301 "macro parameter %d is not a condition code",
4302 n + 1);
4303 text = NULL;
4304 } else {
4305 type = TOK_ID;
4306 text = nasm_strdup(conditions[cc]);
4308 break;
4309 default:
4310 n = atoi(t->text + 1) - 1;
4311 if (n >= ei->nparam)
4312 tt = NULL;
4313 else {
4314 if (ei->nparam > 1)
4315 n = (n + ei->rotate) % ei->nparam;
4316 tt = ei->params[n];
4318 if (tt) {
4319 for (i = 0; i < ei->paramlen[n]; i++) {
4320 *tail = new_Token(NULL, tt->type, tt->text, 0);
4321 tail = &(*tail)->next;
4322 tt = tt->next;
4325 text = NULL; /* we've done it here */
4326 break;
4328 } else {
4330 * seems we have a parameters range here
4332 Token *head, **last;
4333 head = expand_mmac_params_range(ei, t, &last);
4334 if (head != t) {
4335 *tail = head;
4336 *last = tline;
4337 tline = head;
4338 text = NULL;
4342 if (!text) {
4343 delete_Token(t);
4344 } else {
4345 *tail = t;
4346 tail = &t->next;
4347 t->type = type;
4348 nasm_free(t->text);
4349 t->text = text;
4350 t->a.mac = NULL;
4352 changed = true;
4353 continue;
4354 } else if (tline->type == TOK_INDIRECT) {
4355 t = tline;
4356 tline = tline->next;
4357 tt = tokenize(t->text);
4358 tt = expand_mmac_params(tt);
4359 tt = expand_smacro(tt);
4360 *tail = tt;
4361 while (tt) {
4362 tt->a.mac = NULL; /* Necessary? */
4363 tail = &tt->next;
4364 tt = tt->next;
4366 delete_Token(t);
4367 changed = true;
4368 } else {
4369 t = *tail = tline;
4370 tline = tline->next;
4371 t->a.mac = NULL;
4372 tail = &t->next;
4375 *tail = NULL;
4377 if (changed)
4378 paste_tokens(&thead, pp_concat_match,
4379 ARRAY_SIZE(pp_concat_match),
4380 false);
4382 nasm_dump_token(thead);
4384 return thead;
4388 * Expand all single-line macro calls made in the given line.
4389 * Return the expanded version of the line. The original is deemed
4390 * to be destroyed in the process. (In reality we'll just move
4391 * Tokens from input to output a lot of the time, rather than
4392 * actually bothering to destroy and replicate.)
4395 static Token *expand_smacro(Token * tline)
4397 Token *t, *tt, *mstart, **tail, *thead;
4398 SMacro *head = NULL, *m;
4399 Token **params;
4400 int *paramsize;
4401 unsigned int nparam, sparam;
4402 int brackets;
4403 Token *org_tline = tline;
4404 Context *ctx;
4405 const char *mname;
4406 int deadman = DEADMAN_LIMIT;
4407 bool expanded;
4410 * Trick: we should avoid changing the start token pointer since it can
4411 * be contained in "next" field of other token. Because of this
4412 * we allocate a copy of first token and work with it; at the end of
4413 * routine we copy it back
4415 if (org_tline) {
4416 tline = new_Token(org_tline->next, org_tline->type,
4417 org_tline->text, 0);
4418 tline->a.mac = org_tline->a.mac;
4419 nasm_free(org_tline->text);
4420 org_tline->text = NULL;
4423 expanded = true; /* Always expand %+ at least once */
4425 again:
4426 thead = NULL;
4427 tail = &thead;
4429 while (tline) { /* main token loop */
4430 if (!--deadman) {
4431 error(ERR_NONFATAL, "interminable macro recursion");
4432 goto err;
4435 if ((mname = tline->text)) {
4436 /* if this token is a local macro, look in local context */
4437 if (tline->type == TOK_ID) {
4438 head = (SMacro *)hash_findix(&smacros, mname);
4439 } else if (tline->type == TOK_PREPROC_ID) {
4440 ctx = get_ctx(mname, &mname, false);
4441 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
4442 } else
4443 head = NULL;
4446 * We've hit an identifier. As in is_mmacro below, we first
4447 * check whether the identifier is a single-line macro at
4448 * all, then think about checking for parameters if
4449 * necessary.
4451 list_for_each(m, head)
4452 if (!mstrcmp(m->name, mname, m->casesense))
4453 break;
4454 if (m) {
4455 mstart = tline;
4456 params = NULL;
4457 paramsize = NULL;
4458 if (m->nparam == 0) {
4460 * Simple case: the macro is parameterless. Discard the
4461 * one token that the macro call took, and push the
4462 * expansion back on the to-do stack.
4464 if (!m->expansion) {
4465 if (!strcmp("__FILE__", m->name)) {
4466 int32_t num = 0;
4467 char *file = NULL;
4468 src_get(&num, &file);
4469 tline->text = nasm_quote(file, strlen(file));
4470 tline->type = TOK_STRING;
4471 nasm_free(file);
4472 continue;
4474 if (!strcmp("__LINE__", m->name)) {
4475 nasm_free(tline->text);
4476 make_tok_num(tline, src_get_linnum());
4477 continue;
4479 if (!strcmp("__BITS__", m->name)) {
4480 nasm_free(tline->text);
4481 make_tok_num(tline, globalbits);
4482 continue;
4484 tline = delete_Token(tline);
4485 continue;
4487 } else {
4489 * Complicated case: at least one macro with this name
4490 * exists and takes parameters. We must find the
4491 * parameters in the call, count them, find the SMacro
4492 * that corresponds to that form of the macro call, and
4493 * substitute for the parameters when we expand. What a
4494 * pain.
4496 /*tline = tline->next;
4497 skip_white_(tline); */
4498 do {
4499 t = tline->next;
4500 while (tok_type_(t, TOK_SMAC_END)) {
4501 t->a.mac->in_progress = false;
4502 t->text = NULL;
4503 t = tline->next = delete_Token(t);
4505 tline = t;
4506 } while (tok_type_(tline, TOK_WHITESPACE));
4507 if (!tok_is_(tline, "(")) {
4509 * This macro wasn't called with parameters: ignore
4510 * the call. (Behaviour borrowed from gnu cpp.)
4512 tline = mstart;
4513 m = NULL;
4514 } else {
4515 int paren = 0;
4516 int white = 0;
4517 brackets = 0;
4518 nparam = 0;
4519 sparam = PARAM_DELTA;
4520 params = nasm_malloc(sparam * sizeof(Token *));
4521 params[0] = tline->next;
4522 paramsize = nasm_malloc(sparam * sizeof(int));
4523 paramsize[0] = 0;
4524 while (true) { /* parameter loop */
4526 * For some unusual expansions
4527 * which concatenates function call
4529 t = tline->next;
4530 while (tok_type_(t, TOK_SMAC_END)) {
4531 t->a.mac->in_progress = false;
4532 t->text = NULL;
4533 t = tline->next = delete_Token(t);
4535 tline = t;
4537 if (!tline) {
4538 error(ERR_NONFATAL,
4539 "macro call expects terminating `)'");
4540 break;
4542 if (tline->type == TOK_WHITESPACE
4543 && brackets <= 0) {
4544 if (paramsize[nparam])
4545 white++;
4546 else
4547 params[nparam] = tline->next;
4548 continue; /* parameter loop */
4550 if (tline->type == TOK_OTHER
4551 && tline->text[1] == 0) {
4552 char ch = tline->text[0];
4553 if (ch == ',' && !paren && brackets <= 0) {
4554 if (++nparam >= sparam) {
4555 sparam += PARAM_DELTA;
4556 params = nasm_realloc(params,
4557 sparam * sizeof(Token *));
4558 paramsize = nasm_realloc(paramsize,
4559 sparam * sizeof(int));
4561 params[nparam] = tline->next;
4562 paramsize[nparam] = 0;
4563 white = 0;
4564 continue; /* parameter loop */
4566 if (ch == '{' &&
4567 (brackets > 0 || (brackets == 0 &&
4568 !paramsize[nparam])))
4570 if (!(brackets++)) {
4571 params[nparam] = tline->next;
4572 continue; /* parameter loop */
4575 if (ch == '}' && brackets > 0)
4576 if (--brackets == 0) {
4577 brackets = -1;
4578 continue; /* parameter loop */
4580 if (ch == '(' && !brackets)
4581 paren++;
4582 if (ch == ')' && brackets <= 0)
4583 if (--paren < 0)
4584 break;
4586 if (brackets < 0) {
4587 brackets = 0;
4588 error(ERR_NONFATAL, "braces do not "
4589 "enclose all of macro parameter");
4591 paramsize[nparam] += white + 1;
4592 white = 0;
4593 } /* parameter loop */
4594 nparam++;
4595 while (m && (m->nparam != nparam ||
4596 mstrcmp(m->name, mname,
4597 m->casesense)))
4598 m = m->next;
4599 if (!m)
4600 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4601 "macro `%s' exists, "
4602 "but not taking %d parameters",
4603 mstart->text, nparam);
4606 if (m && m->in_progress)
4607 m = NULL;
4608 if (!m) { /* in progess or didn't find '(' or wrong nparam */
4610 * Design question: should we handle !tline, which
4611 * indicates missing ')' here, or expand those
4612 * macros anyway, which requires the (t) test a few
4613 * lines down?
4615 nasm_free(params);
4616 nasm_free(paramsize);
4617 tline = mstart;
4618 } else {
4620 * Expand the macro: we are placed on the last token of the
4621 * call, so that we can easily split the call from the
4622 * following tokens. We also start by pushing an SMAC_END
4623 * token for the cycle removal.
4625 t = tline;
4626 if (t) {
4627 tline = t->next;
4628 t->next = NULL;
4630 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4631 tt->a.mac = m;
4632 m->in_progress = true;
4633 tline = tt;
4634 list_for_each(t, m->expansion) {
4635 if (t->type >= TOK_SMAC_PARAM) {
4636 Token *pcopy = tline, **ptail = &pcopy;
4637 Token *ttt, *pt;
4638 int i;
4640 ttt = params[t->type - TOK_SMAC_PARAM];
4641 i = paramsize[t->type - TOK_SMAC_PARAM];
4642 while (--i >= 0) {
4643 pt = *ptail = new_Token(tline, ttt->type,
4644 ttt->text, 0);
4645 ptail = &pt->next;
4646 ttt = ttt->next;
4648 tline = pcopy;
4649 } else if (t->type == TOK_PREPROC_Q) {
4650 tt = new_Token(tline, TOK_ID, mname, 0);
4651 tline = tt;
4652 } else if (t->type == TOK_PREPROC_QQ) {
4653 tt = new_Token(tline, TOK_ID, m->name, 0);
4654 tline = tt;
4655 } else {
4656 tt = new_Token(tline, t->type, t->text, 0);
4657 tline = tt;
4662 * Having done that, get rid of the macro call, and clean
4663 * up the parameters.
4665 nasm_free(params);
4666 nasm_free(paramsize);
4667 free_tlist(mstart);
4668 expanded = true;
4669 continue; /* main token loop */
4674 if (tline->type == TOK_SMAC_END) {
4675 tline->a.mac->in_progress = false;
4676 tline = delete_Token(tline);
4677 } else {
4678 t = *tail = tline;
4679 tline = tline->next;
4680 t->a.mac = NULL;
4681 t->next = NULL;
4682 tail = &t->next;
4687 * Now scan the entire line and look for successive TOK_IDs that resulted
4688 * after expansion (they can't be produced by tokenize()). The successive
4689 * TOK_IDs should be concatenated.
4690 * Also we look for %+ tokens and concatenate the tokens before and after
4691 * them (without white spaces in between).
4693 if (expanded) {
4694 if (paste_tokens(&thead, pp_concat_match,
4695 ARRAY_SIZE(pp_concat_match),
4696 true)) {
4698 * If we concatenated something, *and* we had previously expanded
4699 * an actual macro, scan the lines again for macros...
4701 tline = thead;
4702 expanded = false;
4703 goto again;
4707 err:
4708 if (org_tline) {
4709 if (thead) {
4710 *org_tline = *thead;
4711 /* since we just gave text to org_line, don't free it */
4712 thead->text = NULL;
4713 delete_Token(thead);
4714 } else {
4715 /* the expression expanded to empty line;
4716 we can't return NULL for some reasons
4717 we just set the line to a single WHITESPACE token. */
4718 memset(org_tline, 0, sizeof(*org_tline));
4719 org_tline->text = NULL;
4720 org_tline->type = TOK_WHITESPACE;
4722 thead = org_tline;
4725 return thead;
4729 * Similar to expand_smacro but used exclusively with macro identifiers
4730 * right before they are fetched in. The reason is that there can be
4731 * identifiers consisting of several subparts. We consider that if there
4732 * are more than one element forming the name, user wants a expansion,
4733 * otherwise it will be left as-is. Example:
4735 * %define %$abc cde
4737 * the identifier %$abc will be left as-is so that the handler for %define
4738 * will suck it and define the corresponding value. Other case:
4740 * %define _%$abc cde
4742 * In this case user wants name to be expanded *before* %define starts
4743 * working, so we'll expand %$abc into something (if it has a value;
4744 * otherwise it will be left as-is) then concatenate all successive
4745 * PP_IDs into one.
4747 static Token *expand_id(Token * tline)
4749 Token *cur, *oldnext = NULL;
4751 if (!tline || !tline->next)
4752 return tline;
4754 cur = tline;
4755 while (cur->next &&
4756 (cur->next->type == TOK_ID ||
4757 cur->next->type == TOK_PREPROC_ID
4758 || cur->next->type == TOK_NUMBER))
4759 cur = cur->next;
4761 /* If identifier consists of just one token, don't expand */
4762 if (cur == tline)
4763 return tline;
4765 if (cur) {
4766 oldnext = cur->next; /* Detach the tail past identifier */
4767 cur->next = NULL; /* so that expand_smacro stops here */
4770 tline = expand_smacro(tline);
4772 if (cur) {
4773 /* expand_smacro possibly changhed tline; re-scan for EOL */
4774 cur = tline;
4775 while (cur && cur->next)
4776 cur = cur->next;
4777 if (cur)
4778 cur->next = oldnext;
4781 return tline;
4785 * Determine whether the given line constitutes a multi-line macro
4786 * call, and return the ExpDef structure called if so. Doesn't have
4787 * to check for an initial label - that's taken care of in
4788 * expand_mmacro - but must check numbers of parameters. Guaranteed
4789 * to be called with tline->type == TOK_ID, so the putative macro
4790 * name is easy to find.
4792 static ExpDef *is_mmacro(Token * tline, Token *** params_array)
4794 ExpDef *head, *ed;
4795 Token **params;
4796 int nparam;
4798 head = (ExpDef *) hash_findix(&expdefs, tline->text);
4801 * Efficiency: first we see if any macro exists with the given
4802 * name. If not, we can return NULL immediately. _Then_ we
4803 * count the parameters, and then we look further along the
4804 * list if necessary to find the proper ExpDef.
4806 list_for_each(ed, head)
4807 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4808 break;
4809 if (!ed)
4810 return NULL;
4813 * OK, we have a potential macro. Count and demarcate the
4814 * parameters.
4816 count_mmac_params(tline->next, &nparam, &params);
4819 * So we know how many parameters we've got. Find the ExpDef
4820 * structure that handles this number.
4822 while (ed) {
4823 if (ed->nparam_min <= nparam
4824 && (ed->plus || nparam <= ed->nparam_max)) {
4826 * It's right, and we can use it. Add its default
4827 * parameters to the end of our list if necessary.
4829 if (ed->defaults && nparam < ed->nparam_min + ed->ndefs) {
4830 params =
4831 nasm_realloc(params,
4832 ((ed->nparam_min + ed->ndefs +
4833 1) * sizeof(*params)));
4834 while (nparam < ed->nparam_min + ed->ndefs) {
4835 params[nparam] = ed->defaults[nparam - ed->nparam_min];
4836 nparam++;
4840 * If we've gone over the maximum parameter count (and
4841 * we're in Plus mode), ignore parameters beyond
4842 * nparam_max.
4844 if (ed->plus && nparam > ed->nparam_max)
4845 nparam = ed->nparam_max;
4847 * Then terminate the parameter list, and leave.
4849 if (!params) { /* need this special case */
4850 params = nasm_malloc(sizeof(*params));
4851 nparam = 0;
4853 params[nparam] = NULL;
4854 *params_array = params;
4855 return ed;
4858 * This one wasn't right: look for the next one with the
4859 * same name.
4861 list_for_each(ed, ed->next)
4862 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4863 break;
4867 * After all that, we didn't find one with the right number of
4868 * parameters. Issue a warning, and fail to expand the macro.
4870 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4871 "macro `%s' exists, but not taking %d parameters",
4872 tline->text, nparam);
4873 nasm_free(params);
4874 return NULL;
4878 * Expand the multi-line macro call made by the given line, if
4879 * there is one to be expanded. If there is, push the expansion on
4880 * istk->expansion and return true. Otherwise return false.
4882 static bool expand_mmacro(Token * tline)
4884 Token *label = NULL;
4885 int dont_prepend = 0;
4886 Token **params, *t;
4887 Line *l = NULL;
4888 ExpDef *ed;
4889 ExpInv *ei;
4890 int i, nparam, *paramlen;
4891 const char *mname;
4893 t = tline;
4894 skip_white_(t);
4895 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4896 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4897 return false;
4898 ed = is_mmacro(t, &params);
4899 if (ed != NULL) {
4900 mname = t->text;
4901 } else {
4902 Token *last;
4904 * We have an id which isn't a macro call. We'll assume
4905 * it might be a label; we'll also check to see if a
4906 * colon follows it. Then, if there's another id after
4907 * that lot, we'll check it again for macro-hood.
4909 label = last = t;
4910 t = t->next;
4911 if (tok_type_(t, TOK_WHITESPACE))
4912 last = t, t = t->next;
4913 if (tok_is_(t, ":")) {
4914 dont_prepend = 1;
4915 last = t, t = t->next;
4916 if (tok_type_(t, TOK_WHITESPACE))
4917 last = t, t = t->next;
4919 if (!tok_type_(t, TOK_ID) || !(ed = is_mmacro(t, &params)))
4920 return false;
4921 last->next = NULL;
4922 mname = t->text;
4923 tline = t;
4927 * Fix up the parameters: this involves stripping leading and
4928 * trailing whitespace, then stripping braces if they are
4929 * present.
4931 for (nparam = 0; params[nparam]; nparam++) ;
4932 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4934 for (i = 0; params[i]; i++) {
4935 int brace = false;
4936 int comma = (!ed->plus || i < nparam - 1);
4938 t = params[i];
4939 skip_white_(t);
4940 if (tok_is_(t, "{"))
4941 t = t->next, brace = true, comma = false;
4942 params[i] = t;
4943 paramlen[i] = 0;
4944 while (t) {
4945 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4946 break; /* ... because we have hit a comma */
4947 if (comma && t->type == TOK_WHITESPACE
4948 && tok_is_(t->next, ","))
4949 break; /* ... or a space then a comma */
4950 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4951 break; /* ... or a brace */
4952 t = t->next;
4953 paramlen[i]++;
4957 if (ed->cur_depth >= ed->max_depth) {
4958 if (ed->max_depth > 1) {
4959 error(ERR_WARNING,
4960 "reached maximum macro recursion depth of %i for %s",
4961 ed->max_depth,ed->name);
4963 return false;
4964 } else {
4965 ed->cur_depth ++;
4969 * OK, we have found a ExpDef structure representing a
4970 * previously defined mmacro. Create an expansion invocation
4971 * and point it back to the expansion definition. Substitution of
4972 * parameter tokens and macro-local tokens doesn't get done
4973 * until the single-line macro substitution process; this is
4974 * because delaying them allows us to change the semantics
4975 * later through %rotate.
4977 ei = new_ExpInv(EXP_MMACRO, ed);
4978 ei->name = nasm_strdup(mname);
4979 //ei->label = label;
4980 //ei->label_text = detoken(label, false);
4981 ei->current = ed->line;
4982 ei->emitting = true;
4983 //ei->iline = tline;
4984 ei->params = params;
4985 ei->nparam = nparam;
4986 ei->rotate = 0;
4987 ei->paramlen = paramlen;
4988 ei->lineno = 0;
4990 ei->prev = istk->expansion;
4991 istk->expansion = ei;
4994 * Special case: detect %00 on first invocation; if found,
4995 * avoid emitting any labels that precede the mmacro call.
4996 * ed->prepend is set to -1 when %00 is detected, else 1.
4998 if (ed->prepend == 0) {
4999 for (l = ed->line; l != NULL; l = l->next) {
5000 for (t = l->first; t != NULL; t = t->next) {
5001 if ((t->type == TOK_PREPROC_ID) &&
5002 (strlen(t->text) == 3) &&
5003 (t->text[1] == '0') && (t->text[2] == '0')) {
5004 dont_prepend = -1;
5005 break;
5008 if (dont_prepend < 0) {
5009 break;
5012 ed->prepend = ((dont_prepend < 0) ? -1 : 1);
5016 * If we had a label, push it on as the first line of
5017 * the macro expansion.
5019 if (label != NULL) {
5020 if (ed->prepend < 0) {
5021 ei->label_text = detoken(label, false);
5022 } else {
5023 if (dont_prepend == 0) {
5024 t = label;
5025 while (t->next != NULL) {
5026 t = t->next;
5028 t->next = new_Token(NULL, TOK_OTHER, ":", 0);
5030 l = new_Line();
5031 l->first = copy_Token(label);
5032 l->next = ei->current;
5033 ei->current = l;
5037 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
5039 istk->mmac_depth++;
5040 return true;
5043 /* The function that actually does the error reporting */
5044 static void verror(int severity, const char *fmt, va_list arg)
5046 char buff[1024];
5048 vsnprintf(buff, sizeof(buff), fmt, arg);
5050 if (istk && istk->mmac_depth > 0) {
5051 ExpInv *ei = istk->expansion;
5052 int lineno = ei->lineno;
5053 while (ei) {
5054 if (ei->type == EXP_MMACRO)
5055 break;
5056 lineno += ei->relno;
5057 ei = ei->prev;
5059 nasm_error(severity, "(%s:%d) %s", ei->def->name,
5060 lineno, buff);
5061 } else
5062 nasm_error(severity, "%s", buff);
5066 * Since preprocessor always operate only on the line that didn't
5067 * arrived yet, we should always use ERR_OFFBY1.
5069 static void error(int severity, const char *fmt, ...)
5071 va_list arg;
5072 va_start(arg, fmt);
5073 verror(severity, fmt, arg);
5074 va_end(arg);
5078 * Because %else etc are evaluated in the state context
5079 * of the previous branch, errors might get lost with error():
5080 * %if 0 ... %else trailing garbage ... %endif
5081 * So %else etc should report errors with this function.
5083 static void error_precond(int severity, const char *fmt, ...)
5085 va_list arg;
5087 /* Only ignore the error if it's really in a dead branch */
5088 if ((istk != NULL) &&
5089 (istk->expansion != NULL) &&
5090 (istk->expansion->type == EXP_IF) &&
5091 (istk->expansion->def->state == COND_NEVER))
5092 return;
5094 va_start(arg, fmt);
5095 verror(severity, fmt, arg);
5096 va_end(arg);
5099 static void
5100 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
5102 Token *t;
5104 cstk = NULL;
5105 istk = nasm_zalloc(sizeof(Include));
5106 istk->fp = fopen(file, "r");
5107 src_set_fname(nasm_strdup(file));
5108 src_set_linnum(0);
5109 istk->lineinc = 1;
5110 if (!istk->fp)
5111 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
5112 file);
5113 defining = NULL;
5114 finals = NULL;
5115 in_final = false;
5116 nested_mac_count = 0;
5117 nested_rep_count = 0;
5118 init_macros();
5119 unique = 0;
5120 if (tasm_compatible_mode) {
5121 stdmacpos = nasm_stdmac;
5122 } else {
5123 stdmacpos = nasm_stdmac_after_tasm;
5125 any_extrastdmac = extrastdmac && *extrastdmac;
5126 do_predef = true;
5127 list = listgen;
5130 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
5131 * The caller, however, will also pass in 3 for preprocess-only so
5132 * we can set __PASS__ accordingly.
5134 pass = apass > 2 ? 2 : apass;
5136 dephead = deptail = deplist;
5137 if (deplist) {
5138 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
5139 sl->next = NULL;
5140 strcpy(sl->str, file);
5141 *deptail = sl;
5142 deptail = &sl->next;
5146 * Define the __PASS__ macro. This is defined here unlike
5147 * all the other builtins, because it is special -- it varies between
5148 * passes.
5150 t = nasm_zalloc(sizeof(*t));
5151 make_tok_num(t, apass);
5152 define_smacro(NULL, "__PASS__", true, 0, t);
5155 static char *pp_getline(void)
5157 char *line;
5158 Token *tline;
5159 ExpDef *ed;
5160 ExpInv *ei;
5161 Line *l;
5162 int j;
5164 while (1) {
5166 * Fetch a tokenized line, either from the expansion
5167 * buffer or from the input file.
5169 tline = NULL;
5171 while (1) { /* until we get a line we can use */
5173 * Fetch a tokenized line from the expansion buffer
5175 if (istk->expansion != NULL) {
5176 ei = istk->expansion;
5177 if (ei->current != NULL) {
5178 if (ei->emitting == false) {
5179 ei->current = NULL;
5180 continue;
5182 l = ei->current;
5183 ei->current = l->next;
5184 ei->lineno++;
5185 tline = copy_Token(l->first);
5186 if (((ei->type == EXP_REP) ||
5187 (ei->type == EXP_MMACRO) ||
5188 (ei->type == EXP_WHILE))
5189 && (ei->def->nolist == false)) {
5190 char *p = detoken(tline, false);
5191 list->line(LIST_MACRO, p);
5192 nasm_free(p);
5194 if (ei->linnum > -1) {
5195 src_set_linnum(src_get_linnum() + 1);
5197 break;
5198 } else if ((ei->type == EXP_REP) &&
5199 (ei->def->cur_depth < ei->def->max_depth)) {
5200 ei->def->cur_depth ++;
5201 ei->current = ei->def->line;
5202 ei->lineno = 0;
5203 continue;
5204 } else if ((ei->type == EXP_WHILE) &&
5205 (ei->def->cur_depth < ei->def->max_depth)) {
5206 ei->current = ei->def->line;
5207 ei->lineno = 0;
5208 tline = copy_Token(ei->current->first);
5209 j = if_condition(tline, PP_WHILE);
5210 tline = NULL;
5211 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
5212 if (j == COND_IF_TRUE) {
5213 ei->current = ei->current->next;
5214 ei->def->cur_depth ++;
5215 } else {
5216 ei->emitting = false;
5217 ei->current = NULL;
5218 ei->def->cur_depth = ei->def->max_depth;
5220 continue;
5221 } else {
5222 istk->expansion = ei->prev;
5223 ed = ei->def;
5224 if (ed != NULL) {
5225 if ((ei->emitting == true) &&
5226 (ed->max_depth == DEADMAN_LIMIT) &&
5227 (ed->cur_depth == DEADMAN_LIMIT)
5229 error(ERR_FATAL, "runaway expansion detected, aborting");
5231 if (ed->cur_depth > 0) {
5232 ed->cur_depth --;
5233 } else if (ed->type != EXP_MMACRO) {
5234 expansions = ed->prev;
5235 free_expdef(ed);
5237 if ((ei->type == EXP_REP) ||
5238 (ei->type == EXP_MMACRO) ||
5239 (ei->type == EXP_WHILE)) {
5240 list->downlevel(LIST_MACRO);
5241 if (ei->type == EXP_MMACRO) {
5242 istk->mmac_depth--;
5246 if (ei->linnum > -1) {
5247 src_set_linnum(ei->linnum);
5249 free_expinv(ei);
5250 continue;
5255 * Read in line from input and tokenize
5257 line = read_line();
5258 if (line) { /* from the current input file */
5259 line = prepreproc(line);
5260 tline = tokenize(line);
5261 nasm_free(line);
5262 break;
5266 * The current file has ended; work down the istk
5269 Include *i = istk;
5270 fclose(i->fp);
5271 if (i->expansion != NULL) {
5272 error(ERR_FATAL,
5273 "end of file while still in an expansion");
5275 /* only set line and file name if there's a next node */
5276 if (i->next) {
5277 src_set_linnum(i->lineno);
5278 nasm_free(src_set_fname(nasm_strdup(i->fname)));
5280 if ((i->next == NULL) && (finals != NULL)) {
5281 in_final = true;
5282 ei = new_ExpInv(EXP_FINAL, NULL);
5283 ei->emitting = true;
5284 ei->current = finals;
5285 istk->expansion = ei;
5286 finals = NULL;
5287 continue;
5289 istk = i->next;
5290 list->downlevel(LIST_INCLUDE);
5291 nasm_free(i);
5292 if (istk == NULL) {
5293 if (finals != NULL) {
5294 in_final = true;
5295 } else {
5296 return NULL;
5299 continue;
5303 if (defining == NULL) {
5304 tline = expand_mmac_params(tline);
5308 * Check the line to see if it's a preprocessor directive.
5310 if (do_directive(tline) == DIRECTIVE_FOUND) {
5311 continue;
5312 } else if (defining != NULL) {
5314 * We're defining an expansion. We emit nothing at all,
5315 * and just shove the tokenized line on to the definition.
5317 if (defining->ignoring == false) {
5318 Line *l = new_Line();
5319 l->first = tline;
5320 if (defining->line == NULL) {
5321 defining->line = l;
5322 defining->last = l;
5323 } else {
5324 defining->last->next = l;
5325 defining->last = l;
5327 } else {
5328 free_tlist(tline);
5330 defining->linecount++;
5331 continue;
5332 } else if ((istk->expansion != NULL) &&
5333 (istk->expansion->emitting != true)) {
5335 * We're in a non-emitting branch of an expansion.
5336 * Emit nothing at all, not even a blank line: when we
5337 * emerge from the expansion we'll give a line-number
5338 * directive so we keep our place correctly.
5340 free_tlist(tline);
5341 continue;
5342 } else {
5343 tline = expand_smacro(tline);
5344 if (expand_mmacro(tline) != true) {
5346 * De-tokenize the line again, and emit it.
5348 line = detoken(tline, true);
5349 free_tlist(tline);
5350 break;
5351 } else {
5352 continue;
5356 return line;
5359 static void pp_cleanup(int pass)
5361 if (defining != NULL) {
5362 error(ERR_NONFATAL, "end of file while still defining an expansion");
5363 while (defining != NULL) {
5364 ExpDef *ed = defining;
5365 defining = ed->prev;
5366 free_expdef(ed);
5368 defining = NULL;
5370 while (cstk != NULL)
5371 ctx_pop();
5372 free_macros();
5373 while (istk != NULL) {
5374 Include *i = istk;
5375 istk = istk->next;
5376 fclose(i->fp);
5377 nasm_free(i->fname);
5378 while (i->expansion != NULL) {
5379 ExpInv *ei = i->expansion;
5380 i->expansion = ei->prev;
5381 free_expinv(ei);
5383 nasm_free(i);
5385 while (cstk)
5386 ctx_pop();
5387 nasm_free(src_set_fname(NULL));
5388 if (pass == 0) {
5389 IncPath *i;
5390 free_llist(predef);
5391 delete_Blocks();
5392 while ((i = ipath)) {
5393 ipath = i->next;
5394 if (i->path)
5395 nasm_free(i->path);
5396 nasm_free(i);
5401 void pp_include_path(char *path)
5403 IncPath *i = nasm_zalloc(sizeof(IncPath));
5405 if (path)
5406 i->path = nasm_strdup(path);
5408 if (ipath) {
5409 IncPath *j = ipath;
5410 while (j->next)
5411 j = j->next;
5412 j->next = i;
5413 } else {
5414 ipath = i;
5418 void pp_pre_include(char *fname)
5420 Token *inc, *space, *name;
5421 Line *l;
5423 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
5424 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
5425 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
5427 l = new_Line();
5428 l->next = predef;
5429 l->first = inc;
5430 predef = l;
5433 void pp_pre_define(char *definition)
5435 Token *def, *space;
5436 Line *l;
5437 char *equals;
5439 equals = strchr(definition, '=');
5440 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5441 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
5442 if (equals)
5443 *equals = ' ';
5444 space->next = tokenize(definition);
5445 if (equals)
5446 *equals = '=';
5448 l = new_Line();
5449 l->next = predef;
5450 l->first = def;
5451 predef = l;
5454 void pp_pre_undefine(char *definition)
5456 Token *def, *space;
5457 Line *l;
5459 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5460 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
5461 space->next = tokenize(definition);
5463 l = new_Line();
5464 l->next = predef;
5465 l->first = def;
5466 predef = l;
5470 * This function is used to assist with "runtime" preprocessor
5471 * directives, e.g. pp_runtime("%define __BITS__ 64");
5473 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5474 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5477 void pp_runtime(char *definition)
5479 Token *def;
5481 def = tokenize(definition);
5482 if (do_directive(def) == NO_DIRECTIVE_FOUND)
5483 free_tlist(def);
5487 void pp_extra_stdmac(macros_t *macros)
5489 extrastdmac = macros;
5492 static void make_tok_num(Token * tok, int64_t val)
5494 char numbuf[20];
5495 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
5496 tok->text = nasm_strdup(numbuf);
5497 tok->type = TOK_NUMBER;
5500 Preproc nasmpp = {
5501 pp_reset,
5502 pp_getline,
5503 pp_cleanup