insns.dat: unbreak test/imm64.bin
[nasm/avx512.git] / preproc.c
blobd75b58eb339f75214c1f0f8dba16b9cbdf8fd4bf
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 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 MMacro MMacro;
86 typedef struct MMacroInvocation MMacroInvocation;
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 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
125 * run.
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
133 struct MMacro {
134 MMacro *next;
135 MMacroInvocation *prev; /* previous invocation */
136 char *name;
137 int nparam_min, nparam_max;
138 bool casesense;
139 bool plus; /* is the last parameter greedy? */
140 bool nolist; /* is this macro listing-inhibited? */
141 int64_t in_progress; /* is this macro currently being expanded? */
142 int32_t max_depth; /* maximum number of recursive expansions allowed */
143 Token *dlist; /* All defaults as one list */
144 Token **defaults; /* Parameter default pointers */
145 int ndefs; /* number of default parameters */
146 Line *expansion;
148 MMacro *next_active;
149 MMacro *rep_nest; /* used for nesting %rep */
150 Token **params; /* actual parameters */
151 Token *iline; /* invocation line */
152 unsigned int nparam, rotate;
153 int *paramlen;
154 uint64_t unique;
155 int lineno; /* Current line number on expansion */
156 uint64_t condcnt; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation {
164 MMacroInvocation *prev; /* previous invocation */
165 Token **params; /* actual parameters */
166 Token *iline; /* invocation line */
167 unsigned int nparam, rotate;
168 int *paramlen;
169 uint64_t unique;
170 uint64_t condcnt;
175 * The context stack is composed of a linked list of these.
177 struct Context {
178 Context *next;
179 char *name;
180 struct hash_table localmac;
181 uint32_t number;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
196 * TOK_SMAC_PARAM+1.
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
203 enum pp_token_type {
204 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
205 TOK_PREPROC_ID, TOK_STRING,
206 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
207 TOK_INTERNAL_STRING,
208 TOK_PREPROC_Q, TOK_PREPROC_QQ,
209 TOK_PASTE, /* %+ */
210 TOK_INDIRECT, /* %[...] */
211 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
215 struct Token {
216 Token *next;
217 char *text;
218 union {
219 SMacro *mac; /* associated macro for TOK_SMAC_END */
220 size_t len; /* scratch length field */
221 } a; /* Auxiliary data */
222 enum pp_token_type type;
226 * Multi-line macro definitions are stored as a linked list of
227 * these, which is essentially a container to allow several linked
228 * lists of Tokens.
230 * Note that in this module, linked lists are treated as stacks
231 * wherever possible. For this reason, Lines are _pushed_ on to the
232 * `expansion' field in MMacro structures, so that the linked list,
233 * if walked, would give the macro lines in reverse order; this
234 * means that we can walk the list when expanding a macro, and thus
235 * push the lines on to the `expansion' field in _istk_ in reverse
236 * order (so that when popped back off they are in the right
237 * order). It may seem cockeyed, and it relies on my design having
238 * an even number of steps in, but it works...
240 * Some of these structures, rather than being actual lines, are
241 * markers delimiting the end of the expansion of a given macro.
242 * This is for use in the cycle-tracking and %rep-handling code.
243 * Such structures have `finishes' non-NULL, and `first' NULL. All
244 * others have `finishes' NULL, but `first' may still be NULL if
245 * the line is blank.
247 struct Line {
248 Line *next;
249 MMacro *finishes;
250 Token *first;
254 * To handle an arbitrary level of file inclusion, we maintain a
255 * stack (ie linked list) of these things.
257 struct Include {
258 Include *next;
259 FILE *fp;
260 Cond *conds;
261 Line *expansion;
262 char *fname;
263 int lineno, lineinc;
264 MMacro *mstk; /* stack of active macros/reps */
268 * Include search path. This is simply a list of strings which get
269 * prepended, in turn, to the name of an include file, in an
270 * attempt to find the file if it's not in the current directory.
272 struct IncPath {
273 IncPath *next;
274 char *path;
278 * Conditional assembly: we maintain a separate stack of these for
279 * each level of file inclusion. (The only reason we keep the
280 * stacks separate is to ensure that a stray `%endif' in a file
281 * included from within the true branch of a `%if' won't terminate
282 * it and cause confusion: instead, rightly, it'll cause an error.)
284 struct Cond {
285 Cond *next;
286 int state;
288 enum {
290 * These states are for use just after %if or %elif: IF_TRUE
291 * means the condition has evaluated to truth so we are
292 * currently emitting, whereas IF_FALSE means we are not
293 * currently emitting but will start doing so if a %else comes
294 * up. In these states, all directives are admissible: %elif,
295 * %else and %endif. (And of course %if.)
297 COND_IF_TRUE, COND_IF_FALSE,
299 * These states come up after a %else: ELSE_TRUE means we're
300 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
301 * any %elif or %else will cause an error.
303 COND_ELSE_TRUE, COND_ELSE_FALSE,
305 * These states mean that we're not emitting now, and also that
306 * nothing until %endif will be emitted at all. COND_DONE is
307 * used when we've had our moment of emission
308 * and have now started seeing %elifs. COND_NEVER is used when
309 * the condition construct in question is contained within a
310 * non-emitting branch of a larger condition construct,
311 * or if there is an error.
313 COND_DONE, COND_NEVER
315 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
318 * These defines are used as the possible return values for do_directive
320 #define NO_DIRECTIVE_FOUND 0
321 #define DIRECTIVE_FOUND 1
324 * This define sets the upper limit for smacro and recursive mmacro
325 * expansions
327 #define DEADMAN_LIMIT (1 << 20)
330 * Condition codes. Note that we use c_ prefix not C_ because C_ is
331 * used in nasm.h for the "real" condition codes. At _this_ level,
332 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
333 * ones, so we need a different enum...
335 static const char * const conditions[] = {
336 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
337 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
338 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
340 enum pp_conds {
341 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
342 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
343 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
344 c_none = -1
346 static const enum pp_conds inverse_ccs[] = {
347 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
348 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,
349 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
353 * Directive names.
355 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
356 static int is_condition(enum preproc_token arg)
358 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
361 /* For TASM compatibility we need to be able to recognise TASM compatible
362 * conditional compilation directives. Using the NASM pre-processor does
363 * not work, so we look for them specifically from the following list and
364 * then jam in the equivalent NASM directive into the input stream.
367 enum {
368 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
369 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
372 static const char * const tasm_directives[] = {
373 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
374 "ifndef", "include", "local"
377 static int StackSize = 4;
378 static char *StackPointer = "ebp";
379 static int ArgOffset = 8;
380 static int LocalOffset = 0;
382 static Context *cstk;
383 static Include *istk;
384 static IncPath *ipath = NULL;
386 static int pass; /* HACK: pass 0 = generate dependencies only */
387 static StrList **dephead, **deptail; /* Dependency list */
389 static uint64_t unique; /* unique identifier numbers */
391 static Line *predef = NULL;
392 static bool do_predef;
394 static ListGen *list;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro *defining;
412 static uint64_t nested_mac_count;
413 static uint64_t nested_rep_count;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t *stdmacpos;
427 * The extra standard macros that come from the object format, if
428 * any.
430 static macros_t *extrastdmac = NULL;
431 static bool any_extrastdmac;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token *freeTokens = NULL;
438 struct Blocks {
439 Blocks *next;
440 void *chunk;
443 static Blocks blocks = { NULL, NULL };
446 * Forward declarations.
448 static Token *expand_mmac_params(Token * tline);
449 static Token *expand_smacro(Token * tline);
450 static Token *expand_id(Token * tline);
451 static Context *get_ctx(const char *name, const char **namep,
452 bool all_contexts);
453 static void make_tok_num(Token * tok, int64_t val);
454 static void error(int severity, const char *fmt, ...);
455 static void error_precond(int severity, const char *fmt, ...);
456 static void *new_Block(size_t size);
457 static void delete_Blocks(void);
458 static Token *new_Token(Token * next, enum pp_token_type type,
459 const char *text, int txtlen);
460 static Token *delete_Token(Token * t);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * nasm_unquote with error if the string contains NUL characters.
472 * If the string contains NUL characters, issue an error and return
473 * the C len, i.e. truncate at the NUL.
475 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
477 size_t len = nasm_unquote(qstr, NULL);
478 size_t clen = strlen(qstr);
480 if (len != clen)
481 error(ERR_NONFATAL, "NUL character in `%s' directive",
482 pp_directives[directive]);
484 return clen;
488 * Handle TASM specific directives, which do not contain a % in
489 * front of them. We do it here because I could not find any other
490 * place to do it for the moment, and it is a hack (ideally it would
491 * be nice to be able to use the NASM pre-processor to do it).
493 static char *check_tasm_directive(char *line)
495 int32_t i, j, k, m, len;
496 char *p, *q, *oldline, oldchar;
498 p = nasm_skip_spaces(line);
500 /* Binary search for the directive name */
501 i = -1;
502 j = ARRAY_SIZE(tasm_directives);
503 q = nasm_skip_word(p);
504 len = q - p;
505 if (len) {
506 oldchar = p[len];
507 p[len] = 0;
508 while (j - i > 1) {
509 k = (j + i) / 2;
510 m = nasm_stricmp(p, tasm_directives[k]);
511 if (m == 0) {
512 /* We have found a directive, so jam a % in front of it
513 * so that NASM will then recognise it as one if it's own.
515 p[len] = oldchar;
516 len = strlen(p);
517 oldline = line;
518 line = nasm_malloc(len + 2);
519 line[0] = '%';
520 if (k == TM_IFDIFI) {
522 * NASM does not recognise IFDIFI, so we convert
523 * it to %if 0. This is not used in NASM
524 * compatible code, but does need to parse for the
525 * TASM macro package.
527 strcpy(line + 1, "if 0");
528 } else {
529 memcpy(line + 1, p, len + 1);
531 nasm_free(oldline);
532 return line;
533 } else if (m < 0) {
534 j = k;
535 } else
536 i = k;
538 p[len] = oldchar;
540 return line;
544 * The pre-preprocessing stage... This function translates line
545 * number indications as they emerge from GNU cpp (`# lineno "file"
546 * flags') into NASM preprocessor line number indications (`%line
547 * lineno file').
549 static char *prepreproc(char *line)
551 int lineno, fnlen;
552 char *fname, *oldline;
554 if (line[0] == '#' && line[1] == ' ') {
555 oldline = line;
556 fname = oldline + 2;
557 lineno = atoi(fname);
558 fname += strspn(fname, "0123456789 ");
559 if (*fname == '"')
560 fname++;
561 fnlen = strcspn(fname, "\"");
562 line = nasm_malloc(20 + fnlen);
563 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
564 nasm_free(oldline);
566 if (tasm_compatible_mode)
567 return check_tasm_directive(line);
568 return line;
572 * Free a linked list of tokens.
574 static void free_tlist(Token * list)
576 while (list)
577 list = delete_Token(list);
581 * Free a linked list of lines.
583 static void free_llist(Line * list)
585 Line *l, *tmp;
586 list_for_each_safe(l, tmp, list) {
587 free_tlist(l->first);
588 nasm_free(l);
593 * Free an MMacro
595 static void free_mmacro(MMacro * m)
597 nasm_free(m->name);
598 free_tlist(m->dlist);
599 nasm_free(m->defaults);
600 free_llist(m->expansion);
601 nasm_free(m);
605 * Free all currently defined macros, and free the hash tables
607 static void free_smacro_table(struct hash_table *smt)
609 SMacro *s, *tmp;
610 const char *key;
611 struct hash_tbl_node *it = NULL;
613 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
614 nasm_free((void *)key);
615 list_for_each_safe(s, tmp, s) {
616 nasm_free(s->name);
617 free_tlist(s->expansion);
618 nasm_free(s);
621 hash_free(smt);
624 static void free_mmacro_table(struct hash_table *mmt)
626 MMacro *m, *tmp;
627 const char *key;
628 struct hash_tbl_node *it = NULL;
630 it = NULL;
631 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
632 nasm_free((void *)key);
633 list_for_each_safe(m ,tmp, m)
634 free_mmacro(m);
636 hash_free(mmt);
639 static void free_macros(void)
641 free_smacro_table(&smacros);
642 free_mmacro_table(&mmacros);
646 * Initialize the hash tables
648 static void init_macros(void)
650 hash_init(&smacros, HASH_LARGE);
651 hash_init(&mmacros, HASH_LARGE);
655 * Pop the context stack.
657 static void ctx_pop(void)
659 Context *c = cstk;
661 cstk = cstk->next;
662 free_smacro_table(&c->localmac);
663 nasm_free(c->name);
664 nasm_free(c);
668 * Search for a key in the hash index; adding it if necessary
669 * (in which case we initialize the data pointer to NULL.)
671 static void **
672 hash_findi_add(struct hash_table *hash, const char *str)
674 struct hash_insert hi;
675 void **r;
676 char *strx;
678 r = hash_findi(hash, str, &hi);
679 if (r)
680 return r;
682 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
683 return hash_add(&hi, strx, NULL);
687 * Like hash_findi, but returns the data element rather than a pointer
688 * to it. Used only when not adding a new element, hence no third
689 * argument.
691 static void *
692 hash_findix(struct hash_table *hash, const char *str)
694 void **p;
696 p = hash_findi(hash, str, NULL);
697 return p ? *p : NULL;
701 * read line from standart macros set,
702 * if there no more left -- return NULL
704 static char *line_from_stdmac(void)
706 unsigned char c;
707 const unsigned char *p = stdmacpos;
708 char *line, *q;
709 size_t len = 0;
711 if (!stdmacpos)
712 return NULL;
714 while ((c = *p++)) {
715 if (c >= 0x80)
716 len += pp_directives_len[c - 0x80] + 1;
717 else
718 len++;
721 line = nasm_malloc(len + 1);
722 q = line;
723 while ((c = *stdmacpos++)) {
724 if (c >= 0x80) {
725 memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
726 q += pp_directives_len[c - 0x80];
727 *q++ = ' ';
728 } else {
729 *q++ = c;
732 stdmacpos = p;
733 *q = '\0';
735 if (!*stdmacpos) {
736 /* This was the last of the standard macro chain... */
737 stdmacpos = NULL;
738 if (any_extrastdmac) {
739 stdmacpos = extrastdmac;
740 any_extrastdmac = false;
741 } else if (do_predef) {
742 Line *pd, *l;
743 Token *head, **tail, *t;
746 * Nasty hack: here we push the contents of
747 * `predef' on to the top-level expansion stack,
748 * since this is the most convenient way to
749 * implement the pre-include and pre-define
750 * features.
752 list_for_each(pd, predef) {
753 head = NULL;
754 tail = &head;
755 list_for_each(t, pd->first) {
756 *tail = new_Token(NULL, t->type, t->text, 0);
757 tail = &(*tail)->next;
760 l = nasm_malloc(sizeof(Line));
761 l->next = istk->expansion;
762 l->first = head;
763 l->finishes = NULL;
765 istk->expansion = l;
767 do_predef = false;
771 return line;
774 #define BUF_DELTA 512
776 * Read a line from the top file in istk, handling multiple CR/LFs
777 * at the end of the line read, and handling spurious ^Zs. Will
778 * return lines from the standard macro set if this has not already
779 * been done.
781 static char *read_line(void)
783 char *buffer, *p, *q;
784 int bufsize, continued_count;
787 * standart macros set (predefined) goes first
789 p = line_from_stdmac();
790 if (p)
791 return p;
794 * regular read from a file
796 bufsize = BUF_DELTA;
797 buffer = nasm_malloc(BUF_DELTA);
798 p = buffer;
799 continued_count = 0;
800 while (1) {
801 q = fgets(p, bufsize - (p - buffer), istk->fp);
802 if (!q)
803 break;
804 p += strlen(p);
805 if (p > buffer && p[-1] == '\n') {
807 * Convert backslash-CRLF line continuation sequences into
808 * nothing at all (for DOS and Windows)
810 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
811 p -= 3;
812 *p = 0;
813 continued_count++;
816 * Also convert backslash-LF line continuation sequences into
817 * nothing at all (for Unix)
819 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
820 p -= 2;
821 *p = 0;
822 continued_count++;
823 } else {
824 break;
827 if (p - buffer > bufsize - 10) {
828 int32_t offset = p - buffer;
829 bufsize += BUF_DELTA;
830 buffer = nasm_realloc(buffer, bufsize);
831 p = buffer + offset; /* prevent stale-pointer problems */
835 if (!q && p == buffer) {
836 nasm_free(buffer);
837 return NULL;
840 src_set_linnum(src_get_linnum() + istk->lineinc +
841 (continued_count * istk->lineinc));
844 * Play safe: remove CRs as well as LFs, if any of either are
845 * present at the end of the line.
847 while (--p >= buffer && (*p == '\n' || *p == '\r'))
848 *p = '\0';
851 * Handle spurious ^Z, which may be inserted into source files
852 * by some file transfer utilities.
854 buffer[strcspn(buffer, "\032")] = '\0';
856 list->line(LIST_READ, buffer);
858 return buffer;
862 * Tokenize a line of text. This is a very simple process since we
863 * don't need to parse the value out of e.g. numeric tokens: we
864 * simply split one string into many.
866 static Token *tokenize(char *line)
868 char c, *p = line;
869 enum pp_token_type type;
870 Token *list = NULL;
871 Token *t, **tail = &list;
873 while (*line) {
874 p = line;
875 if (*p == '%') {
876 p++;
877 if (*p == '+' && !nasm_isdigit(p[1])) {
878 p++;
879 type = TOK_PASTE;
880 } else if (nasm_isdigit(*p) ||
881 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
882 do {
883 p++;
885 while (nasm_isdigit(*p));
886 type = TOK_PREPROC_ID;
887 } else if (*p == '{') {
888 p++;
889 while (*p && *p != '}') {
890 p[-1] = *p;
891 p++;
893 p[-1] = '\0';
894 if (*p)
895 p++;
896 type = TOK_PREPROC_ID;
897 } else if (*p == '[') {
898 int lvl = 1;
899 line += 2; /* Skip the leading %[ */
900 p++;
901 while (lvl && (c = *p++)) {
902 switch (c) {
903 case ']':
904 lvl--;
905 break;
906 case '%':
907 if (*p == '[')
908 lvl++;
909 break;
910 case '\'':
911 case '\"':
912 case '`':
913 p = nasm_skip_string(p - 1) + 1;
914 break;
915 default:
916 break;
919 p--;
920 if (*p)
921 *p++ = '\0';
922 if (lvl)
923 error(ERR_NONFATAL, "unterminated %[ construct");
924 type = TOK_INDIRECT;
925 } else if (*p == '?') {
926 type = TOK_PREPROC_Q; /* %? */
927 p++;
928 if (*p == '?') {
929 type = TOK_PREPROC_QQ; /* %?? */
930 p++;
932 } else if (*p == '!') {
933 type = TOK_PREPROC_ID;
934 p++;
935 if (isidchar(*p)) {
936 do {
937 p++;
939 while (isidchar(*p));
940 } else if (*p == '\'' || *p == '\"' || *p == '`') {
941 p = nasm_skip_string(p);
942 if (*p)
943 p++;
944 else
945 error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
946 } else {
947 /* %! without string or identifier */
948 type = TOK_OTHER; /* Legacy behavior... */
950 } else if (isidchar(*p) ||
951 ((*p == '!' || *p == '%' || *p == '$') &&
952 isidchar(p[1]))) {
953 do {
954 p++;
956 while (isidchar(*p));
957 type = TOK_PREPROC_ID;
958 } else {
959 type = TOK_OTHER;
960 if (*p == '%')
961 p++;
963 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
964 type = TOK_ID;
965 p++;
966 while (*p && isidchar(*p))
967 p++;
968 } else if (*p == '\'' || *p == '"' || *p == '`') {
970 * A string token.
972 type = TOK_STRING;
973 p = nasm_skip_string(p);
975 if (*p) {
976 p++;
977 } else {
978 error(ERR_WARNING|ERR_PASS1, "unterminated string");
979 /* Handling unterminated strings by UNV */
980 /* type = -1; */
982 } else if (p[0] == '$' && p[1] == '$') {
983 type = TOK_OTHER; /* TOKEN_BASE */
984 p += 2;
985 } else if (isnumstart(*p)) {
986 bool is_hex = false;
987 bool is_float = false;
988 bool has_e = false;
989 char c, *r;
992 * A numeric token.
995 if (*p == '$') {
996 p++;
997 is_hex = true;
1000 for (;;) {
1001 c = *p++;
1003 if (!is_hex && (c == 'e' || c == 'E')) {
1004 has_e = true;
1005 if (*p == '+' || *p == '-') {
1007 * e can only be followed by +/- if it is either a
1008 * prefixed hex number or a floating-point number
1010 p++;
1011 is_float = true;
1013 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
1014 is_hex = true;
1015 } else if (c == 'P' || c == 'p') {
1016 is_float = true;
1017 if (*p == '+' || *p == '-')
1018 p++;
1019 } else if (isnumchar(c) || c == '_')
1020 ; /* just advance */
1021 else if (c == '.') {
1023 * we need to deal with consequences of the legacy
1024 * parser, like "1.nolist" being two tokens
1025 * (TOK_NUMBER, TOK_ID) here; at least give it
1026 * a shot for now. In the future, we probably need
1027 * a flex-based scanner with proper pattern matching
1028 * to do it as well as it can be done. Nothing in
1029 * the world is going to help the person who wants
1030 * 0x123.p16 interpreted as two tokens, though.
1032 r = p;
1033 while (*r == '_')
1034 r++;
1036 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
1037 (!is_hex && (*r == 'e' || *r == 'E')) ||
1038 (*r == 'p' || *r == 'P')) {
1039 p = r;
1040 is_float = true;
1041 } else
1042 break; /* Terminate the token */
1043 } else
1044 break;
1046 p--; /* Point to first character beyond number */
1048 if (p == line+1 && *line == '$') {
1049 type = TOK_OTHER; /* TOKEN_HERE */
1050 } else {
1051 if (has_e && !is_hex) {
1052 /* 1e13 is floating-point, but 1e13h is not */
1053 is_float = true;
1056 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1058 } else if (nasm_isspace(*p)) {
1059 type = TOK_WHITESPACE;
1060 p = nasm_skip_spaces(p);
1062 * Whitespace just before end-of-line is discarded by
1063 * pretending it's a comment; whitespace just before a
1064 * comment gets lumped into the comment.
1066 if (!*p || *p == ';') {
1067 type = TOK_COMMENT;
1068 while (*p)
1069 p++;
1071 } else if (*p == ';') {
1072 type = TOK_COMMENT;
1073 while (*p)
1074 p++;
1075 } else {
1077 * Anything else is an operator of some kind. We check
1078 * for all the double-character operators (>>, <<, //,
1079 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1080 * else is a single-character operator.
1082 type = TOK_OTHER;
1083 if ((p[0] == '>' && p[1] == '>') ||
1084 (p[0] == '<' && p[1] == '<') ||
1085 (p[0] == '/' && p[1] == '/') ||
1086 (p[0] == '<' && p[1] == '=') ||
1087 (p[0] == '>' && p[1] == '=') ||
1088 (p[0] == '=' && p[1] == '=') ||
1089 (p[0] == '!' && p[1] == '=') ||
1090 (p[0] == '<' && p[1] == '>') ||
1091 (p[0] == '&' && p[1] == '&') ||
1092 (p[0] == '|' && p[1] == '|') ||
1093 (p[0] == '^' && p[1] == '^')) {
1094 p++;
1096 p++;
1099 /* Handling unterminated string by UNV */
1100 /*if (type == -1)
1102 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1103 t->text[p-line] = *line;
1104 tail = &t->next;
1106 else */
1107 if (type != TOK_COMMENT) {
1108 *tail = t = new_Token(NULL, type, line, p - line);
1109 tail = &t->next;
1111 line = p;
1113 return list;
1117 * this function allocates a new managed block of memory and
1118 * returns a pointer to the block. The managed blocks are
1119 * deleted only all at once by the delete_Blocks function.
1121 static void *new_Block(size_t size)
1123 Blocks *b = &blocks;
1125 /* first, get to the end of the linked list */
1126 while (b->next)
1127 b = b->next;
1128 /* now allocate the requested chunk */
1129 b->chunk = nasm_malloc(size);
1131 /* now allocate a new block for the next request */
1132 b->next = nasm_malloc(sizeof(Blocks));
1133 /* and initialize the contents of the new block */
1134 b->next->next = NULL;
1135 b->next->chunk = NULL;
1136 return b->chunk;
1140 * this function deletes all managed blocks of memory
1142 static void delete_Blocks(void)
1144 Blocks *a, *b = &blocks;
1147 * keep in mind that the first block, pointed to by blocks
1148 * is a static and not dynamically allocated, so we don't
1149 * free it.
1151 while (b) {
1152 if (b->chunk)
1153 nasm_free(b->chunk);
1154 a = b;
1155 b = b->next;
1156 if (a != &blocks)
1157 nasm_free(a);
1162 * this function creates a new Token and passes a pointer to it
1163 * back to the caller. It sets the type and text elements, and
1164 * also the a.mac and next elements to NULL.
1166 static Token *new_Token(Token * next, enum pp_token_type type,
1167 const char *text, int txtlen)
1169 Token *t;
1170 int i;
1172 if (!freeTokens) {
1173 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1174 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1175 freeTokens[i].next = &freeTokens[i + 1];
1176 freeTokens[i].next = NULL;
1178 t = freeTokens;
1179 freeTokens = t->next;
1180 t->next = next;
1181 t->a.mac = NULL;
1182 t->type = type;
1183 if (type == TOK_WHITESPACE || !text) {
1184 t->text = NULL;
1185 } else {
1186 if (txtlen == 0)
1187 txtlen = strlen(text);
1188 t->text = nasm_malloc(txtlen+1);
1189 memcpy(t->text, text, txtlen);
1190 t->text[txtlen] = '\0';
1192 return t;
1195 static Token *delete_Token(Token * t)
1197 Token *next = t->next;
1198 nasm_free(t->text);
1199 t->next = freeTokens;
1200 freeTokens = t;
1201 return next;
1205 * Convert a line of tokens back into text.
1206 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1207 * will be transformed into ..@ctxnum.xxx
1209 static char *detoken(Token * tlist, bool expand_locals)
1211 Token *t;
1212 char *line, *p;
1213 const char *q;
1214 int len = 0;
1216 list_for_each(t, tlist) {
1217 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1218 char *v;
1219 char *q = t->text;
1221 v = t->text + 2;
1222 if (*v == '\'' || *v == '\"' || *v == '`') {
1223 size_t len = nasm_unquote(v, NULL);
1224 size_t clen = strlen(v);
1226 if (len != clen) {
1227 error(ERR_NONFATAL | ERR_PASS1,
1228 "NUL character in %! string");
1229 v = NULL;
1233 if (v) {
1234 char *p = getenv(v);
1235 if (!p) {
1236 error(ERR_NONFATAL | ERR_PASS1,
1237 "nonexistent environment variable `%s'", v);
1238 p = "";
1240 t->text = nasm_strdup(p);
1242 nasm_free(q);
1245 /* Expand local macros here and not during preprocessing */
1246 if (expand_locals &&
1247 t->type == TOK_PREPROC_ID && t->text &&
1248 t->text[0] == '%' && t->text[1] == '$') {
1249 const char *q;
1250 char *p;
1251 Context *ctx = get_ctx(t->text, &q, false);
1252 if (ctx) {
1253 char buffer[40];
1254 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1255 p = nasm_strcat(buffer, q);
1256 nasm_free(t->text);
1257 t->text = p;
1260 if (t->type == TOK_WHITESPACE)
1261 len++;
1262 else if (t->text)
1263 len += strlen(t->text);
1266 p = line = nasm_malloc(len + 1);
1268 list_for_each(t, tlist) {
1269 if (t->type == TOK_WHITESPACE) {
1270 *p++ = ' ';
1271 } else if (t->text) {
1272 q = t->text;
1273 while (*q)
1274 *p++ = *q++;
1277 *p = '\0';
1279 return line;
1283 * A scanner, suitable for use by the expression evaluator, which
1284 * operates on a line of Tokens. Expects a pointer to a pointer to
1285 * the first token in the line to be passed in as its private_data
1286 * field.
1288 * FIX: This really needs to be unified with stdscan.
1290 static int ppscan(void *private_data, struct tokenval *tokval)
1292 Token **tlineptr = private_data;
1293 Token *tline;
1294 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1296 do {
1297 tline = *tlineptr;
1298 *tlineptr = tline ? tline->next : NULL;
1299 } while (tline && (tline->type == TOK_WHITESPACE ||
1300 tline->type == TOK_COMMENT));
1302 if (!tline)
1303 return tokval->t_type = TOKEN_EOS;
1305 tokval->t_charptr = tline->text;
1307 if (tline->text[0] == '$' && !tline->text[1])
1308 return tokval->t_type = TOKEN_HERE;
1309 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1310 return tokval->t_type = TOKEN_BASE;
1312 if (tline->type == TOK_ID) {
1313 p = tokval->t_charptr = tline->text;
1314 if (p[0] == '$') {
1315 tokval->t_charptr++;
1316 return tokval->t_type = TOKEN_ID;
1319 for (r = p, s = ourcopy; *r; r++) {
1320 if (r >= p+MAX_KEYWORD)
1321 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1322 *s++ = nasm_tolower(*r);
1324 *s = '\0';
1325 /* right, so we have an identifier sitting in temp storage. now,
1326 * is it actually a register or instruction name, or what? */
1327 return nasm_token_hash(ourcopy, tokval);
1330 if (tline->type == TOK_NUMBER) {
1331 bool rn_error;
1332 tokval->t_integer = readnum(tline->text, &rn_error);
1333 tokval->t_charptr = tline->text;
1334 if (rn_error)
1335 return tokval->t_type = TOKEN_ERRNUM;
1336 else
1337 return tokval->t_type = TOKEN_NUM;
1340 if (tline->type == TOK_FLOAT) {
1341 return tokval->t_type = TOKEN_FLOAT;
1344 if (tline->type == TOK_STRING) {
1345 char bq, *ep;
1347 bq = tline->text[0];
1348 tokval->t_charptr = tline->text;
1349 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1351 if (ep[0] != bq || ep[1] != '\0')
1352 return tokval->t_type = TOKEN_ERRSTR;
1353 else
1354 return tokval->t_type = TOKEN_STR;
1357 if (tline->type == TOK_OTHER) {
1358 if (!strcmp(tline->text, "<<"))
1359 return tokval->t_type = TOKEN_SHL;
1360 if (!strcmp(tline->text, ">>"))
1361 return tokval->t_type = TOKEN_SHR;
1362 if (!strcmp(tline->text, "//"))
1363 return tokval->t_type = TOKEN_SDIV;
1364 if (!strcmp(tline->text, "%%"))
1365 return tokval->t_type = TOKEN_SMOD;
1366 if (!strcmp(tline->text, "=="))
1367 return tokval->t_type = TOKEN_EQ;
1368 if (!strcmp(tline->text, "<>"))
1369 return tokval->t_type = TOKEN_NE;
1370 if (!strcmp(tline->text, "!="))
1371 return tokval->t_type = TOKEN_NE;
1372 if (!strcmp(tline->text, "<="))
1373 return tokval->t_type = TOKEN_LE;
1374 if (!strcmp(tline->text, ">="))
1375 return tokval->t_type = TOKEN_GE;
1376 if (!strcmp(tline->text, "&&"))
1377 return tokval->t_type = TOKEN_DBL_AND;
1378 if (!strcmp(tline->text, "^^"))
1379 return tokval->t_type = TOKEN_DBL_XOR;
1380 if (!strcmp(tline->text, "||"))
1381 return tokval->t_type = TOKEN_DBL_OR;
1385 * We have no other options: just return the first character of
1386 * the token text.
1388 return tokval->t_type = tline->text[0];
1392 * Compare a string to the name of an existing macro; this is a
1393 * simple wrapper which calls either strcmp or nasm_stricmp
1394 * depending on the value of the `casesense' parameter.
1396 static int mstrcmp(const char *p, const char *q, bool casesense)
1398 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1402 * Compare a string to the name of an existing macro; this is a
1403 * simple wrapper which calls either strcmp or nasm_stricmp
1404 * depending on the value of the `casesense' parameter.
1406 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1408 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1412 * Return the Context structure associated with a %$ token. Return
1413 * NULL, having _already_ reported an error condition, if the
1414 * context stack isn't deep enough for the supplied number of $
1415 * signs.
1416 * If all_contexts == true, contexts that enclose current are
1417 * also scanned for such smacro, until it is found; if not -
1418 * only the context that directly results from the number of $'s
1419 * in variable's name.
1421 * If "namep" is non-NULL, set it to the pointer to the macro name
1422 * tail, i.e. the part beyond %$...
1424 static Context *get_ctx(const char *name, const char **namep,
1425 bool all_contexts)
1427 Context *ctx;
1428 SMacro *m;
1429 int i;
1431 if (namep)
1432 *namep = name;
1434 if (!name || name[0] != '%' || name[1] != '$')
1435 return NULL;
1437 if (!cstk) {
1438 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1439 return NULL;
1442 name += 2;
1443 ctx = cstk;
1444 i = 0;
1445 while (ctx && *name == '$') {
1446 name++;
1447 i++;
1448 ctx = ctx->next;
1450 if (!ctx) {
1451 error(ERR_NONFATAL, "`%s': context stack is only"
1452 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1453 return NULL;
1456 if (namep)
1457 *namep = name;
1459 if (!all_contexts)
1460 return ctx;
1462 do {
1463 /* Search for this smacro in found context */
1464 m = hash_findix(&ctx->localmac, name);
1465 while (m) {
1466 if (!mstrcmp(m->name, name, m->casesense))
1467 return ctx;
1468 m = m->next;
1470 ctx = ctx->next;
1472 while (ctx);
1473 return NULL;
1477 * Check to see if a file is already in a string list
1479 static bool in_list(const StrList *list, const char *str)
1481 while (list) {
1482 if (!strcmp(list->str, str))
1483 return true;
1484 list = list->next;
1486 return false;
1490 * Open an include file. This routine must always return a valid
1491 * file pointer if it returns - it's responsible for throwing an
1492 * ERR_FATAL and bombing out completely if not. It should also try
1493 * the include path one by one until it finds the file or reaches
1494 * the end of the path.
1496 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1497 bool missing_ok)
1499 FILE *fp;
1500 char *prefix = "";
1501 IncPath *ip = ipath;
1502 int len = strlen(file);
1503 size_t prefix_len = 0;
1504 StrList *sl;
1506 while (1) {
1507 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1508 memcpy(sl->str, prefix, prefix_len);
1509 memcpy(sl->str+prefix_len, file, len+1);
1510 fp = fopen(sl->str, "r");
1511 if (fp && dhead && !in_list(*dhead, sl->str)) {
1512 sl->next = NULL;
1513 **dtail = sl;
1514 *dtail = &sl->next;
1515 } else {
1516 nasm_free(sl);
1518 if (fp)
1519 return fp;
1520 if (!ip) {
1521 if (!missing_ok)
1522 break;
1523 prefix = NULL;
1524 } else {
1525 prefix = ip->path;
1526 ip = ip->next;
1528 if (prefix) {
1529 prefix_len = strlen(prefix);
1530 } else {
1531 /* -MG given and file not found */
1532 if (dhead && !in_list(*dhead, file)) {
1533 sl = nasm_malloc(len+1+sizeof sl->next);
1534 sl->next = NULL;
1535 strcpy(sl->str, file);
1536 **dtail = sl;
1537 *dtail = &sl->next;
1539 return NULL;
1543 error(ERR_FATAL, "unable to open include file `%s'", file);
1544 return NULL;
1548 * Determine if we should warn on defining a single-line macro of
1549 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1550 * return true if _any_ single-line macro of that name is defined.
1551 * Otherwise, will return true if a single-line macro with either
1552 * `nparam' or no parameters is defined.
1554 * If a macro with precisely the right number of parameters is
1555 * defined, or nparam is -1, the address of the definition structure
1556 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1557 * is NULL, no action will be taken regarding its contents, and no
1558 * error will occur.
1560 * Note that this is also called with nparam zero to resolve
1561 * `ifdef'.
1563 * If you already know which context macro belongs to, you can pass
1564 * the context pointer as first parameter; if you won't but name begins
1565 * with %$ the context will be automatically computed. If all_contexts
1566 * is true, macro will be searched in outer contexts as well.
1568 static bool
1569 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1570 bool nocase)
1572 struct hash_table *smtbl;
1573 SMacro *m;
1575 if (ctx) {
1576 smtbl = &ctx->localmac;
1577 } else if (name[0] == '%' && name[1] == '$') {
1578 if (cstk)
1579 ctx = get_ctx(name, &name, false);
1580 if (!ctx)
1581 return false; /* got to return _something_ */
1582 smtbl = &ctx->localmac;
1583 } else {
1584 smtbl = &smacros;
1586 m = (SMacro *) hash_findix(smtbl, name);
1588 while (m) {
1589 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1590 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1591 if (defn) {
1592 if (nparam == (int) m->nparam || nparam == -1)
1593 *defn = m;
1594 else
1595 *defn = NULL;
1597 return true;
1599 m = m->next;
1602 return false;
1606 * Count and mark off the parameters in a multi-line macro call.
1607 * This is called both from within the multi-line macro expansion
1608 * code, and also to mark off the default parameters when provided
1609 * in a %macro definition line.
1611 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1613 int paramsize, brace;
1615 *nparam = paramsize = 0;
1616 *params = NULL;
1617 while (t) {
1618 /* +1: we need space for the final NULL */
1619 if (*nparam+1 >= paramsize) {
1620 paramsize += PARAM_DELTA;
1621 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1623 skip_white_(t);
1624 brace = false;
1625 if (tok_is_(t, "{"))
1626 brace = true;
1627 (*params)[(*nparam)++] = t;
1628 while (tok_isnt_(t, brace ? "}" : ","))
1629 t = t->next;
1630 if (t) { /* got a comma/brace */
1631 t = t->next;
1632 if (brace) {
1634 * Now we've found the closing brace, look further
1635 * for the comma.
1637 skip_white_(t);
1638 if (tok_isnt_(t, ",")) {
1639 error(ERR_NONFATAL,
1640 "braces do not enclose all of macro parameter");
1641 while (tok_isnt_(t, ","))
1642 t = t->next;
1644 if (t)
1645 t = t->next; /* eat the comma */
1652 * Determine whether one of the various `if' conditions is true or
1653 * not.
1655 * We must free the tline we get passed.
1657 static bool if_condition(Token * tline, enum preproc_token ct)
1659 enum pp_conditional i = PP_COND(ct);
1660 bool j;
1661 Token *t, *tt, **tptr, *origline;
1662 struct tokenval tokval;
1663 expr *evalresult;
1664 enum pp_token_type needtype;
1665 char *p;
1667 origline = tline;
1669 switch (i) {
1670 case PPC_IFCTX:
1671 j = false; /* have we matched yet? */
1672 while (true) {
1673 skip_white_(tline);
1674 if (!tline)
1675 break;
1676 if (tline->type != TOK_ID) {
1677 error(ERR_NONFATAL,
1678 "`%s' expects context identifiers", pp_directives[ct]);
1679 free_tlist(origline);
1680 return -1;
1682 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1683 j = true;
1684 tline = tline->next;
1686 break;
1688 case PPC_IFDEF:
1689 j = false; /* have we matched yet? */
1690 while (tline) {
1691 skip_white_(tline);
1692 if (!tline || (tline->type != TOK_ID &&
1693 (tline->type != TOK_PREPROC_ID ||
1694 tline->text[1] != '$'))) {
1695 error(ERR_NONFATAL,
1696 "`%s' expects macro identifiers", pp_directives[ct]);
1697 goto fail;
1699 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1700 j = true;
1701 tline = tline->next;
1703 break;
1705 case PPC_IFENV:
1706 tline = expand_smacro(tline);
1707 j = false; /* have we matched yet? */
1708 while (tline) {
1709 skip_white_(tline);
1710 if (!tline || (tline->type != TOK_ID &&
1711 tline->type != TOK_STRING &&
1712 (tline->type != TOK_PREPROC_ID ||
1713 tline->text[1] != '!'))) {
1714 error(ERR_NONFATAL,
1715 "`%s' expects environment variable names",
1716 pp_directives[ct]);
1717 goto fail;
1719 p = tline->text;
1720 if (tline->type == TOK_PREPROC_ID)
1721 p += 2; /* Skip leading %! */
1722 if (*p == '\'' || *p == '\"' || *p == '`')
1723 nasm_unquote_cstr(p, ct);
1724 if (getenv(p))
1725 j = true;
1726 tline = tline->next;
1728 break;
1730 case PPC_IFIDN:
1731 case PPC_IFIDNI:
1732 tline = expand_smacro(tline);
1733 t = tt = tline;
1734 while (tok_isnt_(tt, ","))
1735 tt = tt->next;
1736 if (!tt) {
1737 error(ERR_NONFATAL,
1738 "`%s' expects two comma-separated arguments",
1739 pp_directives[ct]);
1740 goto fail;
1742 tt = tt->next;
1743 j = true; /* assume equality unless proved not */
1744 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1745 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1746 error(ERR_NONFATAL, "`%s': more than one comma on line",
1747 pp_directives[ct]);
1748 goto fail;
1750 if (t->type == TOK_WHITESPACE) {
1751 t = t->next;
1752 continue;
1754 if (tt->type == TOK_WHITESPACE) {
1755 tt = tt->next;
1756 continue;
1758 if (tt->type != t->type) {
1759 j = false; /* found mismatching tokens */
1760 break;
1762 /* When comparing strings, need to unquote them first */
1763 if (t->type == TOK_STRING) {
1764 size_t l1 = nasm_unquote(t->text, NULL);
1765 size_t l2 = nasm_unquote(tt->text, NULL);
1767 if (l1 != l2) {
1768 j = false;
1769 break;
1771 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1772 j = false;
1773 break;
1775 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1776 j = false; /* found mismatching tokens */
1777 break;
1780 t = t->next;
1781 tt = tt->next;
1783 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1784 j = false; /* trailing gunk on one end or other */
1785 break;
1787 case PPC_IFMACRO:
1789 bool found = false;
1790 MMacro searching, *mmac;
1792 skip_white_(tline);
1793 tline = expand_id(tline);
1794 if (!tok_type_(tline, TOK_ID)) {
1795 error(ERR_NONFATAL,
1796 "`%s' expects a macro name", pp_directives[ct]);
1797 goto fail;
1799 searching.name = nasm_strdup(tline->text);
1800 searching.casesense = true;
1801 searching.plus = false;
1802 searching.nolist = false;
1803 searching.in_progress = 0;
1804 searching.max_depth = 0;
1805 searching.rep_nest = NULL;
1806 searching.nparam_min = 0;
1807 searching.nparam_max = INT_MAX;
1808 tline = expand_smacro(tline->next);
1809 skip_white_(tline);
1810 if (!tline) {
1811 } else if (!tok_type_(tline, TOK_NUMBER)) {
1812 error(ERR_NONFATAL,
1813 "`%s' expects a parameter count or nothing",
1814 pp_directives[ct]);
1815 } else {
1816 searching.nparam_min = searching.nparam_max =
1817 readnum(tline->text, &j);
1818 if (j)
1819 error(ERR_NONFATAL,
1820 "unable to parse parameter count `%s'",
1821 tline->text);
1823 if (tline && tok_is_(tline->next, "-")) {
1824 tline = tline->next->next;
1825 if (tok_is_(tline, "*"))
1826 searching.nparam_max = INT_MAX;
1827 else if (!tok_type_(tline, TOK_NUMBER))
1828 error(ERR_NONFATAL,
1829 "`%s' expects a parameter count after `-'",
1830 pp_directives[ct]);
1831 else {
1832 searching.nparam_max = readnum(tline->text, &j);
1833 if (j)
1834 error(ERR_NONFATAL,
1835 "unable to parse parameter count `%s'",
1836 tline->text);
1837 if (searching.nparam_min > searching.nparam_max)
1838 error(ERR_NONFATAL,
1839 "minimum parameter count exceeds maximum");
1842 if (tline && tok_is_(tline->next, "+")) {
1843 tline = tline->next;
1844 searching.plus = true;
1846 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1847 while (mmac) {
1848 if (!strcmp(mmac->name, searching.name) &&
1849 (mmac->nparam_min <= searching.nparam_max
1850 || searching.plus)
1851 && (searching.nparam_min <= mmac->nparam_max
1852 || mmac->plus)) {
1853 found = true;
1854 break;
1856 mmac = mmac->next;
1858 if (tline && tline->next)
1859 error(ERR_WARNING|ERR_PASS1,
1860 "trailing garbage after %%ifmacro ignored");
1861 nasm_free(searching.name);
1862 j = found;
1863 break;
1866 case PPC_IFID:
1867 needtype = TOK_ID;
1868 goto iftype;
1869 case PPC_IFNUM:
1870 needtype = TOK_NUMBER;
1871 goto iftype;
1872 case PPC_IFSTR:
1873 needtype = TOK_STRING;
1874 goto iftype;
1876 iftype:
1877 t = tline = expand_smacro(tline);
1879 while (tok_type_(t, TOK_WHITESPACE) ||
1880 (needtype == TOK_NUMBER &&
1881 tok_type_(t, TOK_OTHER) &&
1882 (t->text[0] == '-' || t->text[0] == '+') &&
1883 !t->text[1]))
1884 t = t->next;
1886 j = tok_type_(t, needtype);
1887 break;
1889 case PPC_IFTOKEN:
1890 t = tline = expand_smacro(tline);
1891 while (tok_type_(t, TOK_WHITESPACE))
1892 t = t->next;
1894 j = false;
1895 if (t) {
1896 t = t->next; /* Skip the actual token */
1897 while (tok_type_(t, TOK_WHITESPACE))
1898 t = t->next;
1899 j = !t; /* Should be nothing left */
1901 break;
1903 case PPC_IFEMPTY:
1904 t = tline = expand_smacro(tline);
1905 while (tok_type_(t, TOK_WHITESPACE))
1906 t = t->next;
1908 j = !t; /* Should be empty */
1909 break;
1911 case PPC_IF:
1912 t = tline = expand_smacro(tline);
1913 tptr = &t;
1914 tokval.t_type = TOKEN_INVALID;
1915 evalresult = evaluate(ppscan, tptr, &tokval,
1916 NULL, pass | CRITICAL, error, NULL);
1917 if (!evalresult)
1918 return -1;
1919 if (tokval.t_type)
1920 error(ERR_WARNING|ERR_PASS1,
1921 "trailing garbage after expression ignored");
1922 if (!is_simple(evalresult)) {
1923 error(ERR_NONFATAL,
1924 "non-constant value given to `%s'", pp_directives[ct]);
1925 goto fail;
1927 j = reloc_value(evalresult) != 0;
1928 break;
1930 default:
1931 error(ERR_FATAL,
1932 "preprocessor directive `%s' not yet implemented",
1933 pp_directives[ct]);
1934 goto fail;
1937 free_tlist(origline);
1938 return j ^ PP_NEGATIVE(ct);
1940 fail:
1941 free_tlist(origline);
1942 return -1;
1946 * Common code for defining an smacro
1948 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1949 int nparam, Token *expansion)
1951 SMacro *smac, **smhead;
1952 struct hash_table *smtbl;
1954 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1955 if (!smac) {
1956 error(ERR_WARNING|ERR_PASS1,
1957 "single-line macro `%s' defined both with and"
1958 " without parameters", mname);
1960 * Some instances of the old code considered this a failure,
1961 * some others didn't. What is the right thing to do here?
1963 free_tlist(expansion);
1964 return false; /* Failure */
1965 } else {
1967 * We're redefining, so we have to take over an
1968 * existing SMacro structure. This means freeing
1969 * what was already in it.
1971 nasm_free(smac->name);
1972 free_tlist(smac->expansion);
1974 } else {
1975 smtbl = ctx ? &ctx->localmac : &smacros;
1976 smhead = (SMacro **) hash_findi_add(smtbl, mname);
1977 smac = nasm_malloc(sizeof(SMacro));
1978 smac->next = *smhead;
1979 *smhead = smac;
1981 smac->name = nasm_strdup(mname);
1982 smac->casesense = casesense;
1983 smac->nparam = nparam;
1984 smac->expansion = expansion;
1985 smac->in_progress = false;
1986 return true; /* Success */
1990 * Undefine an smacro
1992 static void undef_smacro(Context *ctx, const char *mname)
1994 SMacro **smhead, *s, **sp;
1995 struct hash_table *smtbl;
1997 smtbl = ctx ? &ctx->localmac : &smacros;
1998 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
2000 if (smhead) {
2002 * We now have a macro name... go hunt for it.
2004 sp = smhead;
2005 while ((s = *sp) != NULL) {
2006 if (!mstrcmp(s->name, mname, s->casesense)) {
2007 *sp = s->next;
2008 nasm_free(s->name);
2009 free_tlist(s->expansion);
2010 nasm_free(s);
2011 } else {
2012 sp = &s->next;
2019 * Parse a mmacro specification.
2021 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
2023 bool err;
2025 tline = tline->next;
2026 skip_white_(tline);
2027 tline = expand_id(tline);
2028 if (!tok_type_(tline, TOK_ID)) {
2029 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
2030 return false;
2033 def->prev = NULL;
2034 def->name = nasm_strdup(tline->text);
2035 def->plus = false;
2036 def->nolist = false;
2037 def->in_progress = 0;
2038 def->rep_nest = NULL;
2039 def->nparam_min = 0;
2040 def->nparam_max = 0;
2042 tline = expand_smacro(tline->next);
2043 skip_white_(tline);
2044 if (!tok_type_(tline, TOK_NUMBER)) {
2045 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
2046 } else {
2047 def->nparam_min = def->nparam_max =
2048 readnum(tline->text, &err);
2049 if (err)
2050 error(ERR_NONFATAL,
2051 "unable to parse parameter count `%s'", tline->text);
2053 if (tline && tok_is_(tline->next, "-")) {
2054 tline = tline->next->next;
2055 if (tok_is_(tline, "*")) {
2056 def->nparam_max = INT_MAX;
2057 } else if (!tok_type_(tline, TOK_NUMBER)) {
2058 error(ERR_NONFATAL,
2059 "`%s' expects a parameter count after `-'", directive);
2060 } else {
2061 def->nparam_max = readnum(tline->text, &err);
2062 if (err) {
2063 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
2064 tline->text);
2066 if (def->nparam_min > def->nparam_max) {
2067 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
2071 if (tline && tok_is_(tline->next, "+")) {
2072 tline = tline->next;
2073 def->plus = true;
2075 if (tline && tok_type_(tline->next, TOK_ID) &&
2076 !nasm_stricmp(tline->next->text, ".nolist")) {
2077 tline = tline->next;
2078 def->nolist = true;
2082 * Handle default parameters.
2084 if (tline && tline->next) {
2085 def->dlist = tline->next;
2086 tline->next = NULL;
2087 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
2088 } else {
2089 def->dlist = NULL;
2090 def->defaults = NULL;
2092 def->expansion = NULL;
2094 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2095 !def->plus)
2096 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2097 "too many default macro parameters");
2099 return true;
2104 * Decode a size directive
2106 static int parse_size(const char *str) {
2107 static const char *size_names[] =
2108 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2109 static const int sizes[] =
2110 { 0, 1, 4, 16, 8, 10, 2, 32 };
2112 return sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1];
2116 * find and process preprocessor directive in passed line
2117 * Find out if a line contains a preprocessor directive, and deal
2118 * with it if so.
2120 * If a directive _is_ found, it is the responsibility of this routine
2121 * (and not the caller) to free_tlist() the line.
2123 * @param tline a pointer to the current tokeninzed line linked list
2124 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2127 static int do_directive(Token * tline)
2129 enum preproc_token i;
2130 int j;
2131 bool err;
2132 int nparam;
2133 bool nolist;
2134 bool casesense;
2135 int k, m;
2136 int offset;
2137 char *p, *pp;
2138 const char *mname;
2139 Include *inc;
2140 Context *ctx;
2141 Cond *cond;
2142 MMacro *mmac, **mmhead;
2143 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2144 Line *l;
2145 struct tokenval tokval;
2146 expr *evalresult;
2147 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2148 int64_t count;
2149 size_t len;
2150 int severity;
2152 origline = tline;
2154 skip_white_(tline);
2155 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2156 (tline->text[1] == '%' || tline->text[1] == '$'
2157 || tline->text[1] == '!'))
2158 return NO_DIRECTIVE_FOUND;
2160 i = pp_token_hash(tline->text);
2163 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2164 * since they are known to be buggy at moment, we need to fix them
2165 * in future release (2.09-2.10)
2167 if (i == PP_RMACRO || i == PP_RMACRO || i == PP_EXITMACRO) {
2168 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2169 tline->text);
2170 return NO_DIRECTIVE_FOUND;
2174 * If we're in a non-emitting branch of a condition construct,
2175 * or walking to the end of an already terminated %rep block,
2176 * we should ignore all directives except for condition
2177 * directives.
2179 if (((istk->conds && !emitting(istk->conds->state)) ||
2180 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2181 return NO_DIRECTIVE_FOUND;
2185 * If we're defining a macro or reading a %rep block, we should
2186 * ignore all directives except for %macro/%imacro (which nest),
2187 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2188 * If we're in a %rep block, another %rep nests, so should be let through.
2190 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2191 i != PP_RMACRO && i != PP_IRMACRO &&
2192 i != PP_ENDMACRO && i != PP_ENDM &&
2193 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2194 return NO_DIRECTIVE_FOUND;
2197 if (defining) {
2198 if (i == PP_MACRO || i == PP_IMACRO ||
2199 i == PP_RMACRO || i == PP_IRMACRO) {
2200 nested_mac_count++;
2201 return NO_DIRECTIVE_FOUND;
2202 } else if (nested_mac_count > 0) {
2203 if (i == PP_ENDMACRO) {
2204 nested_mac_count--;
2205 return NO_DIRECTIVE_FOUND;
2208 if (!defining->name) {
2209 if (i == PP_REP) {
2210 nested_rep_count++;
2211 return NO_DIRECTIVE_FOUND;
2212 } else if (nested_rep_count > 0) {
2213 if (i == PP_ENDREP) {
2214 nested_rep_count--;
2215 return NO_DIRECTIVE_FOUND;
2221 switch (i) {
2222 case PP_INVALID:
2223 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2224 tline->text);
2225 return NO_DIRECTIVE_FOUND; /* didn't get it */
2227 case PP_STACKSIZE:
2228 /* Directive to tell NASM what the default stack size is. The
2229 * default is for a 16-bit stack, and this can be overriden with
2230 * %stacksize large.
2232 tline = tline->next;
2233 if (tline && tline->type == TOK_WHITESPACE)
2234 tline = tline->next;
2235 if (!tline || tline->type != TOK_ID) {
2236 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2237 free_tlist(origline);
2238 return DIRECTIVE_FOUND;
2240 if (nasm_stricmp(tline->text, "flat") == 0) {
2241 /* All subsequent ARG directives are for a 32-bit stack */
2242 StackSize = 4;
2243 StackPointer = "ebp";
2244 ArgOffset = 8;
2245 LocalOffset = 0;
2246 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2247 /* All subsequent ARG directives are for a 64-bit stack */
2248 StackSize = 8;
2249 StackPointer = "rbp";
2250 ArgOffset = 16;
2251 LocalOffset = 0;
2252 } else if (nasm_stricmp(tline->text, "large") == 0) {
2253 /* All subsequent ARG directives are for a 16-bit stack,
2254 * far function call.
2256 StackSize = 2;
2257 StackPointer = "bp";
2258 ArgOffset = 4;
2259 LocalOffset = 0;
2260 } else if (nasm_stricmp(tline->text, "small") == 0) {
2261 /* All subsequent ARG directives are for a 16-bit stack,
2262 * far function call. We don't support near functions.
2264 StackSize = 2;
2265 StackPointer = "bp";
2266 ArgOffset = 6;
2267 LocalOffset = 0;
2268 } else {
2269 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2270 free_tlist(origline);
2271 return DIRECTIVE_FOUND;
2273 free_tlist(origline);
2274 return DIRECTIVE_FOUND;
2276 case PP_ARG:
2277 /* TASM like ARG directive to define arguments to functions, in
2278 * the following form:
2280 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2282 offset = ArgOffset;
2283 do {
2284 char *arg, directive[256];
2285 int size = StackSize;
2287 /* Find the argument name */
2288 tline = tline->next;
2289 if (tline && tline->type == TOK_WHITESPACE)
2290 tline = tline->next;
2291 if (!tline || tline->type != TOK_ID) {
2292 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2293 free_tlist(origline);
2294 return DIRECTIVE_FOUND;
2296 arg = tline->text;
2298 /* Find the argument size type */
2299 tline = tline->next;
2300 if (!tline || tline->type != TOK_OTHER
2301 || tline->text[0] != ':') {
2302 error(ERR_NONFATAL,
2303 "Syntax error processing `%%arg' directive");
2304 free_tlist(origline);
2305 return DIRECTIVE_FOUND;
2307 tline = tline->next;
2308 if (!tline || tline->type != TOK_ID) {
2309 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2310 free_tlist(origline);
2311 return DIRECTIVE_FOUND;
2314 /* Allow macro expansion of type parameter */
2315 tt = tokenize(tline->text);
2316 tt = expand_smacro(tt);
2317 size = parse_size(tt->text);
2318 if (!size) {
2319 error(ERR_NONFATAL,
2320 "Invalid size type for `%%arg' missing directive");
2321 free_tlist(tt);
2322 free_tlist(origline);
2323 return DIRECTIVE_FOUND;
2325 free_tlist(tt);
2327 /* Round up to even stack slots */
2328 size = ALIGN(size, StackSize);
2330 /* Now define the macro for the argument */
2331 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2332 arg, StackPointer, offset);
2333 do_directive(tokenize(directive));
2334 offset += size;
2336 /* Move to the next argument in the list */
2337 tline = tline->next;
2338 if (tline && tline->type == TOK_WHITESPACE)
2339 tline = tline->next;
2340 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2341 ArgOffset = offset;
2342 free_tlist(origline);
2343 return DIRECTIVE_FOUND;
2345 case PP_LOCAL:
2346 /* TASM like LOCAL directive to define local variables for a
2347 * function, in the following form:
2349 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2351 * The '= LocalSize' at the end is ignored by NASM, but is
2352 * required by TASM to define the local parameter size (and used
2353 * by the TASM macro package).
2355 offset = LocalOffset;
2356 do {
2357 char *local, directive[256];
2358 int size = StackSize;
2360 /* Find the argument name */
2361 tline = tline->next;
2362 if (tline && tline->type == TOK_WHITESPACE)
2363 tline = tline->next;
2364 if (!tline || tline->type != TOK_ID) {
2365 error(ERR_NONFATAL,
2366 "`%%local' missing argument parameter");
2367 free_tlist(origline);
2368 return DIRECTIVE_FOUND;
2370 local = tline->text;
2372 /* Find the argument size type */
2373 tline = tline->next;
2374 if (!tline || tline->type != TOK_OTHER
2375 || tline->text[0] != ':') {
2376 error(ERR_NONFATAL,
2377 "Syntax error processing `%%local' directive");
2378 free_tlist(origline);
2379 return DIRECTIVE_FOUND;
2381 tline = tline->next;
2382 if (!tline || tline->type != TOK_ID) {
2383 error(ERR_NONFATAL,
2384 "`%%local' missing size type parameter");
2385 free_tlist(origline);
2386 return DIRECTIVE_FOUND;
2389 /* Allow macro expansion of type parameter */
2390 tt = tokenize(tline->text);
2391 tt = expand_smacro(tt);
2392 size = parse_size(tt->text);
2393 if (!size) {
2394 error(ERR_NONFATAL,
2395 "Invalid size type for `%%local' missing directive");
2396 free_tlist(tt);
2397 free_tlist(origline);
2398 return DIRECTIVE_FOUND;
2400 free_tlist(tt);
2402 /* Round up to even stack slots */
2403 size = ALIGN(size, StackSize);
2405 offset += size; /* Negative offset, increment before */
2407 /* Now define the macro for the argument */
2408 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2409 local, StackPointer, offset);
2410 do_directive(tokenize(directive));
2412 /* Now define the assign to setup the enter_c macro correctly */
2413 snprintf(directive, sizeof(directive),
2414 "%%assign %%$localsize %%$localsize+%d", size);
2415 do_directive(tokenize(directive));
2417 /* Move to the next argument in the list */
2418 tline = tline->next;
2419 if (tline && tline->type == TOK_WHITESPACE)
2420 tline = tline->next;
2421 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2422 LocalOffset = offset;
2423 free_tlist(origline);
2424 return DIRECTIVE_FOUND;
2426 case PP_CLEAR:
2427 if (tline->next)
2428 error(ERR_WARNING|ERR_PASS1,
2429 "trailing garbage after `%%clear' ignored");
2430 free_macros();
2431 init_macros();
2432 free_tlist(origline);
2433 return DIRECTIVE_FOUND;
2435 case PP_DEPEND:
2436 t = tline->next = expand_smacro(tline->next);
2437 skip_white_(t);
2438 if (!t || (t->type != TOK_STRING &&
2439 t->type != TOK_INTERNAL_STRING)) {
2440 error(ERR_NONFATAL, "`%%depend' expects a file name");
2441 free_tlist(origline);
2442 return DIRECTIVE_FOUND; /* but we did _something_ */
2444 if (t->next)
2445 error(ERR_WARNING|ERR_PASS1,
2446 "trailing garbage after `%%depend' ignored");
2447 p = t->text;
2448 if (t->type != TOK_INTERNAL_STRING)
2449 nasm_unquote_cstr(p, i);
2450 if (dephead && !in_list(*dephead, p)) {
2451 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2452 sl->next = NULL;
2453 strcpy(sl->str, p);
2454 *deptail = sl;
2455 deptail = &sl->next;
2457 free_tlist(origline);
2458 return DIRECTIVE_FOUND;
2460 case PP_INCLUDE:
2461 t = tline->next = expand_smacro(tline->next);
2462 skip_white_(t);
2464 if (!t || (t->type != TOK_STRING &&
2465 t->type != TOK_INTERNAL_STRING)) {
2466 error(ERR_NONFATAL, "`%%include' expects a file name");
2467 free_tlist(origline);
2468 return DIRECTIVE_FOUND; /* but we did _something_ */
2470 if (t->next)
2471 error(ERR_WARNING|ERR_PASS1,
2472 "trailing garbage after `%%include' ignored");
2473 p = t->text;
2474 if (t->type != TOK_INTERNAL_STRING)
2475 nasm_unquote_cstr(p, i);
2476 inc = nasm_malloc(sizeof(Include));
2477 inc->next = istk;
2478 inc->conds = NULL;
2479 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2480 if (!inc->fp) {
2481 /* -MG given but file not found */
2482 nasm_free(inc);
2483 } else {
2484 inc->fname = src_set_fname(nasm_strdup(p));
2485 inc->lineno = src_set_linnum(0);
2486 inc->lineinc = 1;
2487 inc->expansion = NULL;
2488 inc->mstk = NULL;
2489 istk = inc;
2490 list->uplevel(LIST_INCLUDE);
2492 free_tlist(origline);
2493 return DIRECTIVE_FOUND;
2495 case PP_USE:
2497 static macros_t *use_pkg;
2498 const char *pkg_macro = NULL;
2500 tline = tline->next;
2501 skip_white_(tline);
2502 tline = expand_id(tline);
2504 if (!tline || (tline->type != TOK_STRING &&
2505 tline->type != TOK_INTERNAL_STRING &&
2506 tline->type != TOK_ID)) {
2507 error(ERR_NONFATAL, "`%%use' expects a package name");
2508 free_tlist(origline);
2509 return DIRECTIVE_FOUND; /* but we did _something_ */
2511 if (tline->next)
2512 error(ERR_WARNING|ERR_PASS1,
2513 "trailing garbage after `%%use' ignored");
2514 if (tline->type == TOK_STRING)
2515 nasm_unquote_cstr(tline->text, i);
2516 use_pkg = nasm_stdmac_find_package(tline->text);
2517 if (!use_pkg)
2518 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2519 else
2520 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2521 if (use_pkg && ! smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2522 /* Not already included, go ahead and include it */
2523 stdmacpos = use_pkg;
2525 free_tlist(origline);
2526 return DIRECTIVE_FOUND;
2528 case PP_PUSH:
2529 case PP_REPL:
2530 case PP_POP:
2531 tline = tline->next;
2532 skip_white_(tline);
2533 tline = expand_id(tline);
2534 if (tline) {
2535 if (!tok_type_(tline, TOK_ID)) {
2536 error(ERR_NONFATAL, "`%s' expects a context identifier",
2537 pp_directives[i]);
2538 free_tlist(origline);
2539 return DIRECTIVE_FOUND; /* but we did _something_ */
2541 if (tline->next)
2542 error(ERR_WARNING|ERR_PASS1,
2543 "trailing garbage after `%s' ignored",
2544 pp_directives[i]);
2545 p = nasm_strdup(tline->text);
2546 } else {
2547 p = NULL; /* Anonymous */
2550 if (i == PP_PUSH) {
2551 ctx = nasm_malloc(sizeof(Context));
2552 ctx->next = cstk;
2553 hash_init(&ctx->localmac, HASH_SMALL);
2554 ctx->name = p;
2555 ctx->number = unique++;
2556 cstk = ctx;
2557 } else {
2558 /* %pop or %repl */
2559 if (!cstk) {
2560 error(ERR_NONFATAL, "`%s': context stack is empty",
2561 pp_directives[i]);
2562 } else if (i == PP_POP) {
2563 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2564 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2565 "expected %s",
2566 cstk->name ? cstk->name : "anonymous", p);
2567 else
2568 ctx_pop();
2569 } else {
2570 /* i == PP_REPL */
2571 nasm_free(cstk->name);
2572 cstk->name = p;
2573 p = NULL;
2575 nasm_free(p);
2577 free_tlist(origline);
2578 return DIRECTIVE_FOUND;
2579 case PP_FATAL:
2580 severity = ERR_FATAL;
2581 goto issue_error;
2582 case PP_ERROR:
2583 severity = ERR_NONFATAL;
2584 goto issue_error;
2585 case PP_WARNING:
2586 severity = ERR_WARNING|ERR_WARN_USER;
2587 goto issue_error;
2589 issue_error:
2591 /* Only error out if this is the final pass */
2592 if (pass != 2 && i != PP_FATAL)
2593 return DIRECTIVE_FOUND;
2595 tline->next = expand_smacro(tline->next);
2596 tline = tline->next;
2597 skip_white_(tline);
2598 t = tline ? tline->next : NULL;
2599 skip_white_(t);
2600 if (tok_type_(tline, TOK_STRING) && !t) {
2601 /* The line contains only a quoted string */
2602 p = tline->text;
2603 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2604 error(severity, "%s", p);
2605 } else {
2606 /* Not a quoted string, or more than a quoted string */
2607 p = detoken(tline, false);
2608 error(severity, "%s", p);
2609 nasm_free(p);
2611 free_tlist(origline);
2612 return DIRECTIVE_FOUND;
2615 CASE_PP_IF:
2616 if (istk->conds && !emitting(istk->conds->state))
2617 j = COND_NEVER;
2618 else {
2619 j = if_condition(tline->next, i);
2620 tline->next = NULL; /* it got freed */
2621 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2623 cond = nasm_malloc(sizeof(Cond));
2624 cond->next = istk->conds;
2625 cond->state = j;
2626 istk->conds = cond;
2627 if(istk->mstk)
2628 istk->mstk->condcnt ++;
2629 free_tlist(origline);
2630 return DIRECTIVE_FOUND;
2632 CASE_PP_ELIF:
2633 if (!istk->conds)
2634 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2635 switch(istk->conds->state) {
2636 case COND_IF_TRUE:
2637 istk->conds->state = COND_DONE;
2638 break;
2640 case COND_DONE:
2641 case COND_NEVER:
2642 break;
2644 case COND_ELSE_TRUE:
2645 case COND_ELSE_FALSE:
2646 error_precond(ERR_WARNING|ERR_PASS1,
2647 "`%%elif' after `%%else' ignored");
2648 istk->conds->state = COND_NEVER;
2649 break;
2651 case COND_IF_FALSE:
2653 * IMPORTANT: In the case of %if, we will already have
2654 * called expand_mmac_params(); however, if we're
2655 * processing an %elif we must have been in a
2656 * non-emitting mode, which would have inhibited
2657 * the normal invocation of expand_mmac_params().
2658 * Therefore, we have to do it explicitly here.
2660 j = if_condition(expand_mmac_params(tline->next), i);
2661 tline->next = NULL; /* it got freed */
2662 istk->conds->state =
2663 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2664 break;
2666 free_tlist(origline);
2667 return DIRECTIVE_FOUND;
2669 case PP_ELSE:
2670 if (tline->next)
2671 error_precond(ERR_WARNING|ERR_PASS1,
2672 "trailing garbage after `%%else' ignored");
2673 if (!istk->conds)
2674 error(ERR_FATAL, "`%%else': no matching `%%if'");
2675 switch(istk->conds->state) {
2676 case COND_IF_TRUE:
2677 case COND_DONE:
2678 istk->conds->state = COND_ELSE_FALSE;
2679 break;
2681 case COND_NEVER:
2682 break;
2684 case COND_IF_FALSE:
2685 istk->conds->state = COND_ELSE_TRUE;
2686 break;
2688 case COND_ELSE_TRUE:
2689 case COND_ELSE_FALSE:
2690 error_precond(ERR_WARNING|ERR_PASS1,
2691 "`%%else' after `%%else' ignored.");
2692 istk->conds->state = COND_NEVER;
2693 break;
2695 free_tlist(origline);
2696 return DIRECTIVE_FOUND;
2698 case PP_ENDIF:
2699 if (tline->next)
2700 error_precond(ERR_WARNING|ERR_PASS1,
2701 "trailing garbage after `%%endif' ignored");
2702 if (!istk->conds)
2703 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2704 cond = istk->conds;
2705 istk->conds = cond->next;
2706 nasm_free(cond);
2707 if(istk->mstk)
2708 istk->mstk->condcnt --;
2709 free_tlist(origline);
2710 return DIRECTIVE_FOUND;
2712 case PP_RMACRO:
2713 case PP_IRMACRO:
2714 case PP_MACRO:
2715 case PP_IMACRO:
2716 if (defining) {
2717 error(ERR_FATAL, "`%s': already defining a macro",
2718 pp_directives[i]);
2719 return DIRECTIVE_FOUND;
2721 defining = nasm_malloc(sizeof(MMacro));
2722 defining->max_depth =
2723 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2724 defining->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2725 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2726 nasm_free(defining);
2727 defining = NULL;
2728 return DIRECTIVE_FOUND;
2731 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2732 while (mmac) {
2733 if (!strcmp(mmac->name, defining->name) &&
2734 (mmac->nparam_min <= defining->nparam_max
2735 || defining->plus)
2736 && (defining->nparam_min <= mmac->nparam_max
2737 || mmac->plus)) {
2738 error(ERR_WARNING|ERR_PASS1,
2739 "redefining multi-line macro `%s'", defining->name);
2740 return DIRECTIVE_FOUND;
2742 mmac = mmac->next;
2744 free_tlist(origline);
2745 return DIRECTIVE_FOUND;
2747 case PP_ENDM:
2748 case PP_ENDMACRO:
2749 if (! (defining && defining->name)) {
2750 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2751 return DIRECTIVE_FOUND;
2753 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2754 defining->next = *mmhead;
2755 *mmhead = defining;
2756 defining = NULL;
2757 free_tlist(origline);
2758 return DIRECTIVE_FOUND;
2760 case PP_EXITMACRO:
2762 * We must search along istk->expansion until we hit a
2763 * macro-end marker for a macro with a name. Then we
2764 * bypass all lines between exitmacro and endmacro.
2766 list_for_each(l, istk->expansion)
2767 if (l->finishes && l->finishes->name)
2768 break;
2770 if (l) {
2772 * Remove all conditional entries relative to this
2773 * macro invocation. (safe to do in this context)
2775 for ( ; l->finishes->condcnt > 0; l->finishes->condcnt --) {
2776 cond = istk->conds;
2777 istk->conds = cond->next;
2778 nasm_free(cond);
2780 istk->expansion = l;
2781 } else {
2782 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2784 free_tlist(origline);
2785 return DIRECTIVE_FOUND;
2787 case PP_UNMACRO:
2788 case PP_UNIMACRO:
2790 MMacro **mmac_p;
2791 MMacro spec;
2793 spec.casesense = (i == PP_UNMACRO);
2794 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2795 return DIRECTIVE_FOUND;
2797 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2798 while (mmac_p && *mmac_p) {
2799 mmac = *mmac_p;
2800 if (mmac->casesense == spec.casesense &&
2801 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2802 mmac->nparam_min == spec.nparam_min &&
2803 mmac->nparam_max == spec.nparam_max &&
2804 mmac->plus == spec.plus) {
2805 *mmac_p = mmac->next;
2806 free_mmacro(mmac);
2807 } else {
2808 mmac_p = &mmac->next;
2811 free_tlist(origline);
2812 free_tlist(spec.dlist);
2813 return DIRECTIVE_FOUND;
2816 case PP_ROTATE:
2817 if (tline->next && tline->next->type == TOK_WHITESPACE)
2818 tline = tline->next;
2819 if (!tline->next) {
2820 free_tlist(origline);
2821 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2822 return DIRECTIVE_FOUND;
2824 t = expand_smacro(tline->next);
2825 tline->next = NULL;
2826 free_tlist(origline);
2827 tline = t;
2828 tptr = &t;
2829 tokval.t_type = TOKEN_INVALID;
2830 evalresult =
2831 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2832 free_tlist(tline);
2833 if (!evalresult)
2834 return DIRECTIVE_FOUND;
2835 if (tokval.t_type)
2836 error(ERR_WARNING|ERR_PASS1,
2837 "trailing garbage after expression ignored");
2838 if (!is_simple(evalresult)) {
2839 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2840 return DIRECTIVE_FOUND;
2842 mmac = istk->mstk;
2843 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2844 mmac = mmac->next_active;
2845 if (!mmac) {
2846 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2847 } else if (mmac->nparam == 0) {
2848 error(ERR_NONFATAL,
2849 "`%%rotate' invoked within macro without parameters");
2850 } else {
2851 int rotate = mmac->rotate + reloc_value(evalresult);
2853 rotate %= (int)mmac->nparam;
2854 if (rotate < 0)
2855 rotate += mmac->nparam;
2857 mmac->rotate = rotate;
2859 return DIRECTIVE_FOUND;
2861 case PP_REP:
2862 nolist = false;
2863 do {
2864 tline = tline->next;
2865 } while (tok_type_(tline, TOK_WHITESPACE));
2867 if (tok_type_(tline, TOK_ID) &&
2868 nasm_stricmp(tline->text, ".nolist") == 0) {
2869 nolist = true;
2870 do {
2871 tline = tline->next;
2872 } while (tok_type_(tline, TOK_WHITESPACE));
2875 if (tline) {
2876 t = expand_smacro(tline);
2877 tptr = &t;
2878 tokval.t_type = TOKEN_INVALID;
2879 evalresult =
2880 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2881 if (!evalresult) {
2882 free_tlist(origline);
2883 return DIRECTIVE_FOUND;
2885 if (tokval.t_type)
2886 error(ERR_WARNING|ERR_PASS1,
2887 "trailing garbage after expression ignored");
2888 if (!is_simple(evalresult)) {
2889 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2890 return DIRECTIVE_FOUND;
2892 count = reloc_value(evalresult) + 1;
2893 } else {
2894 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2895 count = 0;
2897 free_tlist(origline);
2899 tmp_defining = defining;
2900 defining = nasm_malloc(sizeof(MMacro));
2901 defining->prev = NULL;
2902 defining->name = NULL; /* flags this macro as a %rep block */
2903 defining->casesense = false;
2904 defining->plus = false;
2905 defining->nolist = nolist;
2906 defining->in_progress = count;
2907 defining->max_depth = 0;
2908 defining->nparam_min = defining->nparam_max = 0;
2909 defining->defaults = NULL;
2910 defining->dlist = NULL;
2911 defining->expansion = NULL;
2912 defining->next_active = istk->mstk;
2913 defining->rep_nest = tmp_defining;
2914 return DIRECTIVE_FOUND;
2916 case PP_ENDREP:
2917 if (!defining || defining->name) {
2918 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2919 return DIRECTIVE_FOUND;
2923 * Now we have a "macro" defined - although it has no name
2924 * and we won't be entering it in the hash tables - we must
2925 * push a macro-end marker for it on to istk->expansion.
2926 * After that, it will take care of propagating itself (a
2927 * macro-end marker line for a macro which is really a %rep
2928 * block will cause the macro to be re-expanded, complete
2929 * with another macro-end marker to ensure the process
2930 * continues) until the whole expansion is forcibly removed
2931 * from istk->expansion by a %exitrep.
2933 l = nasm_malloc(sizeof(Line));
2934 l->next = istk->expansion;
2935 l->finishes = defining;
2936 l->first = NULL;
2937 istk->expansion = l;
2939 istk->mstk = defining;
2941 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2942 tmp_defining = defining;
2943 defining = defining->rep_nest;
2944 free_tlist(origline);
2945 return DIRECTIVE_FOUND;
2947 case PP_EXITREP:
2949 * We must search along istk->expansion until we hit a
2950 * macro-end marker for a macro with no name. Then we set
2951 * its `in_progress' flag to 0.
2953 list_for_each(l, istk->expansion)
2954 if (l->finishes && !l->finishes->name)
2955 break;
2957 if (l)
2958 l->finishes->in_progress = 1;
2959 else
2960 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2961 free_tlist(origline);
2962 return DIRECTIVE_FOUND;
2964 case PP_XDEFINE:
2965 case PP_IXDEFINE:
2966 case PP_DEFINE:
2967 case PP_IDEFINE:
2968 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2970 tline = tline->next;
2971 skip_white_(tline);
2972 tline = expand_id(tline);
2973 if (!tline || (tline->type != TOK_ID &&
2974 (tline->type != TOK_PREPROC_ID ||
2975 tline->text[1] != '$'))) {
2976 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2977 pp_directives[i]);
2978 free_tlist(origline);
2979 return DIRECTIVE_FOUND;
2982 ctx = get_ctx(tline->text, &mname, false);
2983 last = tline;
2984 param_start = tline = tline->next;
2985 nparam = 0;
2987 /* Expand the macro definition now for %xdefine and %ixdefine */
2988 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2989 tline = expand_smacro(tline);
2991 if (tok_is_(tline, "(")) {
2993 * This macro has parameters.
2996 tline = tline->next;
2997 while (1) {
2998 skip_white_(tline);
2999 if (!tline) {
3000 error(ERR_NONFATAL, "parameter identifier expected");
3001 free_tlist(origline);
3002 return DIRECTIVE_FOUND;
3004 if (tline->type != TOK_ID) {
3005 error(ERR_NONFATAL,
3006 "`%s': parameter identifier expected",
3007 tline->text);
3008 free_tlist(origline);
3009 return DIRECTIVE_FOUND;
3011 tline->type = TOK_SMAC_PARAM + nparam++;
3012 tline = tline->next;
3013 skip_white_(tline);
3014 if (tok_is_(tline, ",")) {
3015 tline = tline->next;
3016 } else {
3017 if (!tok_is_(tline, ")")) {
3018 error(ERR_NONFATAL,
3019 "`)' expected to terminate macro template");
3020 free_tlist(origline);
3021 return DIRECTIVE_FOUND;
3023 break;
3026 last = tline;
3027 tline = tline->next;
3029 if (tok_type_(tline, TOK_WHITESPACE))
3030 last = tline, tline = tline->next;
3031 macro_start = NULL;
3032 last->next = NULL;
3033 t = tline;
3034 while (t) {
3035 if (t->type == TOK_ID) {
3036 list_for_each(tt, param_start)
3037 if (tt->type >= TOK_SMAC_PARAM &&
3038 !strcmp(tt->text, t->text))
3039 t->type = tt->type;
3041 tt = t->next;
3042 t->next = macro_start;
3043 macro_start = t;
3044 t = tt;
3047 * Good. We now have a macro name, a parameter count, and a
3048 * token list (in reverse order) for an expansion. We ought
3049 * to be OK just to create an SMacro, store it, and let
3050 * free_tlist have the rest of the line (which we have
3051 * carefully re-terminated after chopping off the expansion
3052 * from the end).
3054 define_smacro(ctx, mname, casesense, nparam, macro_start);
3055 free_tlist(origline);
3056 return DIRECTIVE_FOUND;
3058 case PP_UNDEF:
3059 tline = tline->next;
3060 skip_white_(tline);
3061 tline = expand_id(tline);
3062 if (!tline || (tline->type != TOK_ID &&
3063 (tline->type != TOK_PREPROC_ID ||
3064 tline->text[1] != '$'))) {
3065 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
3066 free_tlist(origline);
3067 return DIRECTIVE_FOUND;
3069 if (tline->next) {
3070 error(ERR_WARNING|ERR_PASS1,
3071 "trailing garbage after macro name ignored");
3074 /* Find the context that symbol belongs to */
3075 ctx = get_ctx(tline->text, &mname, false);
3076 undef_smacro(ctx, mname);
3077 free_tlist(origline);
3078 return DIRECTIVE_FOUND;
3080 case PP_DEFSTR:
3081 case PP_IDEFSTR:
3082 casesense = (i == PP_DEFSTR);
3084 tline = tline->next;
3085 skip_white_(tline);
3086 tline = expand_id(tline);
3087 if (!tline || (tline->type != TOK_ID &&
3088 (tline->type != TOK_PREPROC_ID ||
3089 tline->text[1] != '$'))) {
3090 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3091 pp_directives[i]);
3092 free_tlist(origline);
3093 return DIRECTIVE_FOUND;
3096 ctx = get_ctx(tline->text, &mname, false);
3097 last = tline;
3098 tline = expand_smacro(tline->next);
3099 last->next = NULL;
3101 while (tok_type_(tline, TOK_WHITESPACE))
3102 tline = delete_Token(tline);
3104 p = detoken(tline, false);
3105 macro_start = nasm_malloc(sizeof(*macro_start));
3106 macro_start->next = NULL;
3107 macro_start->text = nasm_quote(p, strlen(p));
3108 macro_start->type = TOK_STRING;
3109 macro_start->a.mac = NULL;
3110 nasm_free(p);
3113 * We now have a macro name, an implicit parameter count of
3114 * zero, and a string token to use as an expansion. Create
3115 * and store an SMacro.
3117 define_smacro(ctx, mname, casesense, 0, macro_start);
3118 free_tlist(origline);
3119 return DIRECTIVE_FOUND;
3121 case PP_DEFTOK:
3122 case PP_IDEFTOK:
3123 casesense = (i == PP_DEFTOK);
3125 tline = tline->next;
3126 skip_white_(tline);
3127 tline = expand_id(tline);
3128 if (!tline || (tline->type != TOK_ID &&
3129 (tline->type != TOK_PREPROC_ID ||
3130 tline->text[1] != '$'))) {
3131 error(ERR_NONFATAL,
3132 "`%s' expects a macro identifier as first parameter",
3133 pp_directives[i]);
3134 free_tlist(origline);
3135 return DIRECTIVE_FOUND;
3137 ctx = get_ctx(tline->text, &mname, false);
3138 last = tline;
3139 tline = expand_smacro(tline->next);
3140 last->next = NULL;
3142 t = tline;
3143 while (tok_type_(t, TOK_WHITESPACE))
3144 t = t->next;
3145 /* t should now point to the string */
3146 if (t->type != TOK_STRING) {
3147 error(ERR_NONFATAL,
3148 "`%s` requires string as second parameter",
3149 pp_directives[i]);
3150 free_tlist(tline);
3151 free_tlist(origline);
3152 return DIRECTIVE_FOUND;
3155 nasm_unquote_cstr(t->text, i);
3156 macro_start = tokenize(t->text);
3159 * We now have a macro name, an implicit parameter count of
3160 * zero, and a numeric token to use as an expansion. Create
3161 * and store an SMacro.
3163 define_smacro(ctx, mname, casesense, 0, macro_start);
3164 free_tlist(tline);
3165 free_tlist(origline);
3166 return DIRECTIVE_FOUND;
3168 case PP_PATHSEARCH:
3170 FILE *fp;
3171 StrList *xsl = NULL;
3172 StrList **xst = &xsl;
3174 casesense = true;
3176 tline = tline->next;
3177 skip_white_(tline);
3178 tline = expand_id(tline);
3179 if (!tline || (tline->type != TOK_ID &&
3180 (tline->type != TOK_PREPROC_ID ||
3181 tline->text[1] != '$'))) {
3182 error(ERR_NONFATAL,
3183 "`%%pathsearch' expects a macro identifier as first parameter");
3184 free_tlist(origline);
3185 return DIRECTIVE_FOUND;
3187 ctx = get_ctx(tline->text, &mname, false);
3188 last = tline;
3189 tline = expand_smacro(tline->next);
3190 last->next = NULL;
3192 t = tline;
3193 while (tok_type_(t, TOK_WHITESPACE))
3194 t = t->next;
3196 if (!t || (t->type != TOK_STRING &&
3197 t->type != TOK_INTERNAL_STRING)) {
3198 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3199 free_tlist(tline);
3200 free_tlist(origline);
3201 return DIRECTIVE_FOUND; /* but we did _something_ */
3203 if (t->next)
3204 error(ERR_WARNING|ERR_PASS1,
3205 "trailing garbage after `%%pathsearch' ignored");
3206 p = t->text;
3207 if (t->type != TOK_INTERNAL_STRING)
3208 nasm_unquote(p, NULL);
3210 fp = inc_fopen(p, &xsl, &xst, true);
3211 if (fp) {
3212 p = xsl->str;
3213 fclose(fp); /* Don't actually care about the file */
3215 macro_start = nasm_malloc(sizeof(*macro_start));
3216 macro_start->next = NULL;
3217 macro_start->text = nasm_quote(p, strlen(p));
3218 macro_start->type = TOK_STRING;
3219 macro_start->a.mac = NULL;
3220 if (xsl)
3221 nasm_free(xsl);
3224 * We now have a macro name, an implicit parameter count of
3225 * zero, and a string token to use as an expansion. Create
3226 * and store an SMacro.
3228 define_smacro(ctx, mname, casesense, 0, macro_start);
3229 free_tlist(tline);
3230 free_tlist(origline);
3231 return DIRECTIVE_FOUND;
3234 case PP_STRLEN:
3235 casesense = true;
3237 tline = tline->next;
3238 skip_white_(tline);
3239 tline = expand_id(tline);
3240 if (!tline || (tline->type != TOK_ID &&
3241 (tline->type != TOK_PREPROC_ID ||
3242 tline->text[1] != '$'))) {
3243 error(ERR_NONFATAL,
3244 "`%%strlen' expects a macro identifier as first parameter");
3245 free_tlist(origline);
3246 return DIRECTIVE_FOUND;
3248 ctx = get_ctx(tline->text, &mname, false);
3249 last = tline;
3250 tline = expand_smacro(tline->next);
3251 last->next = NULL;
3253 t = tline;
3254 while (tok_type_(t, TOK_WHITESPACE))
3255 t = t->next;
3256 /* t should now point to the string */
3257 if (!tok_type_(t, TOK_STRING)) {
3258 error(ERR_NONFATAL,
3259 "`%%strlen` requires string as second parameter");
3260 free_tlist(tline);
3261 free_tlist(origline);
3262 return DIRECTIVE_FOUND;
3265 macro_start = nasm_malloc(sizeof(*macro_start));
3266 macro_start->next = NULL;
3267 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3268 macro_start->a.mac = NULL;
3271 * We now have a macro name, an implicit parameter count of
3272 * zero, and a numeric token to use as an expansion. Create
3273 * and store an SMacro.
3275 define_smacro(ctx, mname, casesense, 0, macro_start);
3276 free_tlist(tline);
3277 free_tlist(origline);
3278 return DIRECTIVE_FOUND;
3280 case PP_STRCAT:
3281 casesense = true;
3283 tline = tline->next;
3284 skip_white_(tline);
3285 tline = expand_id(tline);
3286 if (!tline || (tline->type != TOK_ID &&
3287 (tline->type != TOK_PREPROC_ID ||
3288 tline->text[1] != '$'))) {
3289 error(ERR_NONFATAL,
3290 "`%%strcat' expects a macro identifier as first parameter");
3291 free_tlist(origline);
3292 return DIRECTIVE_FOUND;
3294 ctx = get_ctx(tline->text, &mname, false);
3295 last = tline;
3296 tline = expand_smacro(tline->next);
3297 last->next = NULL;
3299 len = 0;
3300 list_for_each(t, tline) {
3301 switch (t->type) {
3302 case TOK_WHITESPACE:
3303 break;
3304 case TOK_STRING:
3305 len += t->a.len = nasm_unquote(t->text, NULL);
3306 break;
3307 case TOK_OTHER:
3308 if (!strcmp(t->text, ",")) /* permit comma separators */
3309 break;
3310 /* else fall through */
3311 default:
3312 error(ERR_NONFATAL,
3313 "non-string passed to `%%strcat' (%d)", t->type);
3314 free_tlist(tline);
3315 free_tlist(origline);
3316 return DIRECTIVE_FOUND;
3320 p = pp = nasm_malloc(len);
3321 list_for_each(t, tline) {
3322 if (t->type == TOK_STRING) {
3323 memcpy(p, t->text, t->a.len);
3324 p += t->a.len;
3329 * We now have a macro name, an implicit parameter count of
3330 * zero, and a numeric token to use as an expansion. Create
3331 * and store an SMacro.
3333 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3334 macro_start->text = nasm_quote(pp, len);
3335 nasm_free(pp);
3336 define_smacro(ctx, mname, casesense, 0, macro_start);
3337 free_tlist(tline);
3338 free_tlist(origline);
3339 return DIRECTIVE_FOUND;
3341 case PP_SUBSTR:
3343 int64_t a1, a2;
3344 size_t len;
3346 casesense = true;
3348 tline = tline->next;
3349 skip_white_(tline);
3350 tline = expand_id(tline);
3351 if (!tline || (tline->type != TOK_ID &&
3352 (tline->type != TOK_PREPROC_ID ||
3353 tline->text[1] != '$'))) {
3354 error(ERR_NONFATAL,
3355 "`%%substr' expects a macro identifier as first parameter");
3356 free_tlist(origline);
3357 return DIRECTIVE_FOUND;
3359 ctx = get_ctx(tline->text, &mname, false);
3360 last = tline;
3361 tline = expand_smacro(tline->next);
3362 last->next = NULL;
3364 t = tline->next;
3365 while (tok_type_(t, TOK_WHITESPACE))
3366 t = t->next;
3368 /* t should now point to the string */
3369 if (t->type != TOK_STRING) {
3370 error(ERR_NONFATAL,
3371 "`%%substr` requires string as second parameter");
3372 free_tlist(tline);
3373 free_tlist(origline);
3374 return DIRECTIVE_FOUND;
3377 tt = t->next;
3378 tptr = &tt;
3379 tokval.t_type = TOKEN_INVALID;
3380 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3381 pass, error, NULL);
3382 if (!evalresult) {
3383 free_tlist(tline);
3384 free_tlist(origline);
3385 return DIRECTIVE_FOUND;
3386 } else if (!is_simple(evalresult)) {
3387 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3388 free_tlist(tline);
3389 free_tlist(origline);
3390 return DIRECTIVE_FOUND;
3392 a1 = evalresult->value-1;
3394 while (tok_type_(tt, TOK_WHITESPACE))
3395 tt = tt->next;
3396 if (!tt) {
3397 a2 = 1; /* Backwards compatibility: one character */
3398 } else {
3399 tokval.t_type = TOKEN_INVALID;
3400 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3401 pass, error, NULL);
3402 if (!evalresult) {
3403 free_tlist(tline);
3404 free_tlist(origline);
3405 return DIRECTIVE_FOUND;
3406 } else if (!is_simple(evalresult)) {
3407 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3408 free_tlist(tline);
3409 free_tlist(origline);
3410 return DIRECTIVE_FOUND;
3412 a2 = evalresult->value;
3415 len = nasm_unquote(t->text, NULL);
3416 if (a2 < 0)
3417 a2 = a2+1+len-a1;
3418 if (a1+a2 > (int64_t)len)
3419 a2 = len-a1;
3421 macro_start = nasm_malloc(sizeof(*macro_start));
3422 macro_start->next = NULL;
3423 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3424 macro_start->type = TOK_STRING;
3425 macro_start->a.mac = NULL;
3428 * We now have a macro name, an implicit parameter count of
3429 * zero, and a numeric token to use as an expansion. Create
3430 * and store an SMacro.
3432 define_smacro(ctx, mname, casesense, 0, macro_start);
3433 free_tlist(tline);
3434 free_tlist(origline);
3435 return DIRECTIVE_FOUND;
3438 case PP_ASSIGN:
3439 case PP_IASSIGN:
3440 casesense = (i == PP_ASSIGN);
3442 tline = tline->next;
3443 skip_white_(tline);
3444 tline = expand_id(tline);
3445 if (!tline || (tline->type != TOK_ID &&
3446 (tline->type != TOK_PREPROC_ID ||
3447 tline->text[1] != '$'))) {
3448 error(ERR_NONFATAL,
3449 "`%%%sassign' expects a macro identifier",
3450 (i == PP_IASSIGN ? "i" : ""));
3451 free_tlist(origline);
3452 return DIRECTIVE_FOUND;
3454 ctx = get_ctx(tline->text, &mname, false);
3455 last = tline;
3456 tline = expand_smacro(tline->next);
3457 last->next = NULL;
3459 t = tline;
3460 tptr = &t;
3461 tokval.t_type = TOKEN_INVALID;
3462 evalresult =
3463 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3464 free_tlist(tline);
3465 if (!evalresult) {
3466 free_tlist(origline);
3467 return DIRECTIVE_FOUND;
3470 if (tokval.t_type)
3471 error(ERR_WARNING|ERR_PASS1,
3472 "trailing garbage after expression ignored");
3474 if (!is_simple(evalresult)) {
3475 error(ERR_NONFATAL,
3476 "non-constant value given to `%%%sassign'",
3477 (i == PP_IASSIGN ? "i" : ""));
3478 free_tlist(origline);
3479 return DIRECTIVE_FOUND;
3482 macro_start = nasm_malloc(sizeof(*macro_start));
3483 macro_start->next = NULL;
3484 make_tok_num(macro_start, reloc_value(evalresult));
3485 macro_start->a.mac = NULL;
3488 * We now have a macro name, an implicit parameter count of
3489 * zero, and a numeric token to use as an expansion. Create
3490 * and store an SMacro.
3492 define_smacro(ctx, mname, casesense, 0, macro_start);
3493 free_tlist(origline);
3494 return DIRECTIVE_FOUND;
3496 case PP_LINE:
3498 * Syntax is `%line nnn[+mmm] [filename]'
3500 tline = tline->next;
3501 skip_white_(tline);
3502 if (!tok_type_(tline, TOK_NUMBER)) {
3503 error(ERR_NONFATAL, "`%%line' expects line number");
3504 free_tlist(origline);
3505 return DIRECTIVE_FOUND;
3507 k = readnum(tline->text, &err);
3508 m = 1;
3509 tline = tline->next;
3510 if (tok_is_(tline, "+")) {
3511 tline = tline->next;
3512 if (!tok_type_(tline, TOK_NUMBER)) {
3513 error(ERR_NONFATAL, "`%%line' expects line increment");
3514 free_tlist(origline);
3515 return DIRECTIVE_FOUND;
3517 m = readnum(tline->text, &err);
3518 tline = tline->next;
3520 skip_white_(tline);
3521 src_set_linnum(k);
3522 istk->lineinc = m;
3523 if (tline) {
3524 nasm_free(src_set_fname(detoken(tline, false)));
3526 free_tlist(origline);
3527 return DIRECTIVE_FOUND;
3529 default:
3530 error(ERR_FATAL,
3531 "preprocessor directive `%s' not yet implemented",
3532 pp_directives[i]);
3533 return DIRECTIVE_FOUND;
3538 * Ensure that a macro parameter contains a condition code and
3539 * nothing else. Return the condition code index if so, or -1
3540 * otherwise.
3542 static int find_cc(Token * t)
3544 Token *tt;
3545 int i, j, k, m;
3547 if (!t)
3548 return -1; /* Probably a %+ without a space */
3550 skip_white_(t);
3551 if (t->type != TOK_ID)
3552 return -1;
3553 tt = t->next;
3554 skip_white_(tt);
3555 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3556 return -1;
3558 i = -1;
3559 j = ARRAY_SIZE(conditions);
3560 while (j - i > 1) {
3561 k = (j + i) / 2;
3562 m = nasm_stricmp(t->text, conditions[k]);
3563 if (m == 0) {
3564 i = k;
3565 j = -2;
3566 break;
3567 } else if (m < 0) {
3568 j = k;
3569 } else
3570 i = k;
3572 if (j != -2)
3573 return -1;
3574 return i;
3577 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3579 Token **tail, *t, *tt;
3580 Token **paste_head;
3581 bool did_paste = false;
3582 char *tmp;
3584 /* Now handle token pasting... */
3585 paste_head = NULL;
3586 tail = head;
3587 while ((t = *tail) && (tt = t->next)) {
3588 switch (t->type) {
3589 case TOK_WHITESPACE:
3590 if (tt->type == TOK_WHITESPACE) {
3591 /* Zap adjacent whitespace tokens */
3592 t->next = delete_Token(tt);
3593 } else {
3594 /* Do not advance paste_head here */
3595 tail = &t->next;
3597 break;
3598 case TOK_ID:
3599 case TOK_NUMBER:
3600 case TOK_FLOAT:
3602 size_t len = 0;
3603 char *tmp, *p;
3605 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3606 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3607 tt->type == TOK_OTHER)) {
3608 len += strlen(tt->text);
3609 tt = tt->next;
3613 * Now tt points to the first token after
3614 * the potential paste area...
3616 if (tt != t->next) {
3617 /* We have at least two tokens... */
3618 len += strlen(t->text);
3619 p = tmp = nasm_malloc(len+1);
3621 while (t != tt) {
3622 strcpy(p, t->text);
3623 p = strchr(p, '\0');
3624 t = delete_Token(t);
3627 t = *tail = tokenize(tmp);
3628 nasm_free(tmp);
3630 while (t->next) {
3631 tail = &t->next;
3632 t = t->next;
3634 t->next = tt; /* Attach the remaining token chain */
3636 did_paste = true;
3638 paste_head = tail;
3639 tail = &t->next;
3640 break;
3642 case TOK_PASTE: /* %+ */
3643 if (handle_paste_tokens) {
3644 /* Zap %+ and whitespace tokens to the right */
3645 while (t && (t->type == TOK_WHITESPACE ||
3646 t->type == TOK_PASTE))
3647 t = *tail = delete_Token(t);
3648 if (!paste_head || !t)
3649 break; /* Nothing to paste with */
3650 tail = paste_head;
3651 t = *tail;
3652 tt = t->next;
3653 while (tok_type_(tt, TOK_WHITESPACE))
3654 tt = t->next = delete_Token(tt);
3656 if (tt) {
3657 tmp = nasm_strcat(t->text, tt->text);
3658 delete_Token(t);
3659 tt = delete_Token(tt);
3660 t = *tail = tokenize(tmp);
3661 nasm_free(tmp);
3662 while (t->next) {
3663 tail = &t->next;
3664 t = t->next;
3666 t->next = tt; /* Attach the remaining token chain */
3667 did_paste = true;
3669 paste_head = tail;
3670 tail = &t->next;
3671 break;
3673 /* else fall through */
3674 default:
3675 tail = &t->next;
3676 if (!tok_type_(t->next, TOK_WHITESPACE))
3677 paste_head = tail;
3678 break;
3681 return did_paste;
3685 * expands to a list of tokens from %{x:y}
3687 static Token *expand_mmac_params_range(MMacro *mac, Token *tline, Token ***last)
3689 Token *t = tline, **tt, *tm, *head;
3690 char *pos;
3691 int fst, lst, j, i;
3693 pos = strchr(tline->text, ':');
3694 nasm_assert(pos);
3696 lst = atoi(pos + 1);
3697 fst = atoi(tline->text + 1);
3700 * only macros params are accounted so
3701 * if someone passes %0 -- we reject such
3702 * value(s)
3704 if (lst == 0 || fst == 0)
3705 goto err;
3707 /* the values should be sane */
3708 if ((fst > (int)mac->nparam || fst < (-(int)mac->nparam)) ||
3709 (lst > (int)mac->nparam || lst < (-(int)mac->nparam)))
3710 goto err;
3712 fst = fst < 0 ? fst + (int)mac->nparam + 1: fst;
3713 lst = lst < 0 ? lst + (int)mac->nparam + 1: lst;
3715 /* counted from zero */
3716 fst--, lst--;
3719 * it will be at least one token
3721 tm = mac->params[(fst + mac->rotate) % mac->nparam];
3722 t = new_Token(NULL, tm->type, tm->text, 0);
3723 head = t, tt = &t->next;
3724 if (fst < lst) {
3725 for (i = fst + 1; i <= lst; i++) {
3726 t = new_Token(NULL, TOK_OTHER, ",", 0);
3727 *tt = t, tt = &t->next;
3728 j = (i + mac->rotate) % mac->nparam;
3729 tm = mac->params[j];
3730 t = new_Token(NULL, tm->type, tm->text, 0);
3731 *tt = t, tt = &t->next;
3733 } else {
3734 for (i = fst - 1; i >= lst; i--) {
3735 t = new_Token(NULL, TOK_OTHER, ",", 0);
3736 *tt = t, tt = &t->next;
3737 j = (i + mac->rotate) % mac->nparam;
3738 tm = mac->params[j];
3739 t = new_Token(NULL, tm->type, tm->text, 0);
3740 *tt = t, tt = &t->next;
3744 *last = tt;
3745 return head;
3747 err:
3748 error(ERR_NONFATAL, "`%%{%s}': macro parameters out of range",
3749 &tline->text[1]);
3750 return tline;
3754 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3755 * %-n) and MMacro-local identifiers (%%foo) as well as
3756 * macro indirection (%[...]) and range (%{..:..}).
3758 static Token *expand_mmac_params(Token * tline)
3760 Token *t, *tt, **tail, *thead;
3761 bool changed = false;
3762 char *pos;
3764 tail = &thead;
3765 thead = NULL;
3767 while (tline) {
3768 if (tline->type == TOK_PREPROC_ID &&
3769 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text[2]) ||
3770 (tline->text[1] >= '0' && tline->text[1] <= '9') ||
3771 tline->text[1] == '%')) {
3772 char *text = NULL;
3773 int type = 0, cc; /* type = 0 to placate optimisers */
3774 char tmpbuf[30];
3775 unsigned int n;
3776 int i;
3777 MMacro *mac;
3779 t = tline;
3780 tline = tline->next;
3782 mac = istk->mstk;
3783 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3784 mac = mac->next_active;
3785 if (!mac) {
3786 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3787 } else {
3788 pos = strchr(t->text, ':');
3789 if (!pos) {
3790 switch (t->text[1]) {
3792 * We have to make a substitution of one of the
3793 * forms %1, %-1, %+1, %%foo, %0.
3795 case '0':
3796 type = TOK_NUMBER;
3797 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3798 text = nasm_strdup(tmpbuf);
3799 break;
3800 case '%':
3801 type = TOK_ID;
3802 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3803 mac->unique);
3804 text = nasm_strcat(tmpbuf, t->text + 2);
3805 break;
3806 case '-':
3807 n = atoi(t->text + 2) - 1;
3808 if (n >= mac->nparam)
3809 tt = NULL;
3810 else {
3811 if (mac->nparam > 1)
3812 n = (n + mac->rotate) % mac->nparam;
3813 tt = mac->params[n];
3815 cc = find_cc(tt);
3816 if (cc == -1) {
3817 error(ERR_NONFATAL,
3818 "macro parameter %d is not a condition code",
3819 n + 1);
3820 text = NULL;
3821 } else {
3822 type = TOK_ID;
3823 if (inverse_ccs[cc] == -1) {
3824 error(ERR_NONFATAL,
3825 "condition code `%s' is not invertible",
3826 conditions[cc]);
3827 text = NULL;
3828 } else
3829 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3831 break;
3832 case '+':
3833 n = atoi(t->text + 2) - 1;
3834 if (n >= mac->nparam)
3835 tt = NULL;
3836 else {
3837 if (mac->nparam > 1)
3838 n = (n + mac->rotate) % mac->nparam;
3839 tt = mac->params[n];
3841 cc = find_cc(tt);
3842 if (cc == -1) {
3843 error(ERR_NONFATAL,
3844 "macro parameter %d is not a condition code",
3845 n + 1);
3846 text = NULL;
3847 } else {
3848 type = TOK_ID;
3849 text = nasm_strdup(conditions[cc]);
3851 break;
3852 default:
3853 n = atoi(t->text + 1) - 1;
3854 if (n >= mac->nparam)
3855 tt = NULL;
3856 else {
3857 if (mac->nparam > 1)
3858 n = (n + mac->rotate) % mac->nparam;
3859 tt = mac->params[n];
3861 if (tt) {
3862 for (i = 0; i < mac->paramlen[n]; i++) {
3863 *tail = new_Token(NULL, tt->type, tt->text, 0);
3864 tail = &(*tail)->next;
3865 tt = tt->next;
3868 text = NULL; /* we've done it here */
3869 break;
3871 } else {
3873 * seems we have a parameters range here
3875 Token *head, **last;
3876 head = expand_mmac_params_range(mac, t, &last);
3877 if (head != t) {
3878 *tail = head;
3879 *last = tline;
3880 tline = head;
3881 text = NULL;
3885 if (!text) {
3886 delete_Token(t);
3887 } else {
3888 *tail = t;
3889 tail = &t->next;
3890 t->type = type;
3891 nasm_free(t->text);
3892 t->text = text;
3893 t->a.mac = NULL;
3895 changed = true;
3896 continue;
3897 } else if (tline->type == TOK_INDIRECT) {
3898 t = tline;
3899 tline = tline->next;
3900 tt = tokenize(t->text);
3901 tt = expand_mmac_params(tt);
3902 tt = expand_smacro(tt);
3903 *tail = tt;
3904 while (tt) {
3905 tt->a.mac = NULL; /* Necessary? */
3906 tail = &tt->next;
3907 tt = tt->next;
3909 delete_Token(t);
3910 changed = true;
3911 } else {
3912 t = *tail = tline;
3913 tline = tline->next;
3914 t->a.mac = NULL;
3915 tail = &t->next;
3918 *tail = NULL;
3920 if (changed)
3921 paste_tokens(&thead, false);
3923 return thead;
3927 * Expand all single-line macro calls made in the given line.
3928 * Return the expanded version of the line. The original is deemed
3929 * to be destroyed in the process. (In reality we'll just move
3930 * Tokens from input to output a lot of the time, rather than
3931 * actually bothering to destroy and replicate.)
3934 static Token *expand_smacro(Token * tline)
3936 Token *t, *tt, *mstart, **tail, *thead;
3937 SMacro *head = NULL, *m;
3938 Token **params;
3939 int *paramsize;
3940 unsigned int nparam, sparam;
3941 int brackets;
3942 Token *org_tline = tline;
3943 Context *ctx;
3944 const char *mname;
3945 int deadman = DEADMAN_LIMIT;
3946 bool expanded;
3949 * Trick: we should avoid changing the start token pointer since it can
3950 * be contained in "next" field of other token. Because of this
3951 * we allocate a copy of first token and work with it; at the end of
3952 * routine we copy it back
3954 if (org_tline) {
3955 tline = new_Token(org_tline->next, org_tline->type,
3956 org_tline->text, 0);
3957 tline->a.mac = org_tline->a.mac;
3958 nasm_free(org_tline->text);
3959 org_tline->text = NULL;
3962 expanded = true; /* Always expand %+ at least once */
3964 again:
3965 thead = NULL;
3966 tail = &thead;
3968 while (tline) { /* main token loop */
3969 if (!--deadman) {
3970 error(ERR_NONFATAL, "interminable macro recursion");
3971 goto err;
3974 if ((mname = tline->text)) {
3975 /* if this token is a local macro, look in local context */
3976 if (tline->type == TOK_ID) {
3977 head = (SMacro *)hash_findix(&smacros, mname);
3978 } else if (tline->type == TOK_PREPROC_ID) {
3979 ctx = get_ctx(mname, &mname, true);
3980 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
3981 } else
3982 head = NULL;
3985 * We've hit an identifier. As in is_mmacro below, we first
3986 * check whether the identifier is a single-line macro at
3987 * all, then think about checking for parameters if
3988 * necessary.
3990 list_for_each(m, head)
3991 if (!mstrcmp(m->name, mname, m->casesense))
3992 break;
3993 if (m) {
3994 mstart = tline;
3995 params = NULL;
3996 paramsize = NULL;
3997 if (m->nparam == 0) {
3999 * Simple case: the macro is parameterless. Discard the
4000 * one token that the macro call took, and push the
4001 * expansion back on the to-do stack.
4003 if (!m->expansion) {
4004 if (!strcmp("__FILE__", m->name)) {
4005 int32_t num = 0;
4006 char *file = NULL;
4007 src_get(&num, &file);
4008 tline->text = nasm_quote(file, strlen(file));
4009 tline->type = TOK_STRING;
4010 nasm_free(file);
4011 continue;
4013 if (!strcmp("__LINE__", m->name)) {
4014 nasm_free(tline->text);
4015 make_tok_num(tline, src_get_linnum());
4016 continue;
4018 if (!strcmp("__BITS__", m->name)) {
4019 nasm_free(tline->text);
4020 make_tok_num(tline, globalbits);
4021 continue;
4023 tline = delete_Token(tline);
4024 continue;
4026 } else {
4028 * Complicated case: at least one macro with this name
4029 * exists and takes parameters. We must find the
4030 * parameters in the call, count them, find the SMacro
4031 * that corresponds to that form of the macro call, and
4032 * substitute for the parameters when we expand. What a
4033 * pain.
4035 /*tline = tline->next;
4036 skip_white_(tline); */
4037 do {
4038 t = tline->next;
4039 while (tok_type_(t, TOK_SMAC_END)) {
4040 t->a.mac->in_progress = false;
4041 t->text = NULL;
4042 t = tline->next = delete_Token(t);
4044 tline = t;
4045 } while (tok_type_(tline, TOK_WHITESPACE));
4046 if (!tok_is_(tline, "(")) {
4048 * This macro wasn't called with parameters: ignore
4049 * the call. (Behaviour borrowed from gnu cpp.)
4051 tline = mstart;
4052 m = NULL;
4053 } else {
4054 int paren = 0;
4055 int white = 0;
4056 brackets = 0;
4057 nparam = 0;
4058 sparam = PARAM_DELTA;
4059 params = nasm_malloc(sparam * sizeof(Token *));
4060 params[0] = tline->next;
4061 paramsize = nasm_malloc(sparam * sizeof(int));
4062 paramsize[0] = 0;
4063 while (true) { /* parameter loop */
4065 * For some unusual expansions
4066 * which concatenates function call
4068 t = tline->next;
4069 while (tok_type_(t, TOK_SMAC_END)) {
4070 t->a.mac->in_progress = false;
4071 t->text = NULL;
4072 t = tline->next = delete_Token(t);
4074 tline = t;
4076 if (!tline) {
4077 error(ERR_NONFATAL,
4078 "macro call expects terminating `)'");
4079 break;
4081 if (tline->type == TOK_WHITESPACE
4082 && brackets <= 0) {
4083 if (paramsize[nparam])
4084 white++;
4085 else
4086 params[nparam] = tline->next;
4087 continue; /* parameter loop */
4089 if (tline->type == TOK_OTHER
4090 && tline->text[1] == 0) {
4091 char ch = tline->text[0];
4092 if (ch == ',' && !paren && brackets <= 0) {
4093 if (++nparam >= sparam) {
4094 sparam += PARAM_DELTA;
4095 params = nasm_realloc(params,
4096 sparam * sizeof(Token *));
4097 paramsize = nasm_realloc(paramsize,
4098 sparam * sizeof(int));
4100 params[nparam] = tline->next;
4101 paramsize[nparam] = 0;
4102 white = 0;
4103 continue; /* parameter loop */
4105 if (ch == '{' &&
4106 (brackets > 0 || (brackets == 0 &&
4107 !paramsize[nparam])))
4109 if (!(brackets++)) {
4110 params[nparam] = tline->next;
4111 continue; /* parameter loop */
4114 if (ch == '}' && brackets > 0)
4115 if (--brackets == 0) {
4116 brackets = -1;
4117 continue; /* parameter loop */
4119 if (ch == '(' && !brackets)
4120 paren++;
4121 if (ch == ')' && brackets <= 0)
4122 if (--paren < 0)
4123 break;
4125 if (brackets < 0) {
4126 brackets = 0;
4127 error(ERR_NONFATAL, "braces do not "
4128 "enclose all of macro parameter");
4130 paramsize[nparam] += white + 1;
4131 white = 0;
4132 } /* parameter loop */
4133 nparam++;
4134 while (m && (m->nparam != nparam ||
4135 mstrcmp(m->name, mname,
4136 m->casesense)))
4137 m = m->next;
4138 if (!m)
4139 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4140 "macro `%s' exists, "
4141 "but not taking %d parameters",
4142 mstart->text, nparam);
4145 if (m && m->in_progress)
4146 m = NULL;
4147 if (!m) { /* in progess or didn't find '(' or wrong nparam */
4149 * Design question: should we handle !tline, which
4150 * indicates missing ')' here, or expand those
4151 * macros anyway, which requires the (t) test a few
4152 * lines down?
4154 nasm_free(params);
4155 nasm_free(paramsize);
4156 tline = mstart;
4157 } else {
4159 * Expand the macro: we are placed on the last token of the
4160 * call, so that we can easily split the call from the
4161 * following tokens. We also start by pushing an SMAC_END
4162 * token for the cycle removal.
4164 t = tline;
4165 if (t) {
4166 tline = t->next;
4167 t->next = NULL;
4169 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4170 tt->a.mac = m;
4171 m->in_progress = true;
4172 tline = tt;
4173 list_for_each(t, m->expansion) {
4174 if (t->type >= TOK_SMAC_PARAM) {
4175 Token *pcopy = tline, **ptail = &pcopy;
4176 Token *ttt, *pt;
4177 int i;
4179 ttt = params[t->type - TOK_SMAC_PARAM];
4180 i = paramsize[t->type - TOK_SMAC_PARAM];
4181 while (--i >= 0) {
4182 pt = *ptail = new_Token(tline, ttt->type,
4183 ttt->text, 0);
4184 ptail = &pt->next;
4185 ttt = ttt->next;
4187 tline = pcopy;
4188 } else if (t->type == TOK_PREPROC_Q) {
4189 tt = new_Token(tline, TOK_ID, mname, 0);
4190 tline = tt;
4191 } else if (t->type == TOK_PREPROC_QQ) {
4192 tt = new_Token(tline, TOK_ID, m->name, 0);
4193 tline = tt;
4194 } else {
4195 tt = new_Token(tline, t->type, t->text, 0);
4196 tline = tt;
4201 * Having done that, get rid of the macro call, and clean
4202 * up the parameters.
4204 nasm_free(params);
4205 nasm_free(paramsize);
4206 free_tlist(mstart);
4207 expanded = true;
4208 continue; /* main token loop */
4213 if (tline->type == TOK_SMAC_END) {
4214 tline->a.mac->in_progress = false;
4215 tline = delete_Token(tline);
4216 } else {
4217 t = *tail = tline;
4218 tline = tline->next;
4219 t->a.mac = NULL;
4220 t->next = NULL;
4221 tail = &t->next;
4226 * Now scan the entire line and look for successive TOK_IDs that resulted
4227 * after expansion (they can't be produced by tokenize()). The successive
4228 * TOK_IDs should be concatenated.
4229 * Also we look for %+ tokens and concatenate the tokens before and after
4230 * them (without white spaces in between).
4232 if (expanded && paste_tokens(&thead, true)) {
4234 * If we concatenated something, *and* we had previously expanded
4235 * an actual macro, scan the lines again for macros...
4237 tline = thead;
4238 expanded = false;
4239 goto again;
4242 err:
4243 if (org_tline) {
4244 if (thead) {
4245 *org_tline = *thead;
4246 /* since we just gave text to org_line, don't free it */
4247 thead->text = NULL;
4248 delete_Token(thead);
4249 } else {
4250 /* the expression expanded to empty line;
4251 we can't return NULL for some reasons
4252 we just set the line to a single WHITESPACE token. */
4253 memset(org_tline, 0, sizeof(*org_tline));
4254 org_tline->text = NULL;
4255 org_tline->type = TOK_WHITESPACE;
4257 thead = org_tline;
4260 return thead;
4264 * Similar to expand_smacro but used exclusively with macro identifiers
4265 * right before they are fetched in. The reason is that there can be
4266 * identifiers consisting of several subparts. We consider that if there
4267 * are more than one element forming the name, user wants a expansion,
4268 * otherwise it will be left as-is. Example:
4270 * %define %$abc cde
4272 * the identifier %$abc will be left as-is so that the handler for %define
4273 * will suck it and define the corresponding value. Other case:
4275 * %define _%$abc cde
4277 * In this case user wants name to be expanded *before* %define starts
4278 * working, so we'll expand %$abc into something (if it has a value;
4279 * otherwise it will be left as-is) then concatenate all successive
4280 * PP_IDs into one.
4282 static Token *expand_id(Token * tline)
4284 Token *cur, *oldnext = NULL;
4286 if (!tline || !tline->next)
4287 return tline;
4289 cur = tline;
4290 while (cur->next &&
4291 (cur->next->type == TOK_ID ||
4292 cur->next->type == TOK_PREPROC_ID
4293 || cur->next->type == TOK_NUMBER))
4294 cur = cur->next;
4296 /* If identifier consists of just one token, don't expand */
4297 if (cur == tline)
4298 return tline;
4300 if (cur) {
4301 oldnext = cur->next; /* Detach the tail past identifier */
4302 cur->next = NULL; /* so that expand_smacro stops here */
4305 tline = expand_smacro(tline);
4307 if (cur) {
4308 /* expand_smacro possibly changhed tline; re-scan for EOL */
4309 cur = tline;
4310 while (cur && cur->next)
4311 cur = cur->next;
4312 if (cur)
4313 cur->next = oldnext;
4316 return tline;
4320 * Determine whether the given line constitutes a multi-line macro
4321 * call, and return the MMacro structure called if so. Doesn't have
4322 * to check for an initial label - that's taken care of in
4323 * expand_mmacro - but must check numbers of parameters. Guaranteed
4324 * to be called with tline->type == TOK_ID, so the putative macro
4325 * name is easy to find.
4327 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4329 MMacro *head, *m;
4330 Token **params;
4331 int nparam;
4333 head = (MMacro *) hash_findix(&mmacros, tline->text);
4336 * Efficiency: first we see if any macro exists with the given
4337 * name. If not, we can return NULL immediately. _Then_ we
4338 * count the parameters, and then we look further along the
4339 * list if necessary to find the proper MMacro.
4341 list_for_each(m, head)
4342 if (!mstrcmp(m->name, tline->text, m->casesense))
4343 break;
4344 if (!m)
4345 return NULL;
4348 * OK, we have a potential macro. Count and demarcate the
4349 * parameters.
4351 count_mmac_params(tline->next, &nparam, &params);
4354 * So we know how many parameters we've got. Find the MMacro
4355 * structure that handles this number.
4357 while (m) {
4358 if (m->nparam_min <= nparam
4359 && (m->plus || nparam <= m->nparam_max)) {
4361 * This one is right. Just check if cycle removal
4362 * prohibits us using it before we actually celebrate...
4364 if (m->in_progress > m->max_depth) {
4365 if (m->max_depth > 0) {
4366 error(ERR_WARNING,
4367 "reached maximum recursion depth of %i",
4368 m->max_depth);
4370 nasm_free(params);
4371 return NULL;
4374 * It's right, and we can use it. Add its default
4375 * parameters to the end of our list if necessary.
4377 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4378 params =
4379 nasm_realloc(params,
4380 ((m->nparam_min + m->ndefs +
4381 1) * sizeof(*params)));
4382 while (nparam < m->nparam_min + m->ndefs) {
4383 params[nparam] = m->defaults[nparam - m->nparam_min];
4384 nparam++;
4388 * If we've gone over the maximum parameter count (and
4389 * we're in Plus mode), ignore parameters beyond
4390 * nparam_max.
4392 if (m->plus && nparam > m->nparam_max)
4393 nparam = m->nparam_max;
4395 * Then terminate the parameter list, and leave.
4397 if (!params) { /* need this special case */
4398 params = nasm_malloc(sizeof(*params));
4399 nparam = 0;
4401 params[nparam] = NULL;
4402 *params_array = params;
4403 return m;
4406 * This one wasn't right: look for the next one with the
4407 * same name.
4409 list_for_each(m, m->next)
4410 if (!mstrcmp(m->name, tline->text, m->casesense))
4411 break;
4415 * After all that, we didn't find one with the right number of
4416 * parameters. Issue a warning, and fail to expand the macro.
4418 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4419 "macro `%s' exists, but not taking %d parameters",
4420 tline->text, nparam);
4421 nasm_free(params);
4422 return NULL;
4427 * Save MMacro invocation specific fields in
4428 * preparation for a recursive macro expansion
4430 static void push_mmacro(MMacro *m)
4432 MMacroInvocation *i;
4434 i = nasm_malloc(sizeof(MMacroInvocation));
4435 i->prev = m->prev;
4436 i->params = m->params;
4437 i->iline = m->iline;
4438 i->nparam = m->nparam;
4439 i->rotate = m->rotate;
4440 i->paramlen = m->paramlen;
4441 i->unique = m->unique;
4442 i->condcnt = m->condcnt;
4443 m->prev = i;
4448 * Restore MMacro invocation specific fields that were
4449 * saved during a previous recursive macro expansion
4451 static void pop_mmacro(MMacro *m)
4453 MMacroInvocation *i;
4455 if (m->prev) {
4456 i = m->prev;
4457 m->prev = i->prev;
4458 m->params = i->params;
4459 m->iline = i->iline;
4460 m->nparam = i->nparam;
4461 m->rotate = i->rotate;
4462 m->paramlen = i->paramlen;
4463 m->unique = i->unique;
4464 m->condcnt = i->condcnt;
4465 nasm_free(i);
4471 * Expand the multi-line macro call made by the given line, if
4472 * there is one to be expanded. If there is, push the expansion on
4473 * istk->expansion and return 1. Otherwise return 0.
4475 static int expand_mmacro(Token * tline)
4477 Token *startline = tline;
4478 Token *label = NULL;
4479 int dont_prepend = 0;
4480 Token **params, *t, *mtok, *tt;
4481 MMacro *m;
4482 Line *l, *ll;
4483 int i, nparam, *paramlen;
4484 const char *mname;
4486 t = tline;
4487 skip_white_(t);
4488 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4489 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4490 return 0;
4491 mtok = t;
4492 m = is_mmacro(t, &params);
4493 if (m) {
4494 mname = t->text;
4495 } else {
4496 Token *last;
4498 * We have an id which isn't a macro call. We'll assume
4499 * it might be a label; we'll also check to see if a
4500 * colon follows it. Then, if there's another id after
4501 * that lot, we'll check it again for macro-hood.
4503 label = last = t;
4504 t = t->next;
4505 if (tok_type_(t, TOK_WHITESPACE))
4506 last = t, t = t->next;
4507 if (tok_is_(t, ":")) {
4508 dont_prepend = 1;
4509 last = t, t = t->next;
4510 if (tok_type_(t, TOK_WHITESPACE))
4511 last = t, t = t->next;
4513 if (!tok_type_(t, TOK_ID) || !(m = is_mmacro(t, &params)))
4514 return 0;
4515 last->next = NULL;
4516 mname = t->text;
4517 tline = t;
4521 * Fix up the parameters: this involves stripping leading and
4522 * trailing whitespace, then stripping braces if they are
4523 * present.
4525 for (nparam = 0; params[nparam]; nparam++) ;
4526 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4528 for (i = 0; params[i]; i++) {
4529 int brace = false;
4530 int comma = (!m->plus || i < nparam - 1);
4532 t = params[i];
4533 skip_white_(t);
4534 if (tok_is_(t, "{"))
4535 t = t->next, brace = true, comma = false;
4536 params[i] = t;
4537 paramlen[i] = 0;
4538 while (t) {
4539 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4540 break; /* ... because we have hit a comma */
4541 if (comma && t->type == TOK_WHITESPACE
4542 && tok_is_(t->next, ","))
4543 break; /* ... or a space then a comma */
4544 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4545 break; /* ... or a brace */
4546 t = t->next;
4547 paramlen[i]++;
4552 * OK, we have a MMacro structure together with a set of
4553 * parameters. We must now go through the expansion and push
4554 * copies of each Line on to istk->expansion. Substitution of
4555 * parameter tokens and macro-local tokens doesn't get done
4556 * until the single-line macro substitution process; this is
4557 * because delaying them allows us to change the semantics
4558 * later through %rotate.
4560 * First, push an end marker on to istk->expansion, mark this
4561 * macro as in progress, and set up its invocation-specific
4562 * variables.
4564 ll = nasm_malloc(sizeof(Line));
4565 ll->next = istk->expansion;
4566 ll->finishes = m;
4567 ll->first = NULL;
4568 istk->expansion = ll;
4571 * Save the previous MMacro expansion in the case of
4572 * macro recursion
4574 if (m->max_depth && m->in_progress)
4575 push_mmacro(m);
4577 m->in_progress ++;
4578 m->params = params;
4579 m->iline = tline;
4580 m->nparam = nparam;
4581 m->rotate = 0;
4582 m->paramlen = paramlen;
4583 m->unique = unique++;
4584 m->lineno = 0;
4585 m->condcnt = 0;
4587 m->next_active = istk->mstk;
4588 istk->mstk = m;
4590 list_for_each(l, m->expansion) {
4591 Token **tail;
4593 ll = nasm_malloc(sizeof(Line));
4594 ll->finishes = NULL;
4595 ll->next = istk->expansion;
4596 istk->expansion = ll;
4597 tail = &ll->first;
4599 list_for_each(t, l->first) {
4600 Token *x = t;
4601 switch (t->type) {
4602 case TOK_PREPROC_Q:
4603 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4604 break;
4605 case TOK_PREPROC_QQ:
4606 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4607 break;
4608 case TOK_PREPROC_ID:
4609 if (t->text[1] == '0' && t->text[2] == '0') {
4610 dont_prepend = -1;
4611 x = label;
4612 if (!x)
4613 continue;
4615 /* fall through */
4616 default:
4617 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4618 break;
4620 tail = &tt->next;
4622 *tail = NULL;
4626 * If we had a label, push it on as the first line of
4627 * the macro expansion.
4629 if (label) {
4630 if (dont_prepend < 0)
4631 free_tlist(startline);
4632 else {
4633 ll = nasm_malloc(sizeof(Line));
4634 ll->finishes = NULL;
4635 ll->next = istk->expansion;
4636 istk->expansion = ll;
4637 ll->first = startline;
4638 if (!dont_prepend) {
4639 while (label->next)
4640 label = label->next;
4641 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4646 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4648 return 1;
4651 /* The function that actually does the error reporting */
4652 static void verror(int severity, const char *fmt, va_list arg)
4654 char buff[1024];
4656 vsnprintf(buff, sizeof(buff), fmt, arg);
4658 if (istk && istk->mstk && istk->mstk->name)
4659 nasm_error(severity, "(%s:%d) %s", istk->mstk->name,
4660 istk->mstk->lineno, buff);
4661 else
4662 nasm_error(severity, "%s", buff);
4666 * Since preprocessor always operate only on the line that didn't
4667 * arrived yet, we should always use ERR_OFFBY1.
4669 static void error(int severity, const char *fmt, ...)
4671 va_list arg;
4673 /* If we're in a dead branch of IF or something like it, ignore the error */
4674 if (istk && istk->conds && !emitting(istk->conds->state))
4675 return;
4677 va_start(arg, fmt);
4678 verror(severity, fmt, arg);
4679 va_end(arg);
4683 * Because %else etc are evaluated in the state context
4684 * of the previous branch, errors might get lost with error():
4685 * %if 0 ... %else trailing garbage ... %endif
4686 * So %else etc should report errors with this function.
4688 static void error_precond(int severity, const char *fmt, ...)
4690 va_list arg;
4692 /* Only ignore the error if it's really in a dead branch */
4693 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4694 return;
4696 va_start(arg, fmt);
4697 verror(severity, fmt, arg);
4698 va_end(arg);
4701 static void
4702 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
4704 Token *t;
4706 cstk = NULL;
4707 istk = nasm_malloc(sizeof(Include));
4708 istk->next = NULL;
4709 istk->conds = NULL;
4710 istk->expansion = NULL;
4711 istk->mstk = NULL;
4712 istk->fp = fopen(file, "r");
4713 istk->fname = NULL;
4714 src_set_fname(nasm_strdup(file));
4715 src_set_linnum(0);
4716 istk->lineinc = 1;
4717 if (!istk->fp)
4718 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4719 file);
4720 defining = NULL;
4721 nested_mac_count = 0;
4722 nested_rep_count = 0;
4723 init_macros();
4724 unique = 0;
4725 if (tasm_compatible_mode) {
4726 stdmacpos = nasm_stdmac;
4727 } else {
4728 stdmacpos = nasm_stdmac_after_tasm;
4730 any_extrastdmac = extrastdmac && *extrastdmac;
4731 do_predef = true;
4732 list = listgen;
4735 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4736 * The caller, however, will also pass in 3 for preprocess-only so
4737 * we can set __PASS__ accordingly.
4739 pass = apass > 2 ? 2 : apass;
4741 dephead = deptail = deplist;
4742 if (deplist) {
4743 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4744 sl->next = NULL;
4745 strcpy(sl->str, file);
4746 *deptail = sl;
4747 deptail = &sl->next;
4751 * Define the __PASS__ macro. This is defined here unlike
4752 * all the other builtins, because it is special -- it varies between
4753 * passes.
4755 t = nasm_malloc(sizeof(*t));
4756 t->next = NULL;
4757 make_tok_num(t, apass);
4758 t->a.mac = NULL;
4759 define_smacro(NULL, "__PASS__", true, 0, t);
4762 static char *pp_getline(void)
4764 char *line;
4765 Token *tline;
4767 while (1) {
4769 * Fetch a tokenized line, either from the macro-expansion
4770 * buffer or from the input file.
4772 tline = NULL;
4773 while (istk->expansion && istk->expansion->finishes) {
4774 Line *l = istk->expansion;
4775 if (!l->finishes->name && l->finishes->in_progress > 1) {
4776 Line *ll;
4779 * This is a macro-end marker for a macro with no
4780 * name, which means it's not really a macro at all
4781 * but a %rep block, and the `in_progress' field is
4782 * more than 1, meaning that we still need to
4783 * repeat. (1 means the natural last repetition; 0
4784 * means termination by %exitrep.) We have
4785 * therefore expanded up to the %endrep, and must
4786 * push the whole block on to the expansion buffer
4787 * again. We don't bother to remove the macro-end
4788 * marker: we'd only have to generate another one
4789 * if we did.
4791 l->finishes->in_progress--;
4792 list_for_each(l, l->finishes->expansion) {
4793 Token *t, *tt, **tail;
4795 ll = nasm_malloc(sizeof(Line));
4796 ll->next = istk->expansion;
4797 ll->finishes = NULL;
4798 ll->first = NULL;
4799 tail = &ll->first;
4801 list_for_each(t, l->first) {
4802 if (t->text || t->type == TOK_WHITESPACE) {
4803 tt = *tail = new_Token(NULL, t->type, t->text, 0);
4804 tail = &tt->next;
4808 istk->expansion = ll;
4810 } else {
4812 * Check whether a `%rep' was started and not ended
4813 * within this macro expansion. This can happen and
4814 * should be detected. It's a fatal error because
4815 * I'm too confused to work out how to recover
4816 * sensibly from it.
4818 if (defining) {
4819 if (defining->name)
4820 error(ERR_PANIC,
4821 "defining with name in expansion");
4822 else if (istk->mstk->name)
4823 error(ERR_FATAL,
4824 "`%%rep' without `%%endrep' within"
4825 " expansion of macro `%s'",
4826 istk->mstk->name);
4830 * FIXME: investigate the relationship at this point between
4831 * istk->mstk and l->finishes
4834 MMacro *m = istk->mstk;
4835 istk->mstk = m->next_active;
4836 if (m->name) {
4838 * This was a real macro call, not a %rep, and
4839 * therefore the parameter information needs to
4840 * be freed.
4842 if (m->prev) {
4843 pop_mmacro(m);
4844 l->finishes->in_progress --;
4845 } else {
4846 nasm_free(m->params);
4847 free_tlist(m->iline);
4848 nasm_free(m->paramlen);
4849 l->finishes->in_progress = 0;
4851 } else
4852 free_mmacro(m);
4854 istk->expansion = l->next;
4855 nasm_free(l);
4856 list->downlevel(LIST_MACRO);
4859 while (1) { /* until we get a line we can use */
4861 if (istk->expansion) { /* from a macro expansion */
4862 char *p;
4863 Line *l = istk->expansion;
4864 if (istk->mstk)
4865 istk->mstk->lineno++;
4866 tline = l->first;
4867 istk->expansion = l->next;
4868 nasm_free(l);
4869 p = detoken(tline, false);
4870 list->line(LIST_MACRO, p);
4871 nasm_free(p);
4872 break;
4874 line = read_line();
4875 if (line) { /* from the current input file */
4876 line = prepreproc(line);
4877 tline = tokenize(line);
4878 nasm_free(line);
4879 break;
4882 * The current file has ended; work down the istk
4885 Include *i = istk;
4886 fclose(i->fp);
4887 if (i->conds)
4888 error(ERR_FATAL,
4889 "expected `%%endif' before end of file");
4890 /* only set line and file name if there's a next node */
4891 if (i->next) {
4892 src_set_linnum(i->lineno);
4893 nasm_free(src_set_fname(i->fname));
4895 istk = i->next;
4896 list->downlevel(LIST_INCLUDE);
4897 nasm_free(i);
4898 if (!istk)
4899 return NULL;
4900 if (istk->expansion && istk->expansion->finishes)
4901 break;
4906 * We must expand MMacro parameters and MMacro-local labels
4907 * _before_ we plunge into directive processing, to cope
4908 * with things like `%define something %1' such as STRUC
4909 * uses. Unless we're _defining_ a MMacro, in which case
4910 * those tokens should be left alone to go into the
4911 * definition; and unless we're in a non-emitting
4912 * condition, in which case we don't want to meddle with
4913 * anything.
4915 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4916 && !(istk->mstk && !istk->mstk->in_progress)) {
4917 tline = expand_mmac_params(tline);
4921 * Check the line to see if it's a preprocessor directive.
4923 if (do_directive(tline) == DIRECTIVE_FOUND) {
4924 continue;
4925 } else if (defining) {
4927 * We're defining a multi-line macro. We emit nothing
4928 * at all, and just
4929 * shove the tokenized line on to the macro definition.
4931 Line *l = nasm_malloc(sizeof(Line));
4932 l->next = defining->expansion;
4933 l->first = tline;
4934 l->finishes = NULL;
4935 defining->expansion = l;
4936 continue;
4937 } else if (istk->conds && !emitting(istk->conds->state)) {
4939 * We're in a non-emitting branch of a condition block.
4940 * Emit nothing at all, not even a blank line: when we
4941 * emerge from the condition we'll give a line-number
4942 * directive so we keep our place correctly.
4944 free_tlist(tline);
4945 continue;
4946 } else if (istk->mstk && !istk->mstk->in_progress) {
4948 * We're in a %rep block which has been terminated, so
4949 * we're walking through to the %endrep without
4950 * emitting anything. Emit nothing at all, not even a
4951 * blank line: when we emerge from the %rep block we'll
4952 * give a line-number directive so we keep our place
4953 * correctly.
4955 free_tlist(tline);
4956 continue;
4957 } else {
4958 tline = expand_smacro(tline);
4959 if (!expand_mmacro(tline)) {
4961 * De-tokenize the line again, and emit it.
4963 line = detoken(tline, true);
4964 free_tlist(tline);
4965 break;
4966 } else {
4967 continue; /* expand_mmacro calls free_tlist */
4972 return line;
4975 static void pp_cleanup(int pass)
4977 if (defining) {
4978 if (defining->name) {
4979 error(ERR_NONFATAL,
4980 "end of file while still defining macro `%s'",
4981 defining->name);
4982 } else {
4983 error(ERR_NONFATAL, "end of file while still in %%rep");
4986 free_mmacro(defining);
4987 defining = NULL;
4989 while (cstk)
4990 ctx_pop();
4991 free_macros();
4992 while (istk) {
4993 Include *i = istk;
4994 istk = istk->next;
4995 fclose(i->fp);
4996 nasm_free(i->fname);
4997 nasm_free(i);
4999 while (cstk)
5000 ctx_pop();
5001 nasm_free(src_set_fname(NULL));
5002 if (pass == 0) {
5003 IncPath *i;
5004 free_llist(predef);
5005 delete_Blocks();
5006 while ((i = ipath)) {
5007 ipath = i->next;
5008 if (i->path)
5009 nasm_free(i->path);
5010 nasm_free(i);
5015 void pp_include_path(char *path)
5017 IncPath *i;
5019 i = nasm_malloc(sizeof(IncPath));
5020 i->path = path ? nasm_strdup(path) : NULL;
5021 i->next = NULL;
5023 if (ipath) {
5024 IncPath *j = ipath;
5025 while (j->next)
5026 j = j->next;
5027 j->next = i;
5028 } else {
5029 ipath = i;
5033 void pp_pre_include(char *fname)
5035 Token *inc, *space, *name;
5036 Line *l;
5038 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
5039 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
5040 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
5042 l = nasm_malloc(sizeof(Line));
5043 l->next = predef;
5044 l->first = inc;
5045 l->finishes = NULL;
5046 predef = l;
5049 void pp_pre_define(char *definition)
5051 Token *def, *space;
5052 Line *l;
5053 char *equals;
5055 equals = strchr(definition, '=');
5056 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5057 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
5058 if (equals)
5059 *equals = ' ';
5060 space->next = tokenize(definition);
5061 if (equals)
5062 *equals = '=';
5064 l = nasm_malloc(sizeof(Line));
5065 l->next = predef;
5066 l->first = def;
5067 l->finishes = NULL;
5068 predef = l;
5071 void pp_pre_undefine(char *definition)
5073 Token *def, *space;
5074 Line *l;
5076 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5077 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
5078 space->next = tokenize(definition);
5080 l = nasm_malloc(sizeof(Line));
5081 l->next = predef;
5082 l->first = def;
5083 l->finishes = NULL;
5084 predef = l;
5088 * Added by Keith Kanios:
5090 * This function is used to assist with "runtime" preprocessor
5091 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5093 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5094 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5097 void pp_runtime(char *definition)
5099 Token *def;
5101 def = tokenize(definition);
5102 if (do_directive(def) == NO_DIRECTIVE_FOUND)
5103 free_tlist(def);
5107 void pp_extra_stdmac(macros_t *macros)
5109 extrastdmac = macros;
5112 static void make_tok_num(Token * tok, int64_t val)
5114 char numbuf[20];
5115 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
5116 tok->text = nasm_strdup(numbuf);
5117 tok->type = TOK_NUMBER;
5120 Preproc nasmpp = {
5121 pp_reset,
5122 pp_getline,
5123 pp_cleanup