sectalign: Implement on/off mode
[nasm-cyr.git] / preproc.c
blobf04434b9afcf4fb4758a289a217db9372bc7ff15
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)
329 /* max reps */
330 #define REP_LIMIT ((INT64_C(1) << 62))
333 * Condition codes. Note that we use c_ prefix not C_ because C_ is
334 * used in nasm.h for the "real" condition codes. At _this_ level,
335 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
336 * ones, so we need a different enum...
338 static const char * const conditions[] = {
339 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
340 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
341 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
343 enum pp_conds {
344 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
345 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
346 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
347 c_none = -1
349 static const enum pp_conds inverse_ccs[] = {
350 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
351 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,
352 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
356 * Directive names.
358 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
359 static int is_condition(enum preproc_token arg)
361 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
364 /* For TASM compatibility we need to be able to recognise TASM compatible
365 * conditional compilation directives. Using the NASM pre-processor does
366 * not work, so we look for them specifically from the following list and
367 * then jam in the equivalent NASM directive into the input stream.
370 enum {
371 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
372 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
375 static const char * const tasm_directives[] = {
376 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
377 "ifndef", "include", "local"
380 static int StackSize = 4;
381 static char *StackPointer = "ebp";
382 static int ArgOffset = 8;
383 static int LocalOffset = 0;
385 static Context *cstk;
386 static Include *istk;
387 static IncPath *ipath = NULL;
389 static int pass; /* HACK: pass 0 = generate dependencies only */
390 static StrList **dephead, **deptail; /* Dependency list */
392 static uint64_t unique; /* unique identifier numbers */
394 static Line *predef = NULL;
395 static bool do_predef;
397 static ListGen *list;
400 * The current set of multi-line macros we have defined.
402 static struct hash_table mmacros;
405 * The current set of single-line macros we have defined.
407 static struct hash_table smacros;
410 * The multi-line macro we are currently defining, or the %rep
411 * block we are currently reading, if any.
413 static MMacro *defining;
415 static uint64_t nested_mac_count;
416 static uint64_t nested_rep_count;
419 * The number of macro parameters to allocate space for at a time.
421 #define PARAM_DELTA 16
424 * The standard macro set: defined in macros.c in the array nasm_stdmac.
425 * This gives our position in the macro set, when we're processing it.
427 static macros_t *stdmacpos;
430 * The extra standard macros that come from the object format, if
431 * any.
433 static macros_t *extrastdmac = NULL;
434 static bool any_extrastdmac;
437 * Tokens are allocated in blocks to improve speed
439 #define TOKEN_BLOCKSIZE 4096
440 static Token *freeTokens = NULL;
441 struct Blocks {
442 Blocks *next;
443 void *chunk;
446 static Blocks blocks = { NULL, NULL };
449 * Forward declarations.
451 static Token *expand_mmac_params(Token * tline);
452 static Token *expand_smacro(Token * tline);
453 static Token *expand_id(Token * tline);
454 static Context *get_ctx(const char *name, const char **namep,
455 bool all_contexts);
456 static void make_tok_num(Token * tok, int64_t val);
457 static void error(int severity, const char *fmt, ...);
458 static void error_precond(int severity, const char *fmt, ...);
459 static void *new_Block(size_t size);
460 static void delete_Blocks(void);
461 static Token *new_Token(Token * next, enum pp_token_type type,
462 const char *text, int txtlen);
463 static Token *delete_Token(Token * t);
466 * Macros for safe checking of token pointers, avoid *(NULL)
468 #define tok_type_(x,t) ((x) && (x)->type == (t))
469 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
470 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
471 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
474 * nasm_unquote with error if the string contains NUL characters.
475 * If the string contains NUL characters, issue an error and return
476 * the C len, i.e. truncate at the NUL.
478 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
480 size_t len = nasm_unquote(qstr, NULL);
481 size_t clen = strlen(qstr);
483 if (len != clen)
484 error(ERR_NONFATAL, "NUL character in `%s' directive",
485 pp_directives[directive]);
487 return clen;
491 * Handle TASM specific directives, which do not contain a % in
492 * front of them. We do it here because I could not find any other
493 * place to do it for the moment, and it is a hack (ideally it would
494 * be nice to be able to use the NASM pre-processor to do it).
496 static char *check_tasm_directive(char *line)
498 int32_t i, j, k, m, len;
499 char *p, *q, *oldline, oldchar;
501 p = nasm_skip_spaces(line);
503 /* Binary search for the directive name */
504 i = -1;
505 j = ARRAY_SIZE(tasm_directives);
506 q = nasm_skip_word(p);
507 len = q - p;
508 if (len) {
509 oldchar = p[len];
510 p[len] = 0;
511 while (j - i > 1) {
512 k = (j + i) / 2;
513 m = nasm_stricmp(p, tasm_directives[k]);
514 if (m == 0) {
515 /* We have found a directive, so jam a % in front of it
516 * so that NASM will then recognise it as one if it's own.
518 p[len] = oldchar;
519 len = strlen(p);
520 oldline = line;
521 line = nasm_malloc(len + 2);
522 line[0] = '%';
523 if (k == TM_IFDIFI) {
525 * NASM does not recognise IFDIFI, so we convert
526 * it to %if 0. This is not used in NASM
527 * compatible code, but does need to parse for the
528 * TASM macro package.
530 strcpy(line + 1, "if 0");
531 } else {
532 memcpy(line + 1, p, len + 1);
534 nasm_free(oldline);
535 return line;
536 } else if (m < 0) {
537 j = k;
538 } else
539 i = k;
541 p[len] = oldchar;
543 return line;
547 * The pre-preprocessing stage... This function translates line
548 * number indications as they emerge from GNU cpp (`# lineno "file"
549 * flags') into NASM preprocessor line number indications (`%line
550 * lineno file').
552 static char *prepreproc(char *line)
554 int lineno, fnlen;
555 char *fname, *oldline;
557 if (line[0] == '#' && line[1] == ' ') {
558 oldline = line;
559 fname = oldline + 2;
560 lineno = atoi(fname);
561 fname += strspn(fname, "0123456789 ");
562 if (*fname == '"')
563 fname++;
564 fnlen = strcspn(fname, "\"");
565 line = nasm_malloc(20 + fnlen);
566 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
567 nasm_free(oldline);
569 if (tasm_compatible_mode)
570 return check_tasm_directive(line);
571 return line;
575 * Free a linked list of tokens.
577 static void free_tlist(Token * list)
579 while (list)
580 list = delete_Token(list);
584 * Free a linked list of lines.
586 static void free_llist(Line * list)
588 Line *l, *tmp;
589 list_for_each_safe(l, tmp, list) {
590 free_tlist(l->first);
591 nasm_free(l);
596 * Free an MMacro
598 static void free_mmacro(MMacro * m)
600 nasm_free(m->name);
601 free_tlist(m->dlist);
602 nasm_free(m->defaults);
603 free_llist(m->expansion);
604 nasm_free(m);
608 * Free all currently defined macros, and free the hash tables
610 static void free_smacro_table(struct hash_table *smt)
612 SMacro *s, *tmp;
613 const char *key;
614 struct hash_tbl_node *it = NULL;
616 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
617 nasm_free((void *)key);
618 list_for_each_safe(s, tmp, s) {
619 nasm_free(s->name);
620 free_tlist(s->expansion);
621 nasm_free(s);
624 hash_free(smt);
627 static void free_mmacro_table(struct hash_table *mmt)
629 MMacro *m, *tmp;
630 const char *key;
631 struct hash_tbl_node *it = NULL;
633 it = NULL;
634 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
635 nasm_free((void *)key);
636 list_for_each_safe(m ,tmp, m)
637 free_mmacro(m);
639 hash_free(mmt);
642 static void free_macros(void)
644 free_smacro_table(&smacros);
645 free_mmacro_table(&mmacros);
649 * Initialize the hash tables
651 static void init_macros(void)
653 hash_init(&smacros, HASH_LARGE);
654 hash_init(&mmacros, HASH_LARGE);
658 * Pop the context stack.
660 static void ctx_pop(void)
662 Context *c = cstk;
664 cstk = cstk->next;
665 free_smacro_table(&c->localmac);
666 nasm_free(c->name);
667 nasm_free(c);
671 * Search for a key in the hash index; adding it if necessary
672 * (in which case we initialize the data pointer to NULL.)
674 static void **
675 hash_findi_add(struct hash_table *hash, const char *str)
677 struct hash_insert hi;
678 void **r;
679 char *strx;
681 r = hash_findi(hash, str, &hi);
682 if (r)
683 return r;
685 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
686 return hash_add(&hi, strx, NULL);
690 * Like hash_findi, but returns the data element rather than a pointer
691 * to it. Used only when not adding a new element, hence no third
692 * argument.
694 static void *
695 hash_findix(struct hash_table *hash, const char *str)
697 void **p;
699 p = hash_findi(hash, str, NULL);
700 return p ? *p : NULL;
704 * read line from standart macros set,
705 * if there no more left -- return NULL
707 static char *line_from_stdmac(void)
709 unsigned char c;
710 const unsigned char *p = stdmacpos;
711 char *line, *q;
712 size_t len = 0;
714 if (!stdmacpos)
715 return NULL;
717 while ((c = *p++)) {
718 if (c >= 0x80)
719 len += pp_directives_len[c - 0x80] + 1;
720 else
721 len++;
724 line = nasm_malloc(len + 1);
725 q = line;
726 while ((c = *stdmacpos++)) {
727 if (c >= 0x80) {
728 memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
729 q += pp_directives_len[c - 0x80];
730 *q++ = ' ';
731 } else {
732 *q++ = c;
735 stdmacpos = p;
736 *q = '\0';
738 if (!*stdmacpos) {
739 /* This was the last of the standard macro chain... */
740 stdmacpos = NULL;
741 if (any_extrastdmac) {
742 stdmacpos = extrastdmac;
743 any_extrastdmac = false;
744 } else if (do_predef) {
745 Line *pd, *l;
746 Token *head, **tail, *t;
749 * Nasty hack: here we push the contents of
750 * `predef' on to the top-level expansion stack,
751 * since this is the most convenient way to
752 * implement the pre-include and pre-define
753 * features.
755 list_for_each(pd, predef) {
756 head = NULL;
757 tail = &head;
758 list_for_each(t, pd->first) {
759 *tail = new_Token(NULL, t->type, t->text, 0);
760 tail = &(*tail)->next;
763 l = nasm_malloc(sizeof(Line));
764 l->next = istk->expansion;
765 l->first = head;
766 l->finishes = NULL;
768 istk->expansion = l;
770 do_predef = false;
774 return line;
777 #define BUF_DELTA 512
779 * Read a line from the top file in istk, handling multiple CR/LFs
780 * at the end of the line read, and handling spurious ^Zs. Will
781 * return lines from the standard macro set if this has not already
782 * been done.
784 static char *read_line(void)
786 char *buffer, *p, *q;
787 int bufsize, continued_count;
790 * standart macros set (predefined) goes first
792 p = line_from_stdmac();
793 if (p)
794 return p;
797 * regular read from a file
799 bufsize = BUF_DELTA;
800 buffer = nasm_malloc(BUF_DELTA);
801 p = buffer;
802 continued_count = 0;
803 while (1) {
804 q = fgets(p, bufsize - (p - buffer), istk->fp);
805 if (!q)
806 break;
807 p += strlen(p);
808 if (p > buffer && p[-1] == '\n') {
810 * Convert backslash-CRLF line continuation sequences into
811 * nothing at all (for DOS and Windows)
813 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
814 p -= 3;
815 *p = 0;
816 continued_count++;
819 * Also convert backslash-LF line continuation sequences into
820 * nothing at all (for Unix)
822 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
823 p -= 2;
824 *p = 0;
825 continued_count++;
826 } else {
827 break;
830 if (p - buffer > bufsize - 10) {
831 int32_t offset = p - buffer;
832 bufsize += BUF_DELTA;
833 buffer = nasm_realloc(buffer, bufsize);
834 p = buffer + offset; /* prevent stale-pointer problems */
838 if (!q && p == buffer) {
839 nasm_free(buffer);
840 return NULL;
843 src_set_linnum(src_get_linnum() + istk->lineinc +
844 (continued_count * istk->lineinc));
847 * Play safe: remove CRs as well as LFs, if any of either are
848 * present at the end of the line.
850 while (--p >= buffer && (*p == '\n' || *p == '\r'))
851 *p = '\0';
854 * Handle spurious ^Z, which may be inserted into source files
855 * by some file transfer utilities.
857 buffer[strcspn(buffer, "\032")] = '\0';
859 list->line(LIST_READ, buffer);
861 return buffer;
865 * Tokenize a line of text. This is a very simple process since we
866 * don't need to parse the value out of e.g. numeric tokens: we
867 * simply split one string into many.
869 static Token *tokenize(char *line)
871 char c, *p = line;
872 enum pp_token_type type;
873 Token *list = NULL;
874 Token *t, **tail = &list;
876 while (*line) {
877 p = line;
878 if (*p == '%') {
879 p++;
880 if (*p == '+' && !nasm_isdigit(p[1])) {
881 p++;
882 type = TOK_PASTE;
883 } else if (nasm_isdigit(*p) ||
884 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
885 do {
886 p++;
888 while (nasm_isdigit(*p));
889 type = TOK_PREPROC_ID;
890 } else if (*p == '{') {
891 p++;
892 while (*p && *p != '}') {
893 p[-1] = *p;
894 p++;
896 p[-1] = '\0';
897 if (*p)
898 p++;
899 type = TOK_PREPROC_ID;
900 } else if (*p == '[') {
901 int lvl = 1;
902 line += 2; /* Skip the leading %[ */
903 p++;
904 while (lvl && (c = *p++)) {
905 switch (c) {
906 case ']':
907 lvl--;
908 break;
909 case '%':
910 if (*p == '[')
911 lvl++;
912 break;
913 case '\'':
914 case '\"':
915 case '`':
916 p = nasm_skip_string(p - 1) + 1;
917 break;
918 default:
919 break;
922 p--;
923 if (*p)
924 *p++ = '\0';
925 if (lvl)
926 error(ERR_NONFATAL, "unterminated %[ construct");
927 type = TOK_INDIRECT;
928 } else if (*p == '?') {
929 type = TOK_PREPROC_Q; /* %? */
930 p++;
931 if (*p == '?') {
932 type = TOK_PREPROC_QQ; /* %?? */
933 p++;
935 } else if (*p == '!') {
936 type = TOK_PREPROC_ID;
937 p++;
938 if (isidchar(*p)) {
939 do {
940 p++;
942 while (isidchar(*p));
943 } else if (*p == '\'' || *p == '\"' || *p == '`') {
944 p = nasm_skip_string(p);
945 if (*p)
946 p++;
947 else
948 error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
949 } else {
950 /* %! without string or identifier */
951 type = TOK_OTHER; /* Legacy behavior... */
953 } else if (isidchar(*p) ||
954 ((*p == '!' || *p == '%' || *p == '$') &&
955 isidchar(p[1]))) {
956 do {
957 p++;
959 while (isidchar(*p));
960 type = TOK_PREPROC_ID;
961 } else {
962 type = TOK_OTHER;
963 if (*p == '%')
964 p++;
966 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
967 type = TOK_ID;
968 p++;
969 while (*p && isidchar(*p))
970 p++;
971 } else if (*p == '\'' || *p == '"' || *p == '`') {
973 * A string token.
975 type = TOK_STRING;
976 p = nasm_skip_string(p);
978 if (*p) {
979 p++;
980 } else {
981 error(ERR_WARNING|ERR_PASS1, "unterminated string");
982 /* Handling unterminated strings by UNV */
983 /* type = -1; */
985 } else if (p[0] == '$' && p[1] == '$') {
986 type = TOK_OTHER; /* TOKEN_BASE */
987 p += 2;
988 } else if (isnumstart(*p)) {
989 bool is_hex = false;
990 bool is_float = false;
991 bool has_e = false;
992 char c, *r;
995 * A numeric token.
998 if (*p == '$') {
999 p++;
1000 is_hex = true;
1003 for (;;) {
1004 c = *p++;
1006 if (!is_hex && (c == 'e' || c == 'E')) {
1007 has_e = true;
1008 if (*p == '+' || *p == '-') {
1010 * e can only be followed by +/- if it is either a
1011 * prefixed hex number or a floating-point number
1013 p++;
1014 is_float = true;
1016 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
1017 is_hex = true;
1018 } else if (c == 'P' || c == 'p') {
1019 is_float = true;
1020 if (*p == '+' || *p == '-')
1021 p++;
1022 } else if (isnumchar(c) || c == '_')
1023 ; /* just advance */
1024 else if (c == '.') {
1026 * we need to deal with consequences of the legacy
1027 * parser, like "1.nolist" being two tokens
1028 * (TOK_NUMBER, TOK_ID) here; at least give it
1029 * a shot for now. In the future, we probably need
1030 * a flex-based scanner with proper pattern matching
1031 * to do it as well as it can be done. Nothing in
1032 * the world is going to help the person who wants
1033 * 0x123.p16 interpreted as two tokens, though.
1035 r = p;
1036 while (*r == '_')
1037 r++;
1039 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
1040 (!is_hex && (*r == 'e' || *r == 'E')) ||
1041 (*r == 'p' || *r == 'P')) {
1042 p = r;
1043 is_float = true;
1044 } else
1045 break; /* Terminate the token */
1046 } else
1047 break;
1049 p--; /* Point to first character beyond number */
1051 if (p == line+1 && *line == '$') {
1052 type = TOK_OTHER; /* TOKEN_HERE */
1053 } else {
1054 if (has_e && !is_hex) {
1055 /* 1e13 is floating-point, but 1e13h is not */
1056 is_float = true;
1059 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1061 } else if (nasm_isspace(*p)) {
1062 type = TOK_WHITESPACE;
1063 p = nasm_skip_spaces(p);
1065 * Whitespace just before end-of-line is discarded by
1066 * pretending it's a comment; whitespace just before a
1067 * comment gets lumped into the comment.
1069 if (!*p || *p == ';') {
1070 type = TOK_COMMENT;
1071 while (*p)
1072 p++;
1074 } else if (*p == ';') {
1075 type = TOK_COMMENT;
1076 while (*p)
1077 p++;
1078 } else {
1080 * Anything else is an operator of some kind. We check
1081 * for all the double-character operators (>>, <<, //,
1082 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1083 * else is a single-character operator.
1085 type = TOK_OTHER;
1086 if ((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[0] == '&' && p[1] == '&') ||
1095 (p[0] == '|' && p[1] == '|') ||
1096 (p[0] == '^' && p[1] == '^')) {
1097 p++;
1099 p++;
1102 /* Handling unterminated string by UNV */
1103 /*if (type == -1)
1105 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1106 t->text[p-line] = *line;
1107 tail = &t->next;
1109 else */
1110 if (type != TOK_COMMENT) {
1111 *tail = t = new_Token(NULL, type, line, p - line);
1112 tail = &t->next;
1114 line = p;
1116 return list;
1120 * this function allocates a new managed block of memory and
1121 * returns a pointer to the block. The managed blocks are
1122 * deleted only all at once by the delete_Blocks function.
1124 static void *new_Block(size_t size)
1126 Blocks *b = &blocks;
1128 /* first, get to the end of the linked list */
1129 while (b->next)
1130 b = b->next;
1131 /* now allocate the requested chunk */
1132 b->chunk = nasm_malloc(size);
1134 /* now allocate a new block for the next request */
1135 b->next = nasm_malloc(sizeof(Blocks));
1136 /* and initialize the contents of the new block */
1137 b->next->next = NULL;
1138 b->next->chunk = NULL;
1139 return b->chunk;
1143 * this function deletes all managed blocks of memory
1145 static void delete_Blocks(void)
1147 Blocks *a, *b = &blocks;
1150 * keep in mind that the first block, pointed to by blocks
1151 * is a static and not dynamically allocated, so we don't
1152 * free it.
1154 while (b) {
1155 if (b->chunk)
1156 nasm_free(b->chunk);
1157 a = b;
1158 b = b->next;
1159 if (a != &blocks)
1160 nasm_free(a);
1165 * this function creates a new Token and passes a pointer to it
1166 * back to the caller. It sets the type and text elements, and
1167 * also the a.mac and next elements to NULL.
1169 static Token *new_Token(Token * next, enum pp_token_type type,
1170 const char *text, int txtlen)
1172 Token *t;
1173 int i;
1175 if (!freeTokens) {
1176 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1177 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1178 freeTokens[i].next = &freeTokens[i + 1];
1179 freeTokens[i].next = NULL;
1181 t = freeTokens;
1182 freeTokens = t->next;
1183 t->next = next;
1184 t->a.mac = NULL;
1185 t->type = type;
1186 if (type == TOK_WHITESPACE || !text) {
1187 t->text = NULL;
1188 } else {
1189 if (txtlen == 0)
1190 txtlen = strlen(text);
1191 t->text = nasm_malloc(txtlen+1);
1192 memcpy(t->text, text, txtlen);
1193 t->text[txtlen] = '\0';
1195 return t;
1198 static Token *delete_Token(Token * t)
1200 Token *next = t->next;
1201 nasm_free(t->text);
1202 t->next = freeTokens;
1203 freeTokens = t;
1204 return next;
1208 * Convert a line of tokens back into text.
1209 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1210 * will be transformed into ..@ctxnum.xxx
1212 static char *detoken(Token * tlist, bool expand_locals)
1214 Token *t;
1215 char *line, *p;
1216 const char *q;
1217 int len = 0;
1219 list_for_each(t, tlist) {
1220 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1221 char *v;
1222 char *q = t->text;
1224 v = t->text + 2;
1225 if (*v == '\'' || *v == '\"' || *v == '`') {
1226 size_t len = nasm_unquote(v, NULL);
1227 size_t clen = strlen(v);
1229 if (len != clen) {
1230 error(ERR_NONFATAL | ERR_PASS1,
1231 "NUL character in %! string");
1232 v = NULL;
1236 if (v) {
1237 char *p = getenv(v);
1238 if (!p) {
1239 error(ERR_NONFATAL | ERR_PASS1,
1240 "nonexistent environment variable `%s'", v);
1241 p = "";
1243 t->text = nasm_strdup(p);
1245 nasm_free(q);
1248 /* Expand local macros here and not during preprocessing */
1249 if (expand_locals &&
1250 t->type == TOK_PREPROC_ID && t->text &&
1251 t->text[0] == '%' && t->text[1] == '$') {
1252 const char *q;
1253 char *p;
1254 Context *ctx = get_ctx(t->text, &q, false);
1255 if (ctx) {
1256 char buffer[40];
1257 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1258 p = nasm_strcat(buffer, q);
1259 nasm_free(t->text);
1260 t->text = p;
1263 if (t->type == TOK_WHITESPACE)
1264 len++;
1265 else if (t->text)
1266 len += strlen(t->text);
1269 p = line = nasm_malloc(len + 1);
1271 list_for_each(t, tlist) {
1272 if (t->type == TOK_WHITESPACE) {
1273 *p++ = ' ';
1274 } else if (t->text) {
1275 q = t->text;
1276 while (*q)
1277 *p++ = *q++;
1280 *p = '\0';
1282 return line;
1286 * A scanner, suitable for use by the expression evaluator, which
1287 * operates on a line of Tokens. Expects a pointer to a pointer to
1288 * the first token in the line to be passed in as its private_data
1289 * field.
1291 * FIX: This really needs to be unified with stdscan.
1293 static int ppscan(void *private_data, struct tokenval *tokval)
1295 Token **tlineptr = private_data;
1296 Token *tline;
1297 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1299 do {
1300 tline = *tlineptr;
1301 *tlineptr = tline ? tline->next : NULL;
1302 } while (tline && (tline->type == TOK_WHITESPACE ||
1303 tline->type == TOK_COMMENT));
1305 if (!tline)
1306 return tokval->t_type = TOKEN_EOS;
1308 tokval->t_charptr = tline->text;
1310 if (tline->text[0] == '$' && !tline->text[1])
1311 return tokval->t_type = TOKEN_HERE;
1312 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1313 return tokval->t_type = TOKEN_BASE;
1315 if (tline->type == TOK_ID) {
1316 p = tokval->t_charptr = tline->text;
1317 if (p[0] == '$') {
1318 tokval->t_charptr++;
1319 return tokval->t_type = TOKEN_ID;
1322 for (r = p, s = ourcopy; *r; r++) {
1323 if (r >= p+MAX_KEYWORD)
1324 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1325 *s++ = nasm_tolower(*r);
1327 *s = '\0';
1328 /* right, so we have an identifier sitting in temp storage. now,
1329 * is it actually a register or instruction name, or what? */
1330 return nasm_token_hash(ourcopy, tokval);
1333 if (tline->type == TOK_NUMBER) {
1334 bool rn_error;
1335 tokval->t_integer = readnum(tline->text, &rn_error);
1336 tokval->t_charptr = tline->text;
1337 if (rn_error)
1338 return tokval->t_type = TOKEN_ERRNUM;
1339 else
1340 return tokval->t_type = TOKEN_NUM;
1343 if (tline->type == TOK_FLOAT) {
1344 return tokval->t_type = TOKEN_FLOAT;
1347 if (tline->type == TOK_STRING) {
1348 char bq, *ep;
1350 bq = tline->text[0];
1351 tokval->t_charptr = tline->text;
1352 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1354 if (ep[0] != bq || ep[1] != '\0')
1355 return tokval->t_type = TOKEN_ERRSTR;
1356 else
1357 return tokval->t_type = TOKEN_STR;
1360 if (tline->type == TOK_OTHER) {
1361 if (!strcmp(tline->text, "<<"))
1362 return tokval->t_type = TOKEN_SHL;
1363 if (!strcmp(tline->text, ">>"))
1364 return tokval->t_type = TOKEN_SHR;
1365 if (!strcmp(tline->text, "//"))
1366 return tokval->t_type = TOKEN_SDIV;
1367 if (!strcmp(tline->text, "%%"))
1368 return tokval->t_type = TOKEN_SMOD;
1369 if (!strcmp(tline->text, "=="))
1370 return tokval->t_type = TOKEN_EQ;
1371 if (!strcmp(tline->text, "<>"))
1372 return tokval->t_type = TOKEN_NE;
1373 if (!strcmp(tline->text, "!="))
1374 return tokval->t_type = TOKEN_NE;
1375 if (!strcmp(tline->text, "<="))
1376 return tokval->t_type = TOKEN_LE;
1377 if (!strcmp(tline->text, ">="))
1378 return tokval->t_type = TOKEN_GE;
1379 if (!strcmp(tline->text, "&&"))
1380 return tokval->t_type = TOKEN_DBL_AND;
1381 if (!strcmp(tline->text, "^^"))
1382 return tokval->t_type = TOKEN_DBL_XOR;
1383 if (!strcmp(tline->text, "||"))
1384 return tokval->t_type = TOKEN_DBL_OR;
1388 * We have no other options: just return the first character of
1389 * the token text.
1391 return tokval->t_type = tline->text[0];
1395 * Compare a string to the name of an existing macro; this is a
1396 * simple wrapper which calls either strcmp or nasm_stricmp
1397 * depending on the value of the `casesense' parameter.
1399 static int mstrcmp(const char *p, const char *q, bool casesense)
1401 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1405 * Compare a string to the name of an existing macro; this is a
1406 * simple wrapper which calls either strcmp or nasm_stricmp
1407 * depending on the value of the `casesense' parameter.
1409 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1411 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1415 * Return the Context structure associated with a %$ token. Return
1416 * NULL, having _already_ reported an error condition, if the
1417 * context stack isn't deep enough for the supplied number of $
1418 * signs.
1419 * If all_contexts == true, contexts that enclose current are
1420 * also scanned for such smacro, until it is found; if not -
1421 * only the context that directly results from the number of $'s
1422 * in variable's name.
1424 * If "namep" is non-NULL, set it to the pointer to the macro name
1425 * tail, i.e. the part beyond %$...
1427 static Context *get_ctx(const char *name, const char **namep,
1428 bool all_contexts)
1430 Context *ctx;
1431 SMacro *m;
1432 int i;
1434 if (namep)
1435 *namep = name;
1437 if (!name || name[0] != '%' || name[1] != '$')
1438 return NULL;
1440 if (!cstk) {
1441 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1442 return NULL;
1445 name += 2;
1446 ctx = cstk;
1447 i = 0;
1448 while (ctx && *name == '$') {
1449 name++;
1450 i++;
1451 ctx = ctx->next;
1453 if (!ctx) {
1454 error(ERR_NONFATAL, "`%s': context stack is only"
1455 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1456 return NULL;
1459 if (namep)
1460 *namep = name;
1462 if (!all_contexts)
1463 return ctx;
1466 * NOTE: In 2.10 we will not need lookup in extarnal
1467 * contexts, so this is a gentle way to inform users
1468 * about their source code need to be updated
1471 /* first round -- check the current context */
1472 m = hash_findix(&ctx->localmac, name);
1473 while (m) {
1474 if (!mstrcmp(m->name, name, m->casesense))
1475 return ctx;
1476 m = m->next;
1479 /* second round - external contexts */
1480 while ((ctx = ctx->next)) {
1481 /* Search for this smacro in found context */
1482 m = hash_findix(&ctx->localmac, name);
1483 while (m) {
1484 if (!mstrcmp(m->name, name, m->casesense)) {
1485 /* NOTE: obsolete since 2.10 */
1486 static int once = 0;
1487 if (!once) {
1488 error(ERR_WARNING, "context-local macro expansion"
1489 " to outer contexts will be deprecated"
1490 " starting in NASM 2.10, please update your"
1491 " code accordingly");
1492 once = 1;
1494 error(ERR_WARNING, "`%s': context through macro expansion", name);
1495 return ctx;
1497 m = m->next;
1501 return NULL;
1505 * Check to see if a file is already in a string list
1507 static bool in_list(const StrList *list, const char *str)
1509 while (list) {
1510 if (!strcmp(list->str, str))
1511 return true;
1512 list = list->next;
1514 return false;
1518 * Open an include file. This routine must always return a valid
1519 * file pointer if it returns - it's responsible for throwing an
1520 * ERR_FATAL and bombing out completely if not. It should also try
1521 * the include path one by one until it finds the file or reaches
1522 * the end of the path.
1524 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1525 bool missing_ok)
1527 FILE *fp;
1528 char *prefix = "";
1529 IncPath *ip = ipath;
1530 int len = strlen(file);
1531 size_t prefix_len = 0;
1532 StrList *sl;
1534 while (1) {
1535 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1536 memcpy(sl->str, prefix, prefix_len);
1537 memcpy(sl->str+prefix_len, file, len+1);
1538 fp = fopen(sl->str, "r");
1539 if (fp && dhead && !in_list(*dhead, sl->str)) {
1540 sl->next = NULL;
1541 **dtail = sl;
1542 *dtail = &sl->next;
1543 } else {
1544 nasm_free(sl);
1546 if (fp)
1547 return fp;
1548 if (!ip) {
1549 if (!missing_ok)
1550 break;
1551 prefix = NULL;
1552 } else {
1553 prefix = ip->path;
1554 ip = ip->next;
1556 if (prefix) {
1557 prefix_len = strlen(prefix);
1558 } else {
1559 /* -MG given and file not found */
1560 if (dhead && !in_list(*dhead, file)) {
1561 sl = nasm_malloc(len+1+sizeof sl->next);
1562 sl->next = NULL;
1563 strcpy(sl->str, file);
1564 **dtail = sl;
1565 *dtail = &sl->next;
1567 return NULL;
1571 error(ERR_FATAL, "unable to open include file `%s'", file);
1572 return NULL;
1576 * Determine if we should warn on defining a single-line macro of
1577 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1578 * return true if _any_ single-line macro of that name is defined.
1579 * Otherwise, will return true if a single-line macro with either
1580 * `nparam' or no parameters is defined.
1582 * If a macro with precisely the right number of parameters is
1583 * defined, or nparam is -1, the address of the definition structure
1584 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1585 * is NULL, no action will be taken regarding its contents, and no
1586 * error will occur.
1588 * Note that this is also called with nparam zero to resolve
1589 * `ifdef'.
1591 * If you already know which context macro belongs to, you can pass
1592 * the context pointer as first parameter; if you won't but name begins
1593 * with %$ the context will be automatically computed. If all_contexts
1594 * is true, macro will be searched in outer contexts as well.
1596 static bool
1597 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1598 bool nocase)
1600 struct hash_table *smtbl;
1601 SMacro *m;
1603 if (ctx) {
1604 smtbl = &ctx->localmac;
1605 } else if (name[0] == '%' && name[1] == '$') {
1606 if (cstk)
1607 ctx = get_ctx(name, &name, false);
1608 if (!ctx)
1609 return false; /* got to return _something_ */
1610 smtbl = &ctx->localmac;
1611 } else {
1612 smtbl = &smacros;
1614 m = (SMacro *) hash_findix(smtbl, name);
1616 while (m) {
1617 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1618 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1619 if (defn) {
1620 if (nparam == (int) m->nparam || nparam == -1)
1621 *defn = m;
1622 else
1623 *defn = NULL;
1625 return true;
1627 m = m->next;
1630 return false;
1634 * Count and mark off the parameters in a multi-line macro call.
1635 * This is called both from within the multi-line macro expansion
1636 * code, and also to mark off the default parameters when provided
1637 * in a %macro definition line.
1639 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1641 int paramsize, brace;
1643 *nparam = paramsize = 0;
1644 *params = NULL;
1645 while (t) {
1646 /* +1: we need space for the final NULL */
1647 if (*nparam+1 >= paramsize) {
1648 paramsize += PARAM_DELTA;
1649 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1651 skip_white_(t);
1652 brace = false;
1653 if (tok_is_(t, "{"))
1654 brace = true;
1655 (*params)[(*nparam)++] = t;
1656 while (tok_isnt_(t, brace ? "}" : ","))
1657 t = t->next;
1658 if (t) { /* got a comma/brace */
1659 t = t->next;
1660 if (brace) {
1662 * Now we've found the closing brace, look further
1663 * for the comma.
1665 skip_white_(t);
1666 if (tok_isnt_(t, ",")) {
1667 error(ERR_NONFATAL,
1668 "braces do not enclose all of macro parameter");
1669 while (tok_isnt_(t, ","))
1670 t = t->next;
1672 if (t)
1673 t = t->next; /* eat the comma */
1680 * Determine whether one of the various `if' conditions is true or
1681 * not.
1683 * We must free the tline we get passed.
1685 static bool if_condition(Token * tline, enum preproc_token ct)
1687 enum pp_conditional i = PP_COND(ct);
1688 bool j;
1689 Token *t, *tt, **tptr, *origline;
1690 struct tokenval tokval;
1691 expr *evalresult;
1692 enum pp_token_type needtype;
1693 char *p;
1695 origline = tline;
1697 switch (i) {
1698 case PPC_IFCTX:
1699 j = false; /* have we matched yet? */
1700 while (true) {
1701 skip_white_(tline);
1702 if (!tline)
1703 break;
1704 if (tline->type != TOK_ID) {
1705 error(ERR_NONFATAL,
1706 "`%s' expects context identifiers", pp_directives[ct]);
1707 free_tlist(origline);
1708 return -1;
1710 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1711 j = true;
1712 tline = tline->next;
1714 break;
1716 case PPC_IFDEF:
1717 j = false; /* have we matched yet? */
1718 while (tline) {
1719 skip_white_(tline);
1720 if (!tline || (tline->type != TOK_ID &&
1721 (tline->type != TOK_PREPROC_ID ||
1722 tline->text[1] != '$'))) {
1723 error(ERR_NONFATAL,
1724 "`%s' expects macro identifiers", pp_directives[ct]);
1725 goto fail;
1727 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1728 j = true;
1729 tline = tline->next;
1731 break;
1733 case PPC_IFENV:
1734 tline = expand_smacro(tline);
1735 j = false; /* have we matched yet? */
1736 while (tline) {
1737 skip_white_(tline);
1738 if (!tline || (tline->type != TOK_ID &&
1739 tline->type != TOK_STRING &&
1740 (tline->type != TOK_PREPROC_ID ||
1741 tline->text[1] != '!'))) {
1742 error(ERR_NONFATAL,
1743 "`%s' expects environment variable names",
1744 pp_directives[ct]);
1745 goto fail;
1747 p = tline->text;
1748 if (tline->type == TOK_PREPROC_ID)
1749 p += 2; /* Skip leading %! */
1750 if (*p == '\'' || *p == '\"' || *p == '`')
1751 nasm_unquote_cstr(p, ct);
1752 if (getenv(p))
1753 j = true;
1754 tline = tline->next;
1756 break;
1758 case PPC_IFIDN:
1759 case PPC_IFIDNI:
1760 tline = expand_smacro(tline);
1761 t = tt = tline;
1762 while (tok_isnt_(tt, ","))
1763 tt = tt->next;
1764 if (!tt) {
1765 error(ERR_NONFATAL,
1766 "`%s' expects two comma-separated arguments",
1767 pp_directives[ct]);
1768 goto fail;
1770 tt = tt->next;
1771 j = true; /* assume equality unless proved not */
1772 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1773 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1774 error(ERR_NONFATAL, "`%s': more than one comma on line",
1775 pp_directives[ct]);
1776 goto fail;
1778 if (t->type == TOK_WHITESPACE) {
1779 t = t->next;
1780 continue;
1782 if (tt->type == TOK_WHITESPACE) {
1783 tt = tt->next;
1784 continue;
1786 if (tt->type != t->type) {
1787 j = false; /* found mismatching tokens */
1788 break;
1790 /* When comparing strings, need to unquote them first */
1791 if (t->type == TOK_STRING) {
1792 size_t l1 = nasm_unquote(t->text, NULL);
1793 size_t l2 = nasm_unquote(tt->text, NULL);
1795 if (l1 != l2) {
1796 j = false;
1797 break;
1799 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1800 j = false;
1801 break;
1803 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1804 j = false; /* found mismatching tokens */
1805 break;
1808 t = t->next;
1809 tt = tt->next;
1811 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1812 j = false; /* trailing gunk on one end or other */
1813 break;
1815 case PPC_IFMACRO:
1817 bool found = false;
1818 MMacro searching, *mmac;
1820 skip_white_(tline);
1821 tline = expand_id(tline);
1822 if (!tok_type_(tline, TOK_ID)) {
1823 error(ERR_NONFATAL,
1824 "`%s' expects a macro name", pp_directives[ct]);
1825 goto fail;
1827 searching.name = nasm_strdup(tline->text);
1828 searching.casesense = true;
1829 searching.plus = false;
1830 searching.nolist = false;
1831 searching.in_progress = 0;
1832 searching.max_depth = 0;
1833 searching.rep_nest = NULL;
1834 searching.nparam_min = 0;
1835 searching.nparam_max = INT_MAX;
1836 tline = expand_smacro(tline->next);
1837 skip_white_(tline);
1838 if (!tline) {
1839 } else if (!tok_type_(tline, TOK_NUMBER)) {
1840 error(ERR_NONFATAL,
1841 "`%s' expects a parameter count or nothing",
1842 pp_directives[ct]);
1843 } else {
1844 searching.nparam_min = searching.nparam_max =
1845 readnum(tline->text, &j);
1846 if (j)
1847 error(ERR_NONFATAL,
1848 "unable to parse parameter count `%s'",
1849 tline->text);
1851 if (tline && tok_is_(tline->next, "-")) {
1852 tline = tline->next->next;
1853 if (tok_is_(tline, "*"))
1854 searching.nparam_max = INT_MAX;
1855 else if (!tok_type_(tline, TOK_NUMBER))
1856 error(ERR_NONFATAL,
1857 "`%s' expects a parameter count after `-'",
1858 pp_directives[ct]);
1859 else {
1860 searching.nparam_max = readnum(tline->text, &j);
1861 if (j)
1862 error(ERR_NONFATAL,
1863 "unable to parse parameter count `%s'",
1864 tline->text);
1865 if (searching.nparam_min > searching.nparam_max)
1866 error(ERR_NONFATAL,
1867 "minimum parameter count exceeds maximum");
1870 if (tline && tok_is_(tline->next, "+")) {
1871 tline = tline->next;
1872 searching.plus = true;
1874 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1875 while (mmac) {
1876 if (!strcmp(mmac->name, searching.name) &&
1877 (mmac->nparam_min <= searching.nparam_max
1878 || searching.plus)
1879 && (searching.nparam_min <= mmac->nparam_max
1880 || mmac->plus)) {
1881 found = true;
1882 break;
1884 mmac = mmac->next;
1886 if (tline && tline->next)
1887 error(ERR_WARNING|ERR_PASS1,
1888 "trailing garbage after %%ifmacro ignored");
1889 nasm_free(searching.name);
1890 j = found;
1891 break;
1894 case PPC_IFID:
1895 needtype = TOK_ID;
1896 goto iftype;
1897 case PPC_IFNUM:
1898 needtype = TOK_NUMBER;
1899 goto iftype;
1900 case PPC_IFSTR:
1901 needtype = TOK_STRING;
1902 goto iftype;
1904 iftype:
1905 t = tline = expand_smacro(tline);
1907 while (tok_type_(t, TOK_WHITESPACE) ||
1908 (needtype == TOK_NUMBER &&
1909 tok_type_(t, TOK_OTHER) &&
1910 (t->text[0] == '-' || t->text[0] == '+') &&
1911 !t->text[1]))
1912 t = t->next;
1914 j = tok_type_(t, needtype);
1915 break;
1917 case PPC_IFTOKEN:
1918 t = tline = expand_smacro(tline);
1919 while (tok_type_(t, TOK_WHITESPACE))
1920 t = t->next;
1922 j = false;
1923 if (t) {
1924 t = t->next; /* Skip the actual token */
1925 while (tok_type_(t, TOK_WHITESPACE))
1926 t = t->next;
1927 j = !t; /* Should be nothing left */
1929 break;
1931 case PPC_IFEMPTY:
1932 t = tline = expand_smacro(tline);
1933 while (tok_type_(t, TOK_WHITESPACE))
1934 t = t->next;
1936 j = !t; /* Should be empty */
1937 break;
1939 case PPC_IF:
1940 t = tline = expand_smacro(tline);
1941 tptr = &t;
1942 tokval.t_type = TOKEN_INVALID;
1943 evalresult = evaluate(ppscan, tptr, &tokval,
1944 NULL, pass | CRITICAL, error, NULL);
1945 if (!evalresult)
1946 return -1;
1947 if (tokval.t_type)
1948 error(ERR_WARNING|ERR_PASS1,
1949 "trailing garbage after expression ignored");
1950 if (!is_simple(evalresult)) {
1951 error(ERR_NONFATAL,
1952 "non-constant value given to `%s'", pp_directives[ct]);
1953 goto fail;
1955 j = reloc_value(evalresult) != 0;
1956 break;
1958 default:
1959 error(ERR_FATAL,
1960 "preprocessor directive `%s' not yet implemented",
1961 pp_directives[ct]);
1962 goto fail;
1965 free_tlist(origline);
1966 return j ^ PP_NEGATIVE(ct);
1968 fail:
1969 free_tlist(origline);
1970 return -1;
1974 * Common code for defining an smacro
1976 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1977 int nparam, Token *expansion)
1979 SMacro *smac, **smhead;
1980 struct hash_table *smtbl;
1982 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1983 if (!smac) {
1984 error(ERR_WARNING|ERR_PASS1,
1985 "single-line macro `%s' defined both with and"
1986 " without parameters", mname);
1988 * Some instances of the old code considered this a failure,
1989 * some others didn't. What is the right thing to do here?
1991 free_tlist(expansion);
1992 return false; /* Failure */
1993 } else {
1995 * We're redefining, so we have to take over an
1996 * existing SMacro structure. This means freeing
1997 * what was already in it.
1999 nasm_free(smac->name);
2000 free_tlist(smac->expansion);
2002 } else {
2003 smtbl = ctx ? &ctx->localmac : &smacros;
2004 smhead = (SMacro **) hash_findi_add(smtbl, mname);
2005 smac = nasm_malloc(sizeof(SMacro));
2006 smac->next = *smhead;
2007 *smhead = smac;
2009 smac->name = nasm_strdup(mname);
2010 smac->casesense = casesense;
2011 smac->nparam = nparam;
2012 smac->expansion = expansion;
2013 smac->in_progress = false;
2014 return true; /* Success */
2018 * Undefine an smacro
2020 static void undef_smacro(Context *ctx, const char *mname)
2022 SMacro **smhead, *s, **sp;
2023 struct hash_table *smtbl;
2025 smtbl = ctx ? &ctx->localmac : &smacros;
2026 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
2028 if (smhead) {
2030 * We now have a macro name... go hunt for it.
2032 sp = smhead;
2033 while ((s = *sp) != NULL) {
2034 if (!mstrcmp(s->name, mname, s->casesense)) {
2035 *sp = s->next;
2036 nasm_free(s->name);
2037 free_tlist(s->expansion);
2038 nasm_free(s);
2039 } else {
2040 sp = &s->next;
2047 * Parse a mmacro specification.
2049 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
2051 bool err;
2053 tline = tline->next;
2054 skip_white_(tline);
2055 tline = expand_id(tline);
2056 if (!tok_type_(tline, TOK_ID)) {
2057 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
2058 return false;
2061 def->prev = NULL;
2062 def->name = nasm_strdup(tline->text);
2063 def->plus = false;
2064 def->nolist = false;
2065 def->in_progress = 0;
2066 def->rep_nest = NULL;
2067 def->nparam_min = 0;
2068 def->nparam_max = 0;
2070 tline = expand_smacro(tline->next);
2071 skip_white_(tline);
2072 if (!tok_type_(tline, TOK_NUMBER)) {
2073 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
2074 } else {
2075 def->nparam_min = def->nparam_max =
2076 readnum(tline->text, &err);
2077 if (err)
2078 error(ERR_NONFATAL,
2079 "unable to parse parameter count `%s'", tline->text);
2081 if (tline && tok_is_(tline->next, "-")) {
2082 tline = tline->next->next;
2083 if (tok_is_(tline, "*")) {
2084 def->nparam_max = INT_MAX;
2085 } else if (!tok_type_(tline, TOK_NUMBER)) {
2086 error(ERR_NONFATAL,
2087 "`%s' expects a parameter count after `-'", directive);
2088 } else {
2089 def->nparam_max = readnum(tline->text, &err);
2090 if (err) {
2091 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
2092 tline->text);
2094 if (def->nparam_min > def->nparam_max) {
2095 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
2099 if (tline && tok_is_(tline->next, "+")) {
2100 tline = tline->next;
2101 def->plus = true;
2103 if (tline && tok_type_(tline->next, TOK_ID) &&
2104 !nasm_stricmp(tline->next->text, ".nolist")) {
2105 tline = tline->next;
2106 def->nolist = true;
2110 * Handle default parameters.
2112 if (tline && tline->next) {
2113 def->dlist = tline->next;
2114 tline->next = NULL;
2115 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
2116 } else {
2117 def->dlist = NULL;
2118 def->defaults = NULL;
2120 def->expansion = NULL;
2122 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2123 !def->plus)
2124 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2125 "too many default macro parameters");
2127 return true;
2132 * Decode a size directive
2134 static int parse_size(const char *str) {
2135 static const char *size_names[] =
2136 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2137 static const int sizes[] =
2138 { 0, 1, 4, 16, 8, 10, 2, 32 };
2140 return sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1];
2144 * find and process preprocessor directive in passed line
2145 * Find out if a line contains a preprocessor directive, and deal
2146 * with it if so.
2148 * If a directive _is_ found, it is the responsibility of this routine
2149 * (and not the caller) to free_tlist() the line.
2151 * @param tline a pointer to the current tokeninzed line linked list
2152 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2155 static int do_directive(Token * tline)
2157 enum preproc_token i;
2158 int j;
2159 bool err;
2160 int nparam;
2161 bool nolist;
2162 bool casesense;
2163 int k, m;
2164 int offset;
2165 char *p, *pp;
2166 const char *mname;
2167 Include *inc;
2168 Context *ctx;
2169 Cond *cond;
2170 MMacro *mmac, **mmhead;
2171 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2172 Line *l;
2173 struct tokenval tokval;
2174 expr *evalresult;
2175 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2176 int64_t count;
2177 size_t len;
2178 int severity;
2180 origline = tline;
2182 skip_white_(tline);
2183 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2184 (tline->text[1] == '%' || tline->text[1] == '$'
2185 || tline->text[1] == '!'))
2186 return NO_DIRECTIVE_FOUND;
2188 i = pp_token_hash(tline->text);
2191 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2192 * since they are known to be buggy at moment, we need to fix them
2193 * in future release (2.09-2.10)
2195 if (i == PP_RMACRO || i == PP_RMACRO || i == PP_EXITMACRO) {
2196 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2197 tline->text);
2198 return NO_DIRECTIVE_FOUND;
2202 * If we're in a non-emitting branch of a condition construct,
2203 * or walking to the end of an already terminated %rep block,
2204 * we should ignore all directives except for condition
2205 * directives.
2207 if (((istk->conds && !emitting(istk->conds->state)) ||
2208 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2209 return NO_DIRECTIVE_FOUND;
2213 * If we're defining a macro or reading a %rep block, we should
2214 * ignore all directives except for %macro/%imacro (which nest),
2215 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2216 * If we're in a %rep block, another %rep nests, so should be let through.
2218 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2219 i != PP_RMACRO && i != PP_IRMACRO &&
2220 i != PP_ENDMACRO && i != PP_ENDM &&
2221 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2222 return NO_DIRECTIVE_FOUND;
2225 if (defining) {
2226 if (i == PP_MACRO || i == PP_IMACRO ||
2227 i == PP_RMACRO || i == PP_IRMACRO) {
2228 nested_mac_count++;
2229 return NO_DIRECTIVE_FOUND;
2230 } else if (nested_mac_count > 0) {
2231 if (i == PP_ENDMACRO) {
2232 nested_mac_count--;
2233 return NO_DIRECTIVE_FOUND;
2236 if (!defining->name) {
2237 if (i == PP_REP) {
2238 nested_rep_count++;
2239 return NO_DIRECTIVE_FOUND;
2240 } else if (nested_rep_count > 0) {
2241 if (i == PP_ENDREP) {
2242 nested_rep_count--;
2243 return NO_DIRECTIVE_FOUND;
2249 switch (i) {
2250 case PP_INVALID:
2251 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2252 tline->text);
2253 return NO_DIRECTIVE_FOUND; /* didn't get it */
2255 case PP_STACKSIZE:
2256 /* Directive to tell NASM what the default stack size is. The
2257 * default is for a 16-bit stack, and this can be overriden with
2258 * %stacksize large.
2260 tline = tline->next;
2261 if (tline && tline->type == TOK_WHITESPACE)
2262 tline = tline->next;
2263 if (!tline || tline->type != TOK_ID) {
2264 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2265 free_tlist(origline);
2266 return DIRECTIVE_FOUND;
2268 if (nasm_stricmp(tline->text, "flat") == 0) {
2269 /* All subsequent ARG directives are for a 32-bit stack */
2270 StackSize = 4;
2271 StackPointer = "ebp";
2272 ArgOffset = 8;
2273 LocalOffset = 0;
2274 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2275 /* All subsequent ARG directives are for a 64-bit stack */
2276 StackSize = 8;
2277 StackPointer = "rbp";
2278 ArgOffset = 16;
2279 LocalOffset = 0;
2280 } else if (nasm_stricmp(tline->text, "large") == 0) {
2281 /* All subsequent ARG directives are for a 16-bit stack,
2282 * far function call.
2284 StackSize = 2;
2285 StackPointer = "bp";
2286 ArgOffset = 4;
2287 LocalOffset = 0;
2288 } else if (nasm_stricmp(tline->text, "small") == 0) {
2289 /* All subsequent ARG directives are for a 16-bit stack,
2290 * far function call. We don't support near functions.
2292 StackSize = 2;
2293 StackPointer = "bp";
2294 ArgOffset = 6;
2295 LocalOffset = 0;
2296 } else {
2297 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2298 free_tlist(origline);
2299 return DIRECTIVE_FOUND;
2301 free_tlist(origline);
2302 return DIRECTIVE_FOUND;
2304 case PP_ARG:
2305 /* TASM like ARG directive to define arguments to functions, in
2306 * the following form:
2308 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2310 offset = ArgOffset;
2311 do {
2312 char *arg, directive[256];
2313 int size = StackSize;
2315 /* Find the argument name */
2316 tline = tline->next;
2317 if (tline && tline->type == TOK_WHITESPACE)
2318 tline = tline->next;
2319 if (!tline || tline->type != TOK_ID) {
2320 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2321 free_tlist(origline);
2322 return DIRECTIVE_FOUND;
2324 arg = tline->text;
2326 /* Find the argument size type */
2327 tline = tline->next;
2328 if (!tline || tline->type != TOK_OTHER
2329 || tline->text[0] != ':') {
2330 error(ERR_NONFATAL,
2331 "Syntax error processing `%%arg' directive");
2332 free_tlist(origline);
2333 return DIRECTIVE_FOUND;
2335 tline = tline->next;
2336 if (!tline || tline->type != TOK_ID) {
2337 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2338 free_tlist(origline);
2339 return DIRECTIVE_FOUND;
2342 /* Allow macro expansion of type parameter */
2343 tt = tokenize(tline->text);
2344 tt = expand_smacro(tt);
2345 size = parse_size(tt->text);
2346 if (!size) {
2347 error(ERR_NONFATAL,
2348 "Invalid size type for `%%arg' missing directive");
2349 free_tlist(tt);
2350 free_tlist(origline);
2351 return DIRECTIVE_FOUND;
2353 free_tlist(tt);
2355 /* Round up to even stack slots */
2356 size = ALIGN(size, StackSize);
2358 /* Now define the macro for the argument */
2359 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2360 arg, StackPointer, offset);
2361 do_directive(tokenize(directive));
2362 offset += size;
2364 /* Move to the next argument in the list */
2365 tline = tline->next;
2366 if (tline && tline->type == TOK_WHITESPACE)
2367 tline = tline->next;
2368 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2369 ArgOffset = offset;
2370 free_tlist(origline);
2371 return DIRECTIVE_FOUND;
2373 case PP_LOCAL:
2374 /* TASM like LOCAL directive to define local variables for a
2375 * function, in the following form:
2377 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2379 * The '= LocalSize' at the end is ignored by NASM, but is
2380 * required by TASM to define the local parameter size (and used
2381 * by the TASM macro package).
2383 offset = LocalOffset;
2384 do {
2385 char *local, directive[256];
2386 int size = StackSize;
2388 /* Find the argument name */
2389 tline = tline->next;
2390 if (tline && tline->type == TOK_WHITESPACE)
2391 tline = tline->next;
2392 if (!tline || tline->type != TOK_ID) {
2393 error(ERR_NONFATAL,
2394 "`%%local' missing argument parameter");
2395 free_tlist(origline);
2396 return DIRECTIVE_FOUND;
2398 local = tline->text;
2400 /* Find the argument size type */
2401 tline = tline->next;
2402 if (!tline || tline->type != TOK_OTHER
2403 || tline->text[0] != ':') {
2404 error(ERR_NONFATAL,
2405 "Syntax error processing `%%local' directive");
2406 free_tlist(origline);
2407 return DIRECTIVE_FOUND;
2409 tline = tline->next;
2410 if (!tline || tline->type != TOK_ID) {
2411 error(ERR_NONFATAL,
2412 "`%%local' missing size type parameter");
2413 free_tlist(origline);
2414 return DIRECTIVE_FOUND;
2417 /* Allow macro expansion of type parameter */
2418 tt = tokenize(tline->text);
2419 tt = expand_smacro(tt);
2420 size = parse_size(tt->text);
2421 if (!size) {
2422 error(ERR_NONFATAL,
2423 "Invalid size type for `%%local' missing directive");
2424 free_tlist(tt);
2425 free_tlist(origline);
2426 return DIRECTIVE_FOUND;
2428 free_tlist(tt);
2430 /* Round up to even stack slots */
2431 size = ALIGN(size, StackSize);
2433 offset += size; /* Negative offset, increment before */
2435 /* Now define the macro for the argument */
2436 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2437 local, StackPointer, offset);
2438 do_directive(tokenize(directive));
2440 /* Now define the assign to setup the enter_c macro correctly */
2441 snprintf(directive, sizeof(directive),
2442 "%%assign %%$localsize %%$localsize+%d", size);
2443 do_directive(tokenize(directive));
2445 /* Move to the next argument in the list */
2446 tline = tline->next;
2447 if (tline && tline->type == TOK_WHITESPACE)
2448 tline = tline->next;
2449 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2450 LocalOffset = offset;
2451 free_tlist(origline);
2452 return DIRECTIVE_FOUND;
2454 case PP_CLEAR:
2455 if (tline->next)
2456 error(ERR_WARNING|ERR_PASS1,
2457 "trailing garbage after `%%clear' ignored");
2458 free_macros();
2459 init_macros();
2460 free_tlist(origline);
2461 return DIRECTIVE_FOUND;
2463 case PP_DEPEND:
2464 t = tline->next = expand_smacro(tline->next);
2465 skip_white_(t);
2466 if (!t || (t->type != TOK_STRING &&
2467 t->type != TOK_INTERNAL_STRING)) {
2468 error(ERR_NONFATAL, "`%%depend' expects a file name");
2469 free_tlist(origline);
2470 return DIRECTIVE_FOUND; /* but we did _something_ */
2472 if (t->next)
2473 error(ERR_WARNING|ERR_PASS1,
2474 "trailing garbage after `%%depend' ignored");
2475 p = t->text;
2476 if (t->type != TOK_INTERNAL_STRING)
2477 nasm_unquote_cstr(p, i);
2478 if (dephead && !in_list(*dephead, p)) {
2479 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2480 sl->next = NULL;
2481 strcpy(sl->str, p);
2482 *deptail = sl;
2483 deptail = &sl->next;
2485 free_tlist(origline);
2486 return DIRECTIVE_FOUND;
2488 case PP_INCLUDE:
2489 t = tline->next = expand_smacro(tline->next);
2490 skip_white_(t);
2492 if (!t || (t->type != TOK_STRING &&
2493 t->type != TOK_INTERNAL_STRING)) {
2494 error(ERR_NONFATAL, "`%%include' expects a file name");
2495 free_tlist(origline);
2496 return DIRECTIVE_FOUND; /* but we did _something_ */
2498 if (t->next)
2499 error(ERR_WARNING|ERR_PASS1,
2500 "trailing garbage after `%%include' ignored");
2501 p = t->text;
2502 if (t->type != TOK_INTERNAL_STRING)
2503 nasm_unquote_cstr(p, i);
2504 inc = nasm_malloc(sizeof(Include));
2505 inc->next = istk;
2506 inc->conds = NULL;
2507 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2508 if (!inc->fp) {
2509 /* -MG given but file not found */
2510 nasm_free(inc);
2511 } else {
2512 inc->fname = src_set_fname(nasm_strdup(p));
2513 inc->lineno = src_set_linnum(0);
2514 inc->lineinc = 1;
2515 inc->expansion = NULL;
2516 inc->mstk = NULL;
2517 istk = inc;
2518 list->uplevel(LIST_INCLUDE);
2520 free_tlist(origline);
2521 return DIRECTIVE_FOUND;
2523 case PP_USE:
2525 static macros_t *use_pkg;
2526 const char *pkg_macro = NULL;
2528 tline = tline->next;
2529 skip_white_(tline);
2530 tline = expand_id(tline);
2532 if (!tline || (tline->type != TOK_STRING &&
2533 tline->type != TOK_INTERNAL_STRING &&
2534 tline->type != TOK_ID)) {
2535 error(ERR_NONFATAL, "`%%use' expects a package name");
2536 free_tlist(origline);
2537 return DIRECTIVE_FOUND; /* but we did _something_ */
2539 if (tline->next)
2540 error(ERR_WARNING|ERR_PASS1,
2541 "trailing garbage after `%%use' ignored");
2542 if (tline->type == TOK_STRING)
2543 nasm_unquote_cstr(tline->text, i);
2544 use_pkg = nasm_stdmac_find_package(tline->text);
2545 if (!use_pkg)
2546 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2547 else
2548 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2549 if (use_pkg && ! smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2550 /* Not already included, go ahead and include it */
2551 stdmacpos = use_pkg;
2553 free_tlist(origline);
2554 return DIRECTIVE_FOUND;
2556 case PP_PUSH:
2557 case PP_REPL:
2558 case PP_POP:
2559 tline = tline->next;
2560 skip_white_(tline);
2561 tline = expand_id(tline);
2562 if (tline) {
2563 if (!tok_type_(tline, TOK_ID)) {
2564 error(ERR_NONFATAL, "`%s' expects a context identifier",
2565 pp_directives[i]);
2566 free_tlist(origline);
2567 return DIRECTIVE_FOUND; /* but we did _something_ */
2569 if (tline->next)
2570 error(ERR_WARNING|ERR_PASS1,
2571 "trailing garbage after `%s' ignored",
2572 pp_directives[i]);
2573 p = nasm_strdup(tline->text);
2574 } else {
2575 p = NULL; /* Anonymous */
2578 if (i == PP_PUSH) {
2579 ctx = nasm_malloc(sizeof(Context));
2580 ctx->next = cstk;
2581 hash_init(&ctx->localmac, HASH_SMALL);
2582 ctx->name = p;
2583 ctx->number = unique++;
2584 cstk = ctx;
2585 } else {
2586 /* %pop or %repl */
2587 if (!cstk) {
2588 error(ERR_NONFATAL, "`%s': context stack is empty",
2589 pp_directives[i]);
2590 } else if (i == PP_POP) {
2591 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2592 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2593 "expected %s",
2594 cstk->name ? cstk->name : "anonymous", p);
2595 else
2596 ctx_pop();
2597 } else {
2598 /* i == PP_REPL */
2599 nasm_free(cstk->name);
2600 cstk->name = p;
2601 p = NULL;
2603 nasm_free(p);
2605 free_tlist(origline);
2606 return DIRECTIVE_FOUND;
2607 case PP_FATAL:
2608 severity = ERR_FATAL;
2609 goto issue_error;
2610 case PP_ERROR:
2611 severity = ERR_NONFATAL;
2612 goto issue_error;
2613 case PP_WARNING:
2614 severity = ERR_WARNING|ERR_WARN_USER;
2615 goto issue_error;
2617 issue_error:
2619 /* Only error out if this is the final pass */
2620 if (pass != 2 && i != PP_FATAL)
2621 return DIRECTIVE_FOUND;
2623 tline->next = expand_smacro(tline->next);
2624 tline = tline->next;
2625 skip_white_(tline);
2626 t = tline ? tline->next : NULL;
2627 skip_white_(t);
2628 if (tok_type_(tline, TOK_STRING) && !t) {
2629 /* The line contains only a quoted string */
2630 p = tline->text;
2631 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2632 error(severity, "%s", p);
2633 } else {
2634 /* Not a quoted string, or more than a quoted string */
2635 p = detoken(tline, false);
2636 error(severity, "%s", p);
2637 nasm_free(p);
2639 free_tlist(origline);
2640 return DIRECTIVE_FOUND;
2643 CASE_PP_IF:
2644 if (istk->conds && !emitting(istk->conds->state))
2645 j = COND_NEVER;
2646 else {
2647 j = if_condition(tline->next, i);
2648 tline->next = NULL; /* it got freed */
2649 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2651 cond = nasm_malloc(sizeof(Cond));
2652 cond->next = istk->conds;
2653 cond->state = j;
2654 istk->conds = cond;
2655 if(istk->mstk)
2656 istk->mstk->condcnt ++;
2657 free_tlist(origline);
2658 return DIRECTIVE_FOUND;
2660 CASE_PP_ELIF:
2661 if (!istk->conds)
2662 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2663 switch(istk->conds->state) {
2664 case COND_IF_TRUE:
2665 istk->conds->state = COND_DONE;
2666 break;
2668 case COND_DONE:
2669 case COND_NEVER:
2670 break;
2672 case COND_ELSE_TRUE:
2673 case COND_ELSE_FALSE:
2674 error_precond(ERR_WARNING|ERR_PASS1,
2675 "`%%elif' after `%%else' ignored");
2676 istk->conds->state = COND_NEVER;
2677 break;
2679 case COND_IF_FALSE:
2681 * IMPORTANT: In the case of %if, we will already have
2682 * called expand_mmac_params(); however, if we're
2683 * processing an %elif we must have been in a
2684 * non-emitting mode, which would have inhibited
2685 * the normal invocation of expand_mmac_params().
2686 * Therefore, we have to do it explicitly here.
2688 j = if_condition(expand_mmac_params(tline->next), i);
2689 tline->next = NULL; /* it got freed */
2690 istk->conds->state =
2691 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2692 break;
2694 free_tlist(origline);
2695 return DIRECTIVE_FOUND;
2697 case PP_ELSE:
2698 if (tline->next)
2699 error_precond(ERR_WARNING|ERR_PASS1,
2700 "trailing garbage after `%%else' ignored");
2701 if (!istk->conds)
2702 error(ERR_FATAL, "`%%else': no matching `%%if'");
2703 switch(istk->conds->state) {
2704 case COND_IF_TRUE:
2705 case COND_DONE:
2706 istk->conds->state = COND_ELSE_FALSE;
2707 break;
2709 case COND_NEVER:
2710 break;
2712 case COND_IF_FALSE:
2713 istk->conds->state = COND_ELSE_TRUE;
2714 break;
2716 case COND_ELSE_TRUE:
2717 case COND_ELSE_FALSE:
2718 error_precond(ERR_WARNING|ERR_PASS1,
2719 "`%%else' after `%%else' ignored.");
2720 istk->conds->state = COND_NEVER;
2721 break;
2723 free_tlist(origline);
2724 return DIRECTIVE_FOUND;
2726 case PP_ENDIF:
2727 if (tline->next)
2728 error_precond(ERR_WARNING|ERR_PASS1,
2729 "trailing garbage after `%%endif' ignored");
2730 if (!istk->conds)
2731 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2732 cond = istk->conds;
2733 istk->conds = cond->next;
2734 nasm_free(cond);
2735 if(istk->mstk)
2736 istk->mstk->condcnt --;
2737 free_tlist(origline);
2738 return DIRECTIVE_FOUND;
2740 case PP_RMACRO:
2741 case PP_IRMACRO:
2742 case PP_MACRO:
2743 case PP_IMACRO:
2744 if (defining) {
2745 error(ERR_FATAL, "`%s': already defining a macro",
2746 pp_directives[i]);
2747 return DIRECTIVE_FOUND;
2749 defining = nasm_malloc(sizeof(MMacro));
2750 defining->max_depth =
2751 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2752 defining->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2753 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2754 nasm_free(defining);
2755 defining = NULL;
2756 return DIRECTIVE_FOUND;
2759 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2760 while (mmac) {
2761 if (!strcmp(mmac->name, defining->name) &&
2762 (mmac->nparam_min <= defining->nparam_max
2763 || defining->plus)
2764 && (defining->nparam_min <= mmac->nparam_max
2765 || mmac->plus)) {
2766 error(ERR_WARNING|ERR_PASS1,
2767 "redefining multi-line macro `%s'", defining->name);
2768 return DIRECTIVE_FOUND;
2770 mmac = mmac->next;
2772 free_tlist(origline);
2773 return DIRECTIVE_FOUND;
2775 case PP_ENDM:
2776 case PP_ENDMACRO:
2777 if (! (defining && defining->name)) {
2778 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2779 return DIRECTIVE_FOUND;
2781 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2782 defining->next = *mmhead;
2783 *mmhead = defining;
2784 defining = NULL;
2785 free_tlist(origline);
2786 return DIRECTIVE_FOUND;
2788 case PP_EXITMACRO:
2790 * We must search along istk->expansion until we hit a
2791 * macro-end marker for a macro with a name. Then we
2792 * bypass all lines between exitmacro and endmacro.
2794 list_for_each(l, istk->expansion)
2795 if (l->finishes && l->finishes->name)
2796 break;
2798 if (l) {
2800 * Remove all conditional entries relative to this
2801 * macro invocation. (safe to do in this context)
2803 for ( ; l->finishes->condcnt > 0; l->finishes->condcnt --) {
2804 cond = istk->conds;
2805 istk->conds = cond->next;
2806 nasm_free(cond);
2808 istk->expansion = l;
2809 } else {
2810 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2812 free_tlist(origline);
2813 return DIRECTIVE_FOUND;
2815 case PP_UNMACRO:
2816 case PP_UNIMACRO:
2818 MMacro **mmac_p;
2819 MMacro spec;
2821 spec.casesense = (i == PP_UNMACRO);
2822 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2823 return DIRECTIVE_FOUND;
2825 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2826 while (mmac_p && *mmac_p) {
2827 mmac = *mmac_p;
2828 if (mmac->casesense == spec.casesense &&
2829 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2830 mmac->nparam_min == spec.nparam_min &&
2831 mmac->nparam_max == spec.nparam_max &&
2832 mmac->plus == spec.plus) {
2833 *mmac_p = mmac->next;
2834 free_mmacro(mmac);
2835 } else {
2836 mmac_p = &mmac->next;
2839 free_tlist(origline);
2840 free_tlist(spec.dlist);
2841 return DIRECTIVE_FOUND;
2844 case PP_ROTATE:
2845 if (tline->next && tline->next->type == TOK_WHITESPACE)
2846 tline = tline->next;
2847 if (!tline->next) {
2848 free_tlist(origline);
2849 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2850 return DIRECTIVE_FOUND;
2852 t = expand_smacro(tline->next);
2853 tline->next = NULL;
2854 free_tlist(origline);
2855 tline = t;
2856 tptr = &t;
2857 tokval.t_type = TOKEN_INVALID;
2858 evalresult =
2859 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2860 free_tlist(tline);
2861 if (!evalresult)
2862 return DIRECTIVE_FOUND;
2863 if (tokval.t_type)
2864 error(ERR_WARNING|ERR_PASS1,
2865 "trailing garbage after expression ignored");
2866 if (!is_simple(evalresult)) {
2867 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2868 return DIRECTIVE_FOUND;
2870 mmac = istk->mstk;
2871 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2872 mmac = mmac->next_active;
2873 if (!mmac) {
2874 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2875 } else if (mmac->nparam == 0) {
2876 error(ERR_NONFATAL,
2877 "`%%rotate' invoked within macro without parameters");
2878 } else {
2879 int rotate = mmac->rotate + reloc_value(evalresult);
2881 rotate %= (int)mmac->nparam;
2882 if (rotate < 0)
2883 rotate += mmac->nparam;
2885 mmac->rotate = rotate;
2887 return DIRECTIVE_FOUND;
2889 case PP_REP:
2890 nolist = false;
2891 do {
2892 tline = tline->next;
2893 } while (tok_type_(tline, TOK_WHITESPACE));
2895 if (tok_type_(tline, TOK_ID) &&
2896 nasm_stricmp(tline->text, ".nolist") == 0) {
2897 nolist = true;
2898 do {
2899 tline = tline->next;
2900 } while (tok_type_(tline, TOK_WHITESPACE));
2903 if (tline) {
2904 t = expand_smacro(tline);
2905 tptr = &t;
2906 tokval.t_type = TOKEN_INVALID;
2907 evalresult =
2908 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2909 if (!evalresult) {
2910 free_tlist(origline);
2911 return DIRECTIVE_FOUND;
2913 if (tokval.t_type)
2914 error(ERR_WARNING|ERR_PASS1,
2915 "trailing garbage after expression ignored");
2916 if (!is_simple(evalresult)) {
2917 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2918 return DIRECTIVE_FOUND;
2920 count = reloc_value(evalresult);
2921 if (count >= REP_LIMIT) {
2922 error(ERR_NONFATAL, "`%%rep' value exceeds limit");
2923 count = 0;
2924 } else
2925 count++;
2926 } else {
2927 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2928 count = 0;
2930 free_tlist(origline);
2932 tmp_defining = defining;
2933 defining = nasm_malloc(sizeof(MMacro));
2934 defining->prev = NULL;
2935 defining->name = NULL; /* flags this macro as a %rep block */
2936 defining->casesense = false;
2937 defining->plus = false;
2938 defining->nolist = nolist;
2939 defining->in_progress = count;
2940 defining->max_depth = 0;
2941 defining->nparam_min = defining->nparam_max = 0;
2942 defining->defaults = NULL;
2943 defining->dlist = NULL;
2944 defining->expansion = NULL;
2945 defining->next_active = istk->mstk;
2946 defining->rep_nest = tmp_defining;
2947 return DIRECTIVE_FOUND;
2949 case PP_ENDREP:
2950 if (!defining || defining->name) {
2951 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2952 return DIRECTIVE_FOUND;
2956 * Now we have a "macro" defined - although it has no name
2957 * and we won't be entering it in the hash tables - we must
2958 * push a macro-end marker for it on to istk->expansion.
2959 * After that, it will take care of propagating itself (a
2960 * macro-end marker line for a macro which is really a %rep
2961 * block will cause the macro to be re-expanded, complete
2962 * with another macro-end marker to ensure the process
2963 * continues) until the whole expansion is forcibly removed
2964 * from istk->expansion by a %exitrep.
2966 l = nasm_malloc(sizeof(Line));
2967 l->next = istk->expansion;
2968 l->finishes = defining;
2969 l->first = NULL;
2970 istk->expansion = l;
2972 istk->mstk = defining;
2974 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2975 tmp_defining = defining;
2976 defining = defining->rep_nest;
2977 free_tlist(origline);
2978 return DIRECTIVE_FOUND;
2980 case PP_EXITREP:
2982 * We must search along istk->expansion until we hit a
2983 * macro-end marker for a macro with no name. Then we set
2984 * its `in_progress' flag to 0.
2986 list_for_each(l, istk->expansion)
2987 if (l->finishes && !l->finishes->name)
2988 break;
2990 if (l)
2991 l->finishes->in_progress = 1;
2992 else
2993 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2994 free_tlist(origline);
2995 return DIRECTIVE_FOUND;
2997 case PP_XDEFINE:
2998 case PP_IXDEFINE:
2999 case PP_DEFINE:
3000 case PP_IDEFINE:
3001 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
3003 tline = tline->next;
3004 skip_white_(tline);
3005 tline = expand_id(tline);
3006 if (!tline || (tline->type != TOK_ID &&
3007 (tline->type != TOK_PREPROC_ID ||
3008 tline->text[1] != '$'))) {
3009 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3010 pp_directives[i]);
3011 free_tlist(origline);
3012 return DIRECTIVE_FOUND;
3015 ctx = get_ctx(tline->text, &mname, false);
3016 last = tline;
3017 param_start = tline = tline->next;
3018 nparam = 0;
3020 /* Expand the macro definition now for %xdefine and %ixdefine */
3021 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
3022 tline = expand_smacro(tline);
3024 if (tok_is_(tline, "(")) {
3026 * This macro has parameters.
3029 tline = tline->next;
3030 while (1) {
3031 skip_white_(tline);
3032 if (!tline) {
3033 error(ERR_NONFATAL, "parameter identifier expected");
3034 free_tlist(origline);
3035 return DIRECTIVE_FOUND;
3037 if (tline->type != TOK_ID) {
3038 error(ERR_NONFATAL,
3039 "`%s': parameter identifier expected",
3040 tline->text);
3041 free_tlist(origline);
3042 return DIRECTIVE_FOUND;
3044 tline->type = TOK_SMAC_PARAM + nparam++;
3045 tline = tline->next;
3046 skip_white_(tline);
3047 if (tok_is_(tline, ",")) {
3048 tline = tline->next;
3049 } else {
3050 if (!tok_is_(tline, ")")) {
3051 error(ERR_NONFATAL,
3052 "`)' expected to terminate macro template");
3053 free_tlist(origline);
3054 return DIRECTIVE_FOUND;
3056 break;
3059 last = tline;
3060 tline = tline->next;
3062 if (tok_type_(tline, TOK_WHITESPACE))
3063 last = tline, tline = tline->next;
3064 macro_start = NULL;
3065 last->next = NULL;
3066 t = tline;
3067 while (t) {
3068 if (t->type == TOK_ID) {
3069 list_for_each(tt, param_start)
3070 if (tt->type >= TOK_SMAC_PARAM &&
3071 !strcmp(tt->text, t->text))
3072 t->type = tt->type;
3074 tt = t->next;
3075 t->next = macro_start;
3076 macro_start = t;
3077 t = tt;
3080 * Good. We now have a macro name, a parameter count, and a
3081 * token list (in reverse order) for an expansion. We ought
3082 * to be OK just to create an SMacro, store it, and let
3083 * free_tlist have the rest of the line (which we have
3084 * carefully re-terminated after chopping off the expansion
3085 * from the end).
3087 define_smacro(ctx, mname, casesense, nparam, macro_start);
3088 free_tlist(origline);
3089 return DIRECTIVE_FOUND;
3091 case PP_UNDEF:
3092 tline = tline->next;
3093 skip_white_(tline);
3094 tline = expand_id(tline);
3095 if (!tline || (tline->type != TOK_ID &&
3096 (tline->type != TOK_PREPROC_ID ||
3097 tline->text[1] != '$'))) {
3098 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
3099 free_tlist(origline);
3100 return DIRECTIVE_FOUND;
3102 if (tline->next) {
3103 error(ERR_WARNING|ERR_PASS1,
3104 "trailing garbage after macro name ignored");
3107 /* Find the context that symbol belongs to */
3108 ctx = get_ctx(tline->text, &mname, false);
3109 undef_smacro(ctx, mname);
3110 free_tlist(origline);
3111 return DIRECTIVE_FOUND;
3113 case PP_DEFSTR:
3114 case PP_IDEFSTR:
3115 casesense = (i == PP_DEFSTR);
3117 tline = tline->next;
3118 skip_white_(tline);
3119 tline = expand_id(tline);
3120 if (!tline || (tline->type != TOK_ID &&
3121 (tline->type != TOK_PREPROC_ID ||
3122 tline->text[1] != '$'))) {
3123 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3124 pp_directives[i]);
3125 free_tlist(origline);
3126 return DIRECTIVE_FOUND;
3129 ctx = get_ctx(tline->text, &mname, false);
3130 last = tline;
3131 tline = expand_smacro(tline->next);
3132 last->next = NULL;
3134 while (tok_type_(tline, TOK_WHITESPACE))
3135 tline = delete_Token(tline);
3137 p = detoken(tline, false);
3138 macro_start = nasm_malloc(sizeof(*macro_start));
3139 macro_start->next = NULL;
3140 macro_start->text = nasm_quote(p, strlen(p));
3141 macro_start->type = TOK_STRING;
3142 macro_start->a.mac = NULL;
3143 nasm_free(p);
3146 * We now have a macro name, an implicit parameter count of
3147 * zero, and a string token to use as an expansion. Create
3148 * and store an SMacro.
3150 define_smacro(ctx, mname, casesense, 0, macro_start);
3151 free_tlist(origline);
3152 return DIRECTIVE_FOUND;
3154 case PP_DEFTOK:
3155 case PP_IDEFTOK:
3156 casesense = (i == PP_DEFTOK);
3158 tline = tline->next;
3159 skip_white_(tline);
3160 tline = expand_id(tline);
3161 if (!tline || (tline->type != TOK_ID &&
3162 (tline->type != TOK_PREPROC_ID ||
3163 tline->text[1] != '$'))) {
3164 error(ERR_NONFATAL,
3165 "`%s' expects a macro identifier as first parameter",
3166 pp_directives[i]);
3167 free_tlist(origline);
3168 return DIRECTIVE_FOUND;
3170 ctx = get_ctx(tline->text, &mname, false);
3171 last = tline;
3172 tline = expand_smacro(tline->next);
3173 last->next = NULL;
3175 t = tline;
3176 while (tok_type_(t, TOK_WHITESPACE))
3177 t = t->next;
3178 /* t should now point to the string */
3179 if (t->type != TOK_STRING) {
3180 error(ERR_NONFATAL,
3181 "`%s` requires string as second parameter",
3182 pp_directives[i]);
3183 free_tlist(tline);
3184 free_tlist(origline);
3185 return DIRECTIVE_FOUND;
3188 nasm_unquote_cstr(t->text, i);
3189 macro_start = tokenize(t->text);
3192 * We now have a macro name, an implicit parameter count of
3193 * zero, and a numeric token to use as an expansion. Create
3194 * and store an SMacro.
3196 define_smacro(ctx, mname, casesense, 0, macro_start);
3197 free_tlist(tline);
3198 free_tlist(origline);
3199 return DIRECTIVE_FOUND;
3201 case PP_PATHSEARCH:
3203 FILE *fp;
3204 StrList *xsl = NULL;
3205 StrList **xst = &xsl;
3207 casesense = true;
3209 tline = tline->next;
3210 skip_white_(tline);
3211 tline = expand_id(tline);
3212 if (!tline || (tline->type != TOK_ID &&
3213 (tline->type != TOK_PREPROC_ID ||
3214 tline->text[1] != '$'))) {
3215 error(ERR_NONFATAL,
3216 "`%%pathsearch' expects a macro identifier as first parameter");
3217 free_tlist(origline);
3218 return DIRECTIVE_FOUND;
3220 ctx = get_ctx(tline->text, &mname, false);
3221 last = tline;
3222 tline = expand_smacro(tline->next);
3223 last->next = NULL;
3225 t = tline;
3226 while (tok_type_(t, TOK_WHITESPACE))
3227 t = t->next;
3229 if (!t || (t->type != TOK_STRING &&
3230 t->type != TOK_INTERNAL_STRING)) {
3231 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3232 free_tlist(tline);
3233 free_tlist(origline);
3234 return DIRECTIVE_FOUND; /* but we did _something_ */
3236 if (t->next)
3237 error(ERR_WARNING|ERR_PASS1,
3238 "trailing garbage after `%%pathsearch' ignored");
3239 p = t->text;
3240 if (t->type != TOK_INTERNAL_STRING)
3241 nasm_unquote(p, NULL);
3243 fp = inc_fopen(p, &xsl, &xst, true);
3244 if (fp) {
3245 p = xsl->str;
3246 fclose(fp); /* Don't actually care about the file */
3248 macro_start = nasm_malloc(sizeof(*macro_start));
3249 macro_start->next = NULL;
3250 macro_start->text = nasm_quote(p, strlen(p));
3251 macro_start->type = TOK_STRING;
3252 macro_start->a.mac = NULL;
3253 if (xsl)
3254 nasm_free(xsl);
3257 * We now have a macro name, an implicit parameter count of
3258 * zero, and a string token to use as an expansion. Create
3259 * and store an SMacro.
3261 define_smacro(ctx, mname, casesense, 0, macro_start);
3262 free_tlist(tline);
3263 free_tlist(origline);
3264 return DIRECTIVE_FOUND;
3267 case PP_STRLEN:
3268 casesense = true;
3270 tline = tline->next;
3271 skip_white_(tline);
3272 tline = expand_id(tline);
3273 if (!tline || (tline->type != TOK_ID &&
3274 (tline->type != TOK_PREPROC_ID ||
3275 tline->text[1] != '$'))) {
3276 error(ERR_NONFATAL,
3277 "`%%strlen' expects a macro identifier as first parameter");
3278 free_tlist(origline);
3279 return DIRECTIVE_FOUND;
3281 ctx = get_ctx(tline->text, &mname, false);
3282 last = tline;
3283 tline = expand_smacro(tline->next);
3284 last->next = NULL;
3286 t = tline;
3287 while (tok_type_(t, TOK_WHITESPACE))
3288 t = t->next;
3289 /* t should now point to the string */
3290 if (!tok_type_(t, TOK_STRING)) {
3291 error(ERR_NONFATAL,
3292 "`%%strlen` requires string as second parameter");
3293 free_tlist(tline);
3294 free_tlist(origline);
3295 return DIRECTIVE_FOUND;
3298 macro_start = nasm_malloc(sizeof(*macro_start));
3299 macro_start->next = NULL;
3300 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3301 macro_start->a.mac = NULL;
3304 * We now have a macro name, an implicit parameter count of
3305 * zero, and a numeric token to use as an expansion. Create
3306 * and store an SMacro.
3308 define_smacro(ctx, mname, casesense, 0, macro_start);
3309 free_tlist(tline);
3310 free_tlist(origline);
3311 return DIRECTIVE_FOUND;
3313 case PP_STRCAT:
3314 casesense = true;
3316 tline = tline->next;
3317 skip_white_(tline);
3318 tline = expand_id(tline);
3319 if (!tline || (tline->type != TOK_ID &&
3320 (tline->type != TOK_PREPROC_ID ||
3321 tline->text[1] != '$'))) {
3322 error(ERR_NONFATAL,
3323 "`%%strcat' expects a macro identifier as first parameter");
3324 free_tlist(origline);
3325 return DIRECTIVE_FOUND;
3327 ctx = get_ctx(tline->text, &mname, false);
3328 last = tline;
3329 tline = expand_smacro(tline->next);
3330 last->next = NULL;
3332 len = 0;
3333 list_for_each(t, tline) {
3334 switch (t->type) {
3335 case TOK_WHITESPACE:
3336 break;
3337 case TOK_STRING:
3338 len += t->a.len = nasm_unquote(t->text, NULL);
3339 break;
3340 case TOK_OTHER:
3341 if (!strcmp(t->text, ",")) /* permit comma separators */
3342 break;
3343 /* else fall through */
3344 default:
3345 error(ERR_NONFATAL,
3346 "non-string passed to `%%strcat' (%d)", t->type);
3347 free_tlist(tline);
3348 free_tlist(origline);
3349 return DIRECTIVE_FOUND;
3353 p = pp = nasm_malloc(len);
3354 list_for_each(t, tline) {
3355 if (t->type == TOK_STRING) {
3356 memcpy(p, t->text, t->a.len);
3357 p += t->a.len;
3362 * We now have a macro name, an implicit parameter count of
3363 * zero, and a numeric token to use as an expansion. Create
3364 * and store an SMacro.
3366 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3367 macro_start->text = nasm_quote(pp, len);
3368 nasm_free(pp);
3369 define_smacro(ctx, mname, casesense, 0, macro_start);
3370 free_tlist(tline);
3371 free_tlist(origline);
3372 return DIRECTIVE_FOUND;
3374 case PP_SUBSTR:
3376 int64_t a1, a2;
3377 size_t len;
3379 casesense = true;
3381 tline = tline->next;
3382 skip_white_(tline);
3383 tline = expand_id(tline);
3384 if (!tline || (tline->type != TOK_ID &&
3385 (tline->type != TOK_PREPROC_ID ||
3386 tline->text[1] != '$'))) {
3387 error(ERR_NONFATAL,
3388 "`%%substr' expects a macro identifier as first parameter");
3389 free_tlist(origline);
3390 return DIRECTIVE_FOUND;
3392 ctx = get_ctx(tline->text, &mname, false);
3393 last = tline;
3394 tline = expand_smacro(tline->next);
3395 last->next = NULL;
3397 t = tline->next;
3398 while (tok_type_(t, TOK_WHITESPACE))
3399 t = t->next;
3401 /* t should now point to the string */
3402 if (t->type != TOK_STRING) {
3403 error(ERR_NONFATAL,
3404 "`%%substr` requires string as second parameter");
3405 free_tlist(tline);
3406 free_tlist(origline);
3407 return DIRECTIVE_FOUND;
3410 tt = t->next;
3411 tptr = &tt;
3412 tokval.t_type = TOKEN_INVALID;
3413 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3414 pass, error, NULL);
3415 if (!evalresult) {
3416 free_tlist(tline);
3417 free_tlist(origline);
3418 return DIRECTIVE_FOUND;
3419 } else if (!is_simple(evalresult)) {
3420 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3421 free_tlist(tline);
3422 free_tlist(origline);
3423 return DIRECTIVE_FOUND;
3425 a1 = evalresult->value-1;
3427 while (tok_type_(tt, TOK_WHITESPACE))
3428 tt = tt->next;
3429 if (!tt) {
3430 a2 = 1; /* Backwards compatibility: one character */
3431 } else {
3432 tokval.t_type = TOKEN_INVALID;
3433 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3434 pass, error, NULL);
3435 if (!evalresult) {
3436 free_tlist(tline);
3437 free_tlist(origline);
3438 return DIRECTIVE_FOUND;
3439 } else if (!is_simple(evalresult)) {
3440 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3441 free_tlist(tline);
3442 free_tlist(origline);
3443 return DIRECTIVE_FOUND;
3445 a2 = evalresult->value;
3448 len = nasm_unquote(t->text, NULL);
3449 if (a2 < 0)
3450 a2 = a2+1+len-a1;
3451 if (a1+a2 > (int64_t)len)
3452 a2 = len-a1;
3454 macro_start = nasm_malloc(sizeof(*macro_start));
3455 macro_start->next = NULL;
3456 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3457 macro_start->type = TOK_STRING;
3458 macro_start->a.mac = NULL;
3461 * We now have a macro name, an implicit parameter count of
3462 * zero, and a numeric token to use as an expansion. Create
3463 * and store an SMacro.
3465 define_smacro(ctx, mname, casesense, 0, macro_start);
3466 free_tlist(tline);
3467 free_tlist(origline);
3468 return DIRECTIVE_FOUND;
3471 case PP_ASSIGN:
3472 case PP_IASSIGN:
3473 casesense = (i == PP_ASSIGN);
3475 tline = tline->next;
3476 skip_white_(tline);
3477 tline = expand_id(tline);
3478 if (!tline || (tline->type != TOK_ID &&
3479 (tline->type != TOK_PREPROC_ID ||
3480 tline->text[1] != '$'))) {
3481 error(ERR_NONFATAL,
3482 "`%%%sassign' expects a macro identifier",
3483 (i == PP_IASSIGN ? "i" : ""));
3484 free_tlist(origline);
3485 return DIRECTIVE_FOUND;
3487 ctx = get_ctx(tline->text, &mname, false);
3488 last = tline;
3489 tline = expand_smacro(tline->next);
3490 last->next = NULL;
3492 t = tline;
3493 tptr = &t;
3494 tokval.t_type = TOKEN_INVALID;
3495 evalresult =
3496 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3497 free_tlist(tline);
3498 if (!evalresult) {
3499 free_tlist(origline);
3500 return DIRECTIVE_FOUND;
3503 if (tokval.t_type)
3504 error(ERR_WARNING|ERR_PASS1,
3505 "trailing garbage after expression ignored");
3507 if (!is_simple(evalresult)) {
3508 error(ERR_NONFATAL,
3509 "non-constant value given to `%%%sassign'",
3510 (i == PP_IASSIGN ? "i" : ""));
3511 free_tlist(origline);
3512 return DIRECTIVE_FOUND;
3515 macro_start = nasm_malloc(sizeof(*macro_start));
3516 macro_start->next = NULL;
3517 make_tok_num(macro_start, reloc_value(evalresult));
3518 macro_start->a.mac = NULL;
3521 * We now have a macro name, an implicit parameter count of
3522 * zero, and a numeric token to use as an expansion. Create
3523 * and store an SMacro.
3525 define_smacro(ctx, mname, casesense, 0, macro_start);
3526 free_tlist(origline);
3527 return DIRECTIVE_FOUND;
3529 case PP_LINE:
3531 * Syntax is `%line nnn[+mmm] [filename]'
3533 tline = tline->next;
3534 skip_white_(tline);
3535 if (!tok_type_(tline, TOK_NUMBER)) {
3536 error(ERR_NONFATAL, "`%%line' expects line number");
3537 free_tlist(origline);
3538 return DIRECTIVE_FOUND;
3540 k = readnum(tline->text, &err);
3541 m = 1;
3542 tline = tline->next;
3543 if (tok_is_(tline, "+")) {
3544 tline = tline->next;
3545 if (!tok_type_(tline, TOK_NUMBER)) {
3546 error(ERR_NONFATAL, "`%%line' expects line increment");
3547 free_tlist(origline);
3548 return DIRECTIVE_FOUND;
3550 m = readnum(tline->text, &err);
3551 tline = tline->next;
3553 skip_white_(tline);
3554 src_set_linnum(k);
3555 istk->lineinc = m;
3556 if (tline) {
3557 nasm_free(src_set_fname(detoken(tline, false)));
3559 free_tlist(origline);
3560 return DIRECTIVE_FOUND;
3562 default:
3563 error(ERR_FATAL,
3564 "preprocessor directive `%s' not yet implemented",
3565 pp_directives[i]);
3566 return DIRECTIVE_FOUND;
3571 * Ensure that a macro parameter contains a condition code and
3572 * nothing else. Return the condition code index if so, or -1
3573 * otherwise.
3575 static int find_cc(Token * t)
3577 Token *tt;
3578 int i, j, k, m;
3580 if (!t)
3581 return -1; /* Probably a %+ without a space */
3583 skip_white_(t);
3584 if (t->type != TOK_ID)
3585 return -1;
3586 tt = t->next;
3587 skip_white_(tt);
3588 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3589 return -1;
3591 i = -1;
3592 j = ARRAY_SIZE(conditions);
3593 while (j - i > 1) {
3594 k = (j + i) / 2;
3595 m = nasm_stricmp(t->text, conditions[k]);
3596 if (m == 0) {
3597 i = k;
3598 j = -2;
3599 break;
3600 } else if (m < 0) {
3601 j = k;
3602 } else
3603 i = k;
3605 if (j != -2)
3606 return -1;
3607 return i;
3610 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3612 Token **tail, *t, *tt;
3613 Token **paste_head;
3614 bool did_paste = false;
3615 char *tmp;
3617 /* Now handle token pasting... */
3618 paste_head = NULL;
3619 tail = head;
3620 while ((t = *tail) && (tt = t->next)) {
3621 switch (t->type) {
3622 case TOK_WHITESPACE:
3623 if (tt->type == TOK_WHITESPACE) {
3624 /* Zap adjacent whitespace tokens */
3625 t->next = delete_Token(tt);
3626 } else {
3627 /* Do not advance paste_head here */
3628 tail = &t->next;
3630 break;
3631 case TOK_ID:
3632 case TOK_NUMBER:
3633 case TOK_FLOAT:
3635 size_t len = 0;
3636 char *tmp, *p;
3638 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3639 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3640 tt->type == TOK_OTHER)) {
3641 len += strlen(tt->text);
3642 tt = tt->next;
3646 * Now tt points to the first token after
3647 * the potential paste area...
3649 if (tt != t->next) {
3650 /* We have at least two tokens... */
3651 len += strlen(t->text);
3652 p = tmp = nasm_malloc(len+1);
3654 while (t != tt) {
3655 strcpy(p, t->text);
3656 p = strchr(p, '\0');
3657 t = delete_Token(t);
3660 t = *tail = tokenize(tmp);
3661 nasm_free(tmp);
3663 while (t->next) {
3664 tail = &t->next;
3665 t = t->next;
3667 t->next = tt; /* Attach the remaining token chain */
3669 did_paste = true;
3671 paste_head = tail;
3672 tail = &t->next;
3673 break;
3675 case TOK_PASTE: /* %+ */
3676 if (handle_paste_tokens) {
3677 /* Zap %+ and whitespace tokens to the right */
3678 while (t && (t->type == TOK_WHITESPACE ||
3679 t->type == TOK_PASTE))
3680 t = *tail = delete_Token(t);
3681 if (!paste_head || !t)
3682 break; /* Nothing to paste with */
3683 tail = paste_head;
3684 t = *tail;
3685 tt = t->next;
3686 while (tok_type_(tt, TOK_WHITESPACE))
3687 tt = t->next = delete_Token(tt);
3689 if (tt) {
3690 tmp = nasm_strcat(t->text, tt->text);
3691 delete_Token(t);
3692 tt = delete_Token(tt);
3693 t = *tail = tokenize(tmp);
3694 nasm_free(tmp);
3695 while (t->next) {
3696 tail = &t->next;
3697 t = t->next;
3699 t->next = tt; /* Attach the remaining token chain */
3700 did_paste = true;
3702 paste_head = tail;
3703 tail = &t->next;
3704 break;
3706 /* else fall through */
3707 default:
3708 tail = &t->next;
3709 if (!tok_type_(t->next, TOK_WHITESPACE))
3710 paste_head = tail;
3711 break;
3714 return did_paste;
3718 * expands to a list of tokens from %{x:y}
3720 static Token *expand_mmac_params_range(MMacro *mac, Token *tline, Token ***last)
3722 Token *t = tline, **tt, *tm, *head;
3723 char *pos;
3724 int fst, lst, j, i;
3726 pos = strchr(tline->text, ':');
3727 nasm_assert(pos);
3729 lst = atoi(pos + 1);
3730 fst = atoi(tline->text + 1);
3733 * only macros params are accounted so
3734 * if someone passes %0 -- we reject such
3735 * value(s)
3737 if (lst == 0 || fst == 0)
3738 goto err;
3740 /* the values should be sane */
3741 if ((fst > (int)mac->nparam || fst < (-(int)mac->nparam)) ||
3742 (lst > (int)mac->nparam || lst < (-(int)mac->nparam)))
3743 goto err;
3745 fst = fst < 0 ? fst + (int)mac->nparam + 1: fst;
3746 lst = lst < 0 ? lst + (int)mac->nparam + 1: lst;
3748 /* counted from zero */
3749 fst--, lst--;
3752 * it will be at least one token
3754 tm = mac->params[(fst + mac->rotate) % mac->nparam];
3755 t = new_Token(NULL, tm->type, tm->text, 0);
3756 head = t, tt = &t->next;
3757 if (fst < lst) {
3758 for (i = fst + 1; i <= lst; i++) {
3759 t = new_Token(NULL, TOK_OTHER, ",", 0);
3760 *tt = t, tt = &t->next;
3761 j = (i + mac->rotate) % mac->nparam;
3762 tm = mac->params[j];
3763 t = new_Token(NULL, tm->type, tm->text, 0);
3764 *tt = t, tt = &t->next;
3766 } else {
3767 for (i = fst - 1; i >= lst; i--) {
3768 t = new_Token(NULL, TOK_OTHER, ",", 0);
3769 *tt = t, tt = &t->next;
3770 j = (i + mac->rotate) % mac->nparam;
3771 tm = mac->params[j];
3772 t = new_Token(NULL, tm->type, tm->text, 0);
3773 *tt = t, tt = &t->next;
3777 *last = tt;
3778 return head;
3780 err:
3781 error(ERR_NONFATAL, "`%%{%s}': macro parameters out of range",
3782 &tline->text[1]);
3783 return tline;
3787 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3788 * %-n) and MMacro-local identifiers (%%foo) as well as
3789 * macro indirection (%[...]) and range (%{..:..}).
3791 static Token *expand_mmac_params(Token * tline)
3793 Token *t, *tt, **tail, *thead;
3794 bool changed = false;
3795 char *pos;
3797 tail = &thead;
3798 thead = NULL;
3800 while (tline) {
3801 if (tline->type == TOK_PREPROC_ID &&
3802 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text[2]) ||
3803 (tline->text[1] >= '0' && tline->text[1] <= '9') ||
3804 tline->text[1] == '%')) {
3805 char *text = NULL;
3806 int type = 0, cc; /* type = 0 to placate optimisers */
3807 char tmpbuf[30];
3808 unsigned int n;
3809 int i;
3810 MMacro *mac;
3812 t = tline;
3813 tline = tline->next;
3815 mac = istk->mstk;
3816 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3817 mac = mac->next_active;
3818 if (!mac) {
3819 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3820 } else {
3821 pos = strchr(t->text, ':');
3822 if (!pos) {
3823 switch (t->text[1]) {
3825 * We have to make a substitution of one of the
3826 * forms %1, %-1, %+1, %%foo, %0.
3828 case '0':
3829 type = TOK_NUMBER;
3830 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3831 text = nasm_strdup(tmpbuf);
3832 break;
3833 case '%':
3834 type = TOK_ID;
3835 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3836 mac->unique);
3837 text = nasm_strcat(tmpbuf, t->text + 2);
3838 break;
3839 case '-':
3840 n = atoi(t->text + 2) - 1;
3841 if (n >= mac->nparam)
3842 tt = NULL;
3843 else {
3844 if (mac->nparam > 1)
3845 n = (n + mac->rotate) % mac->nparam;
3846 tt = mac->params[n];
3848 cc = find_cc(tt);
3849 if (cc == -1) {
3850 error(ERR_NONFATAL,
3851 "macro parameter %d is not a condition code",
3852 n + 1);
3853 text = NULL;
3854 } else {
3855 type = TOK_ID;
3856 if (inverse_ccs[cc] == -1) {
3857 error(ERR_NONFATAL,
3858 "condition code `%s' is not invertible",
3859 conditions[cc]);
3860 text = NULL;
3861 } else
3862 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3864 break;
3865 case '+':
3866 n = atoi(t->text + 2) - 1;
3867 if (n >= mac->nparam)
3868 tt = NULL;
3869 else {
3870 if (mac->nparam > 1)
3871 n = (n + mac->rotate) % mac->nparam;
3872 tt = mac->params[n];
3874 cc = find_cc(tt);
3875 if (cc == -1) {
3876 error(ERR_NONFATAL,
3877 "macro parameter %d is not a condition code",
3878 n + 1);
3879 text = NULL;
3880 } else {
3881 type = TOK_ID;
3882 text = nasm_strdup(conditions[cc]);
3884 break;
3885 default:
3886 n = atoi(t->text + 1) - 1;
3887 if (n >= mac->nparam)
3888 tt = NULL;
3889 else {
3890 if (mac->nparam > 1)
3891 n = (n + mac->rotate) % mac->nparam;
3892 tt = mac->params[n];
3894 if (tt) {
3895 for (i = 0; i < mac->paramlen[n]; i++) {
3896 *tail = new_Token(NULL, tt->type, tt->text, 0);
3897 tail = &(*tail)->next;
3898 tt = tt->next;
3901 text = NULL; /* we've done it here */
3902 break;
3904 } else {
3906 * seems we have a parameters range here
3908 Token *head, **last;
3909 head = expand_mmac_params_range(mac, t, &last);
3910 if (head != t) {
3911 *tail = head;
3912 *last = tline;
3913 tline = head;
3914 text = NULL;
3918 if (!text) {
3919 delete_Token(t);
3920 } else {
3921 *tail = t;
3922 tail = &t->next;
3923 t->type = type;
3924 nasm_free(t->text);
3925 t->text = text;
3926 t->a.mac = NULL;
3928 changed = true;
3929 continue;
3930 } else if (tline->type == TOK_INDIRECT) {
3931 t = tline;
3932 tline = tline->next;
3933 tt = tokenize(t->text);
3934 tt = expand_mmac_params(tt);
3935 tt = expand_smacro(tt);
3936 *tail = tt;
3937 while (tt) {
3938 tt->a.mac = NULL; /* Necessary? */
3939 tail = &tt->next;
3940 tt = tt->next;
3942 delete_Token(t);
3943 changed = true;
3944 } else {
3945 t = *tail = tline;
3946 tline = tline->next;
3947 t->a.mac = NULL;
3948 tail = &t->next;
3951 *tail = NULL;
3953 if (changed)
3954 paste_tokens(&thead, false);
3956 return thead;
3960 * Expand all single-line macro calls made in the given line.
3961 * Return the expanded version of the line. The original is deemed
3962 * to be destroyed in the process. (In reality we'll just move
3963 * Tokens from input to output a lot of the time, rather than
3964 * actually bothering to destroy and replicate.)
3967 static Token *expand_smacro(Token * tline)
3969 Token *t, *tt, *mstart, **tail, *thead;
3970 SMacro *head = NULL, *m;
3971 Token **params;
3972 int *paramsize;
3973 unsigned int nparam, sparam;
3974 int brackets;
3975 Token *org_tline = tline;
3976 Context *ctx;
3977 const char *mname;
3978 int deadman = DEADMAN_LIMIT;
3979 bool expanded;
3982 * Trick: we should avoid changing the start token pointer since it can
3983 * be contained in "next" field of other token. Because of this
3984 * we allocate a copy of first token and work with it; at the end of
3985 * routine we copy it back
3987 if (org_tline) {
3988 tline = new_Token(org_tline->next, org_tline->type,
3989 org_tline->text, 0);
3990 tline->a.mac = org_tline->a.mac;
3991 nasm_free(org_tline->text);
3992 org_tline->text = NULL;
3995 expanded = true; /* Always expand %+ at least once */
3997 again:
3998 thead = NULL;
3999 tail = &thead;
4001 while (tline) { /* main token loop */
4002 if (!--deadman) {
4003 error(ERR_NONFATAL, "interminable macro recursion");
4004 goto err;
4007 if ((mname = tline->text)) {
4008 /* if this token is a local macro, look in local context */
4009 if (tline->type == TOK_ID) {
4010 head = (SMacro *)hash_findix(&smacros, mname);
4011 } else if (tline->type == TOK_PREPROC_ID) {
4012 ctx = get_ctx(mname, &mname, true);
4013 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
4014 } else
4015 head = NULL;
4018 * We've hit an identifier. As in is_mmacro below, we first
4019 * check whether the identifier is a single-line macro at
4020 * all, then think about checking for parameters if
4021 * necessary.
4023 list_for_each(m, head)
4024 if (!mstrcmp(m->name, mname, m->casesense))
4025 break;
4026 if (m) {
4027 mstart = tline;
4028 params = NULL;
4029 paramsize = NULL;
4030 if (m->nparam == 0) {
4032 * Simple case: the macro is parameterless. Discard the
4033 * one token that the macro call took, and push the
4034 * expansion back on the to-do stack.
4036 if (!m->expansion) {
4037 if (!strcmp("__FILE__", m->name)) {
4038 int32_t num = 0;
4039 char *file = NULL;
4040 src_get(&num, &file);
4041 tline->text = nasm_quote(file, strlen(file));
4042 tline->type = TOK_STRING;
4043 nasm_free(file);
4044 continue;
4046 if (!strcmp("__LINE__", m->name)) {
4047 nasm_free(tline->text);
4048 make_tok_num(tline, src_get_linnum());
4049 continue;
4051 if (!strcmp("__BITS__", m->name)) {
4052 nasm_free(tline->text);
4053 make_tok_num(tline, globalbits);
4054 continue;
4056 tline = delete_Token(tline);
4057 continue;
4059 } else {
4061 * Complicated case: at least one macro with this name
4062 * exists and takes parameters. We must find the
4063 * parameters in the call, count them, find the SMacro
4064 * that corresponds to that form of the macro call, and
4065 * substitute for the parameters when we expand. What a
4066 * pain.
4068 /*tline = tline->next;
4069 skip_white_(tline); */
4070 do {
4071 t = tline->next;
4072 while (tok_type_(t, TOK_SMAC_END)) {
4073 t->a.mac->in_progress = false;
4074 t->text = NULL;
4075 t = tline->next = delete_Token(t);
4077 tline = t;
4078 } while (tok_type_(tline, TOK_WHITESPACE));
4079 if (!tok_is_(tline, "(")) {
4081 * This macro wasn't called with parameters: ignore
4082 * the call. (Behaviour borrowed from gnu cpp.)
4084 tline = mstart;
4085 m = NULL;
4086 } else {
4087 int paren = 0;
4088 int white = 0;
4089 brackets = 0;
4090 nparam = 0;
4091 sparam = PARAM_DELTA;
4092 params = nasm_malloc(sparam * sizeof(Token *));
4093 params[0] = tline->next;
4094 paramsize = nasm_malloc(sparam * sizeof(int));
4095 paramsize[0] = 0;
4096 while (true) { /* parameter loop */
4098 * For some unusual expansions
4099 * which concatenates function call
4101 t = tline->next;
4102 while (tok_type_(t, TOK_SMAC_END)) {
4103 t->a.mac->in_progress = false;
4104 t->text = NULL;
4105 t = tline->next = delete_Token(t);
4107 tline = t;
4109 if (!tline) {
4110 error(ERR_NONFATAL,
4111 "macro call expects terminating `)'");
4112 break;
4114 if (tline->type == TOK_WHITESPACE
4115 && brackets <= 0) {
4116 if (paramsize[nparam])
4117 white++;
4118 else
4119 params[nparam] = tline->next;
4120 continue; /* parameter loop */
4122 if (tline->type == TOK_OTHER
4123 && tline->text[1] == 0) {
4124 char ch = tline->text[0];
4125 if (ch == ',' && !paren && brackets <= 0) {
4126 if (++nparam >= sparam) {
4127 sparam += PARAM_DELTA;
4128 params = nasm_realloc(params,
4129 sparam * sizeof(Token *));
4130 paramsize = nasm_realloc(paramsize,
4131 sparam * sizeof(int));
4133 params[nparam] = tline->next;
4134 paramsize[nparam] = 0;
4135 white = 0;
4136 continue; /* parameter loop */
4138 if (ch == '{' &&
4139 (brackets > 0 || (brackets == 0 &&
4140 !paramsize[nparam])))
4142 if (!(brackets++)) {
4143 params[nparam] = tline->next;
4144 continue; /* parameter loop */
4147 if (ch == '}' && brackets > 0)
4148 if (--brackets == 0) {
4149 brackets = -1;
4150 continue; /* parameter loop */
4152 if (ch == '(' && !brackets)
4153 paren++;
4154 if (ch == ')' && brackets <= 0)
4155 if (--paren < 0)
4156 break;
4158 if (brackets < 0) {
4159 brackets = 0;
4160 error(ERR_NONFATAL, "braces do not "
4161 "enclose all of macro parameter");
4163 paramsize[nparam] += white + 1;
4164 white = 0;
4165 } /* parameter loop */
4166 nparam++;
4167 while (m && (m->nparam != nparam ||
4168 mstrcmp(m->name, mname,
4169 m->casesense)))
4170 m = m->next;
4171 if (!m)
4172 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4173 "macro `%s' exists, "
4174 "but not taking %d parameters",
4175 mstart->text, nparam);
4178 if (m && m->in_progress)
4179 m = NULL;
4180 if (!m) { /* in progess or didn't find '(' or wrong nparam */
4182 * Design question: should we handle !tline, which
4183 * indicates missing ')' here, or expand those
4184 * macros anyway, which requires the (t) test a few
4185 * lines down?
4187 nasm_free(params);
4188 nasm_free(paramsize);
4189 tline = mstart;
4190 } else {
4192 * Expand the macro: we are placed on the last token of the
4193 * call, so that we can easily split the call from the
4194 * following tokens. We also start by pushing an SMAC_END
4195 * token for the cycle removal.
4197 t = tline;
4198 if (t) {
4199 tline = t->next;
4200 t->next = NULL;
4202 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4203 tt->a.mac = m;
4204 m->in_progress = true;
4205 tline = tt;
4206 list_for_each(t, m->expansion) {
4207 if (t->type >= TOK_SMAC_PARAM) {
4208 Token *pcopy = tline, **ptail = &pcopy;
4209 Token *ttt, *pt;
4210 int i;
4212 ttt = params[t->type - TOK_SMAC_PARAM];
4213 i = paramsize[t->type - TOK_SMAC_PARAM];
4214 while (--i >= 0) {
4215 pt = *ptail = new_Token(tline, ttt->type,
4216 ttt->text, 0);
4217 ptail = &pt->next;
4218 ttt = ttt->next;
4220 tline = pcopy;
4221 } else if (t->type == TOK_PREPROC_Q) {
4222 tt = new_Token(tline, TOK_ID, mname, 0);
4223 tline = tt;
4224 } else if (t->type == TOK_PREPROC_QQ) {
4225 tt = new_Token(tline, TOK_ID, m->name, 0);
4226 tline = tt;
4227 } else {
4228 tt = new_Token(tline, t->type, t->text, 0);
4229 tline = tt;
4234 * Having done that, get rid of the macro call, and clean
4235 * up the parameters.
4237 nasm_free(params);
4238 nasm_free(paramsize);
4239 free_tlist(mstart);
4240 expanded = true;
4241 continue; /* main token loop */
4246 if (tline->type == TOK_SMAC_END) {
4247 tline->a.mac->in_progress = false;
4248 tline = delete_Token(tline);
4249 } else {
4250 t = *tail = tline;
4251 tline = tline->next;
4252 t->a.mac = NULL;
4253 t->next = NULL;
4254 tail = &t->next;
4259 * Now scan the entire line and look for successive TOK_IDs that resulted
4260 * after expansion (they can't be produced by tokenize()). The successive
4261 * TOK_IDs should be concatenated.
4262 * Also we look for %+ tokens and concatenate the tokens before and after
4263 * them (without white spaces in between).
4265 if (expanded && paste_tokens(&thead, true)) {
4267 * If we concatenated something, *and* we had previously expanded
4268 * an actual macro, scan the lines again for macros...
4270 tline = thead;
4271 expanded = false;
4272 goto again;
4275 err:
4276 if (org_tline) {
4277 if (thead) {
4278 *org_tline = *thead;
4279 /* since we just gave text to org_line, don't free it */
4280 thead->text = NULL;
4281 delete_Token(thead);
4282 } else {
4283 /* the expression expanded to empty line;
4284 we can't return NULL for some reasons
4285 we just set the line to a single WHITESPACE token. */
4286 memset(org_tline, 0, sizeof(*org_tline));
4287 org_tline->text = NULL;
4288 org_tline->type = TOK_WHITESPACE;
4290 thead = org_tline;
4293 return thead;
4297 * Similar to expand_smacro but used exclusively with macro identifiers
4298 * right before they are fetched in. The reason is that there can be
4299 * identifiers consisting of several subparts. We consider that if there
4300 * are more than one element forming the name, user wants a expansion,
4301 * otherwise it will be left as-is. Example:
4303 * %define %$abc cde
4305 * the identifier %$abc will be left as-is so that the handler for %define
4306 * will suck it and define the corresponding value. Other case:
4308 * %define _%$abc cde
4310 * In this case user wants name to be expanded *before* %define starts
4311 * working, so we'll expand %$abc into something (if it has a value;
4312 * otherwise it will be left as-is) then concatenate all successive
4313 * PP_IDs into one.
4315 static Token *expand_id(Token * tline)
4317 Token *cur, *oldnext = NULL;
4319 if (!tline || !tline->next)
4320 return tline;
4322 cur = tline;
4323 while (cur->next &&
4324 (cur->next->type == TOK_ID ||
4325 cur->next->type == TOK_PREPROC_ID
4326 || cur->next->type == TOK_NUMBER))
4327 cur = cur->next;
4329 /* If identifier consists of just one token, don't expand */
4330 if (cur == tline)
4331 return tline;
4333 if (cur) {
4334 oldnext = cur->next; /* Detach the tail past identifier */
4335 cur->next = NULL; /* so that expand_smacro stops here */
4338 tline = expand_smacro(tline);
4340 if (cur) {
4341 /* expand_smacro possibly changhed tline; re-scan for EOL */
4342 cur = tline;
4343 while (cur && cur->next)
4344 cur = cur->next;
4345 if (cur)
4346 cur->next = oldnext;
4349 return tline;
4353 * Determine whether the given line constitutes a multi-line macro
4354 * call, and return the MMacro structure called if so. Doesn't have
4355 * to check for an initial label - that's taken care of in
4356 * expand_mmacro - but must check numbers of parameters. Guaranteed
4357 * to be called with tline->type == TOK_ID, so the putative macro
4358 * name is easy to find.
4360 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4362 MMacro *head, *m;
4363 Token **params;
4364 int nparam;
4366 head = (MMacro *) hash_findix(&mmacros, tline->text);
4369 * Efficiency: first we see if any macro exists with the given
4370 * name. If not, we can return NULL immediately. _Then_ we
4371 * count the parameters, and then we look further along the
4372 * list if necessary to find the proper MMacro.
4374 list_for_each(m, head)
4375 if (!mstrcmp(m->name, tline->text, m->casesense))
4376 break;
4377 if (!m)
4378 return NULL;
4381 * OK, we have a potential macro. Count and demarcate the
4382 * parameters.
4384 count_mmac_params(tline->next, &nparam, &params);
4387 * So we know how many parameters we've got. Find the MMacro
4388 * structure that handles this number.
4390 while (m) {
4391 if (m->nparam_min <= nparam
4392 && (m->plus || nparam <= m->nparam_max)) {
4394 * This one is right. Just check if cycle removal
4395 * prohibits us using it before we actually celebrate...
4397 if (m->in_progress > m->max_depth) {
4398 if (m->max_depth > 0) {
4399 error(ERR_WARNING,
4400 "reached maximum recursion depth of %i",
4401 m->max_depth);
4403 nasm_free(params);
4404 return NULL;
4407 * It's right, and we can use it. Add its default
4408 * parameters to the end of our list if necessary.
4410 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4411 params =
4412 nasm_realloc(params,
4413 ((m->nparam_min + m->ndefs +
4414 1) * sizeof(*params)));
4415 while (nparam < m->nparam_min + m->ndefs) {
4416 params[nparam] = m->defaults[nparam - m->nparam_min];
4417 nparam++;
4421 * If we've gone over the maximum parameter count (and
4422 * we're in Plus mode), ignore parameters beyond
4423 * nparam_max.
4425 if (m->plus && nparam > m->nparam_max)
4426 nparam = m->nparam_max;
4428 * Then terminate the parameter list, and leave.
4430 if (!params) { /* need this special case */
4431 params = nasm_malloc(sizeof(*params));
4432 nparam = 0;
4434 params[nparam] = NULL;
4435 *params_array = params;
4436 return m;
4439 * This one wasn't right: look for the next one with the
4440 * same name.
4442 list_for_each(m, m->next)
4443 if (!mstrcmp(m->name, tline->text, m->casesense))
4444 break;
4448 * After all that, we didn't find one with the right number of
4449 * parameters. Issue a warning, and fail to expand the macro.
4451 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4452 "macro `%s' exists, but not taking %d parameters",
4453 tline->text, nparam);
4454 nasm_free(params);
4455 return NULL;
4460 * Save MMacro invocation specific fields in
4461 * preparation for a recursive macro expansion
4463 static void push_mmacro(MMacro *m)
4465 MMacroInvocation *i;
4467 i = nasm_malloc(sizeof(MMacroInvocation));
4468 i->prev = m->prev;
4469 i->params = m->params;
4470 i->iline = m->iline;
4471 i->nparam = m->nparam;
4472 i->rotate = m->rotate;
4473 i->paramlen = m->paramlen;
4474 i->unique = m->unique;
4475 i->condcnt = m->condcnt;
4476 m->prev = i;
4481 * Restore MMacro invocation specific fields that were
4482 * saved during a previous recursive macro expansion
4484 static void pop_mmacro(MMacro *m)
4486 MMacroInvocation *i;
4488 if (m->prev) {
4489 i = m->prev;
4490 m->prev = i->prev;
4491 m->params = i->params;
4492 m->iline = i->iline;
4493 m->nparam = i->nparam;
4494 m->rotate = i->rotate;
4495 m->paramlen = i->paramlen;
4496 m->unique = i->unique;
4497 m->condcnt = i->condcnt;
4498 nasm_free(i);
4504 * Expand the multi-line macro call made by the given line, if
4505 * there is one to be expanded. If there is, push the expansion on
4506 * istk->expansion and return 1. Otherwise return 0.
4508 static int expand_mmacro(Token * tline)
4510 Token *startline = tline;
4511 Token *label = NULL;
4512 int dont_prepend = 0;
4513 Token **params, *t, *mtok, *tt;
4514 MMacro *m;
4515 Line *l, *ll;
4516 int i, nparam, *paramlen;
4517 const char *mname;
4519 t = tline;
4520 skip_white_(t);
4521 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4522 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4523 return 0;
4524 mtok = t;
4525 m = is_mmacro(t, &params);
4526 if (m) {
4527 mname = t->text;
4528 } else {
4529 Token *last;
4531 * We have an id which isn't a macro call. We'll assume
4532 * it might be a label; we'll also check to see if a
4533 * colon follows it. Then, if there's another id after
4534 * that lot, we'll check it again for macro-hood.
4536 label = last = t;
4537 t = t->next;
4538 if (tok_type_(t, TOK_WHITESPACE))
4539 last = t, t = t->next;
4540 if (tok_is_(t, ":")) {
4541 dont_prepend = 1;
4542 last = t, t = t->next;
4543 if (tok_type_(t, TOK_WHITESPACE))
4544 last = t, t = t->next;
4546 if (!tok_type_(t, TOK_ID) || !(m = is_mmacro(t, &params)))
4547 return 0;
4548 last->next = NULL;
4549 mname = t->text;
4550 tline = t;
4554 * Fix up the parameters: this involves stripping leading and
4555 * trailing whitespace, then stripping braces if they are
4556 * present.
4558 for (nparam = 0; params[nparam]; nparam++) ;
4559 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4561 for (i = 0; params[i]; i++) {
4562 int brace = false;
4563 int comma = (!m->plus || i < nparam - 1);
4565 t = params[i];
4566 skip_white_(t);
4567 if (tok_is_(t, "{"))
4568 t = t->next, brace = true, comma = false;
4569 params[i] = t;
4570 paramlen[i] = 0;
4571 while (t) {
4572 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4573 break; /* ... because we have hit a comma */
4574 if (comma && t->type == TOK_WHITESPACE
4575 && tok_is_(t->next, ","))
4576 break; /* ... or a space then a comma */
4577 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4578 break; /* ... or a brace */
4579 t = t->next;
4580 paramlen[i]++;
4585 * OK, we have a MMacro structure together with a set of
4586 * parameters. We must now go through the expansion and push
4587 * copies of each Line on to istk->expansion. Substitution of
4588 * parameter tokens and macro-local tokens doesn't get done
4589 * until the single-line macro substitution process; this is
4590 * because delaying them allows us to change the semantics
4591 * later through %rotate.
4593 * First, push an end marker on to istk->expansion, mark this
4594 * macro as in progress, and set up its invocation-specific
4595 * variables.
4597 ll = nasm_malloc(sizeof(Line));
4598 ll->next = istk->expansion;
4599 ll->finishes = m;
4600 ll->first = NULL;
4601 istk->expansion = ll;
4604 * Save the previous MMacro expansion in the case of
4605 * macro recursion
4607 if (m->max_depth && m->in_progress)
4608 push_mmacro(m);
4610 m->in_progress ++;
4611 m->params = params;
4612 m->iline = tline;
4613 m->nparam = nparam;
4614 m->rotate = 0;
4615 m->paramlen = paramlen;
4616 m->unique = unique++;
4617 m->lineno = 0;
4618 m->condcnt = 0;
4620 m->next_active = istk->mstk;
4621 istk->mstk = m;
4623 list_for_each(l, m->expansion) {
4624 Token **tail;
4626 ll = nasm_malloc(sizeof(Line));
4627 ll->finishes = NULL;
4628 ll->next = istk->expansion;
4629 istk->expansion = ll;
4630 tail = &ll->first;
4632 list_for_each(t, l->first) {
4633 Token *x = t;
4634 switch (t->type) {
4635 case TOK_PREPROC_Q:
4636 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4637 break;
4638 case TOK_PREPROC_QQ:
4639 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4640 break;
4641 case TOK_PREPROC_ID:
4642 if (t->text[1] == '0' && t->text[2] == '0') {
4643 dont_prepend = -1;
4644 x = label;
4645 if (!x)
4646 continue;
4648 /* fall through */
4649 default:
4650 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4651 break;
4653 tail = &tt->next;
4655 *tail = NULL;
4659 * If we had a label, push it on as the first line of
4660 * the macro expansion.
4662 if (label) {
4663 if (dont_prepend < 0)
4664 free_tlist(startline);
4665 else {
4666 ll = nasm_malloc(sizeof(Line));
4667 ll->finishes = NULL;
4668 ll->next = istk->expansion;
4669 istk->expansion = ll;
4670 ll->first = startline;
4671 if (!dont_prepend) {
4672 while (label->next)
4673 label = label->next;
4674 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4679 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4681 return 1;
4684 /* The function that actually does the error reporting */
4685 static void verror(int severity, const char *fmt, va_list arg)
4687 char buff[1024];
4689 vsnprintf(buff, sizeof(buff), fmt, arg);
4691 if (istk && istk->mstk && istk->mstk->name)
4692 nasm_error(severity, "(%s:%d) %s", istk->mstk->name,
4693 istk->mstk->lineno, buff);
4694 else
4695 nasm_error(severity, "%s", buff);
4699 * Since preprocessor always operate only on the line that didn't
4700 * arrived yet, we should always use ERR_OFFBY1.
4702 static void error(int severity, const char *fmt, ...)
4704 va_list arg;
4706 /* If we're in a dead branch of IF or something like it, ignore the error */
4707 if (istk && istk->conds && !emitting(istk->conds->state))
4708 return;
4710 va_start(arg, fmt);
4711 verror(severity, fmt, arg);
4712 va_end(arg);
4716 * Because %else etc are evaluated in the state context
4717 * of the previous branch, errors might get lost with error():
4718 * %if 0 ... %else trailing garbage ... %endif
4719 * So %else etc should report errors with this function.
4721 static void error_precond(int severity, const char *fmt, ...)
4723 va_list arg;
4725 /* Only ignore the error if it's really in a dead branch */
4726 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4727 return;
4729 va_start(arg, fmt);
4730 verror(severity, fmt, arg);
4731 va_end(arg);
4734 static void
4735 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
4737 Token *t;
4739 cstk = NULL;
4740 istk = nasm_malloc(sizeof(Include));
4741 istk->next = NULL;
4742 istk->conds = NULL;
4743 istk->expansion = NULL;
4744 istk->mstk = NULL;
4745 istk->fp = fopen(file, "r");
4746 istk->fname = NULL;
4747 src_set_fname(nasm_strdup(file));
4748 src_set_linnum(0);
4749 istk->lineinc = 1;
4750 if (!istk->fp)
4751 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4752 file);
4753 defining = NULL;
4754 nested_mac_count = 0;
4755 nested_rep_count = 0;
4756 init_macros();
4757 unique = 0;
4758 if (tasm_compatible_mode) {
4759 stdmacpos = nasm_stdmac;
4760 } else {
4761 stdmacpos = nasm_stdmac_after_tasm;
4763 any_extrastdmac = extrastdmac && *extrastdmac;
4764 do_predef = true;
4765 list = listgen;
4768 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4769 * The caller, however, will also pass in 3 for preprocess-only so
4770 * we can set __PASS__ accordingly.
4772 pass = apass > 2 ? 2 : apass;
4774 dephead = deptail = deplist;
4775 if (deplist) {
4776 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4777 sl->next = NULL;
4778 strcpy(sl->str, file);
4779 *deptail = sl;
4780 deptail = &sl->next;
4784 * Define the __PASS__ macro. This is defined here unlike
4785 * all the other builtins, because it is special -- it varies between
4786 * passes.
4788 t = nasm_malloc(sizeof(*t));
4789 t->next = NULL;
4790 make_tok_num(t, apass);
4791 t->a.mac = NULL;
4792 define_smacro(NULL, "__PASS__", true, 0, t);
4795 static char *pp_getline(void)
4797 char *line;
4798 Token *tline;
4800 while (1) {
4802 * Fetch a tokenized line, either from the macro-expansion
4803 * buffer or from the input file.
4805 tline = NULL;
4806 while (istk->expansion && istk->expansion->finishes) {
4807 Line *l = istk->expansion;
4808 if (!l->finishes->name && l->finishes->in_progress > 1) {
4809 Line *ll;
4812 * This is a macro-end marker for a macro with no
4813 * name, which means it's not really a macro at all
4814 * but a %rep block, and the `in_progress' field is
4815 * more than 1, meaning that we still need to
4816 * repeat. (1 means the natural last repetition; 0
4817 * means termination by %exitrep.) We have
4818 * therefore expanded up to the %endrep, and must
4819 * push the whole block on to the expansion buffer
4820 * again. We don't bother to remove the macro-end
4821 * marker: we'd only have to generate another one
4822 * if we did.
4824 l->finishes->in_progress--;
4825 list_for_each(l, l->finishes->expansion) {
4826 Token *t, *tt, **tail;
4828 ll = nasm_malloc(sizeof(Line));
4829 ll->next = istk->expansion;
4830 ll->finishes = NULL;
4831 ll->first = NULL;
4832 tail = &ll->first;
4834 list_for_each(t, l->first) {
4835 if (t->text || t->type == TOK_WHITESPACE) {
4836 tt = *tail = new_Token(NULL, t->type, t->text, 0);
4837 tail = &tt->next;
4841 istk->expansion = ll;
4843 } else {
4845 * Check whether a `%rep' was started and not ended
4846 * within this macro expansion. This can happen and
4847 * should be detected. It's a fatal error because
4848 * I'm too confused to work out how to recover
4849 * sensibly from it.
4851 if (defining) {
4852 if (defining->name)
4853 error(ERR_PANIC,
4854 "defining with name in expansion");
4855 else if (istk->mstk->name)
4856 error(ERR_FATAL,
4857 "`%%rep' without `%%endrep' within"
4858 " expansion of macro `%s'",
4859 istk->mstk->name);
4863 * FIXME: investigate the relationship at this point between
4864 * istk->mstk and l->finishes
4867 MMacro *m = istk->mstk;
4868 istk->mstk = m->next_active;
4869 if (m->name) {
4871 * This was a real macro call, not a %rep, and
4872 * therefore the parameter information needs to
4873 * be freed.
4875 if (m->prev) {
4876 pop_mmacro(m);
4877 l->finishes->in_progress --;
4878 } else {
4879 nasm_free(m->params);
4880 free_tlist(m->iline);
4881 nasm_free(m->paramlen);
4882 l->finishes->in_progress = 0;
4884 } else
4885 free_mmacro(m);
4887 istk->expansion = l->next;
4888 nasm_free(l);
4889 list->downlevel(LIST_MACRO);
4892 while (1) { /* until we get a line we can use */
4894 if (istk->expansion) { /* from a macro expansion */
4895 char *p;
4896 Line *l = istk->expansion;
4897 if (istk->mstk)
4898 istk->mstk->lineno++;
4899 tline = l->first;
4900 istk->expansion = l->next;
4901 nasm_free(l);
4902 p = detoken(tline, false);
4903 list->line(LIST_MACRO, p);
4904 nasm_free(p);
4905 break;
4907 line = read_line();
4908 if (line) { /* from the current input file */
4909 line = prepreproc(line);
4910 tline = tokenize(line);
4911 nasm_free(line);
4912 break;
4915 * The current file has ended; work down the istk
4918 Include *i = istk;
4919 fclose(i->fp);
4920 if (i->conds)
4921 error(ERR_FATAL,
4922 "expected `%%endif' before end of file");
4923 /* only set line and file name if there's a next node */
4924 if (i->next) {
4925 src_set_linnum(i->lineno);
4926 nasm_free(src_set_fname(i->fname));
4928 istk = i->next;
4929 list->downlevel(LIST_INCLUDE);
4930 nasm_free(i);
4931 if (!istk)
4932 return NULL;
4933 if (istk->expansion && istk->expansion->finishes)
4934 break;
4939 * We must expand MMacro parameters and MMacro-local labels
4940 * _before_ we plunge into directive processing, to cope
4941 * with things like `%define something %1' such as STRUC
4942 * uses. Unless we're _defining_ a MMacro, in which case
4943 * those tokens should be left alone to go into the
4944 * definition; and unless we're in a non-emitting
4945 * condition, in which case we don't want to meddle with
4946 * anything.
4948 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4949 && !(istk->mstk && !istk->mstk->in_progress)) {
4950 tline = expand_mmac_params(tline);
4954 * Check the line to see if it's a preprocessor directive.
4956 if (do_directive(tline) == DIRECTIVE_FOUND) {
4957 continue;
4958 } else if (defining) {
4960 * We're defining a multi-line macro. We emit nothing
4961 * at all, and just
4962 * shove the tokenized line on to the macro definition.
4964 Line *l = nasm_malloc(sizeof(Line));
4965 l->next = defining->expansion;
4966 l->first = tline;
4967 l->finishes = NULL;
4968 defining->expansion = l;
4969 continue;
4970 } else if (istk->conds && !emitting(istk->conds->state)) {
4972 * We're in a non-emitting branch of a condition block.
4973 * Emit nothing at all, not even a blank line: when we
4974 * emerge from the condition we'll give a line-number
4975 * directive so we keep our place correctly.
4977 free_tlist(tline);
4978 continue;
4979 } else if (istk->mstk && !istk->mstk->in_progress) {
4981 * We're in a %rep block which has been terminated, so
4982 * we're walking through to the %endrep without
4983 * emitting anything. Emit nothing at all, not even a
4984 * blank line: when we emerge from the %rep block we'll
4985 * give a line-number directive so we keep our place
4986 * correctly.
4988 free_tlist(tline);
4989 continue;
4990 } else {
4991 tline = expand_smacro(tline);
4992 if (!expand_mmacro(tline)) {
4994 * De-tokenize the line again, and emit it.
4996 line = detoken(tline, true);
4997 free_tlist(tline);
4998 break;
4999 } else {
5000 continue; /* expand_mmacro calls free_tlist */
5005 return line;
5008 static void pp_cleanup(int pass)
5010 if (defining) {
5011 if (defining->name) {
5012 error(ERR_NONFATAL,
5013 "end of file while still defining macro `%s'",
5014 defining->name);
5015 } else {
5016 error(ERR_NONFATAL, "end of file while still in %%rep");
5019 free_mmacro(defining);
5020 defining = NULL;
5022 while (cstk)
5023 ctx_pop();
5024 free_macros();
5025 while (istk) {
5026 Include *i = istk;
5027 istk = istk->next;
5028 fclose(i->fp);
5029 nasm_free(i->fname);
5030 nasm_free(i);
5032 while (cstk)
5033 ctx_pop();
5034 nasm_free(src_set_fname(NULL));
5035 if (pass == 0) {
5036 IncPath *i;
5037 free_llist(predef);
5038 delete_Blocks();
5039 while ((i = ipath)) {
5040 ipath = i->next;
5041 if (i->path)
5042 nasm_free(i->path);
5043 nasm_free(i);
5048 void pp_include_path(char *path)
5050 IncPath *i;
5052 i = nasm_malloc(sizeof(IncPath));
5053 i->path = path ? nasm_strdup(path) : NULL;
5054 i->next = NULL;
5056 if (ipath) {
5057 IncPath *j = ipath;
5058 while (j->next)
5059 j = j->next;
5060 j->next = i;
5061 } else {
5062 ipath = i;
5066 void pp_pre_include(char *fname)
5068 Token *inc, *space, *name;
5069 Line *l;
5071 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
5072 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
5073 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
5075 l = nasm_malloc(sizeof(Line));
5076 l->next = predef;
5077 l->first = inc;
5078 l->finishes = NULL;
5079 predef = l;
5082 void pp_pre_define(char *definition)
5084 Token *def, *space;
5085 Line *l;
5086 char *equals;
5088 equals = strchr(definition, '=');
5089 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5090 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
5091 if (equals)
5092 *equals = ' ';
5093 space->next = tokenize(definition);
5094 if (equals)
5095 *equals = '=';
5097 l = nasm_malloc(sizeof(Line));
5098 l->next = predef;
5099 l->first = def;
5100 l->finishes = NULL;
5101 predef = l;
5104 void pp_pre_undefine(char *definition)
5106 Token *def, *space;
5107 Line *l;
5109 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5110 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
5111 space->next = tokenize(definition);
5113 l = nasm_malloc(sizeof(Line));
5114 l->next = predef;
5115 l->first = def;
5116 l->finishes = NULL;
5117 predef = l;
5121 * Added by Keith Kanios:
5123 * This function is used to assist with "runtime" preprocessor
5124 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5126 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5127 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5130 void pp_runtime(char *definition)
5132 Token *def;
5134 def = tokenize(definition);
5135 if (do_directive(def) == NO_DIRECTIVE_FOUND)
5136 free_tlist(def);
5140 void pp_extra_stdmac(macros_t *macros)
5142 extrastdmac = macros;
5145 static void make_tok_num(Token * tok, int64_t val)
5147 char numbuf[20];
5148 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
5149 tok->text = nasm_strdup(numbuf);
5150 tok->type = TOK_NUMBER;
5153 Preproc nasmpp = {
5154 pp_reset,
5155 pp_getline,
5156 pp_cleanup