doc/changes.src: Restore empty line.
[nasm.git] / preproc.c
blobc076066e6b196364861ac1a76ee5abf8e92c23a9
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
44 * or
45 * {
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
48 * }
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
63 #include "compiler.h"
65 #include <stdio.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <stddef.h>
69 #include <string.h>
70 #include <ctype.h>
71 #include <limits.h>
72 #include <inttypes.h>
74 #include "nasm.h"
75 #include "nasmlib.h"
76 #include "preproc.h"
77 #include "hashtbl.h"
78 #include "quote.h"
79 #include "stdscan.h"
80 #include "eval.h"
81 #include "tokens.h"
82 #include "tables.h"
84 typedef struct SMacro SMacro;
85 typedef struct MMacro MMacro;
86 typedef struct MMacroInvocation MMacroInvocation;
87 typedef struct Context Context;
88 typedef struct Token Token;
89 typedef struct Blocks Blocks;
90 typedef struct Line Line;
91 typedef struct Include Include;
92 typedef struct Cond Cond;
93 typedef struct IncPath IncPath;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
107 struct SMacro {
108 SMacro *next;
109 char *name;
110 bool casesense;
111 bool in_progress;
112 unsigned int nparam;
113 Token *expansion;
117 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
125 * run.
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
133 struct MMacro {
134 MMacro *next;
135 MMacroInvocation *prev; /* previous invocation */
136 char *name;
137 int nparam_min, nparam_max;
138 bool casesense;
139 bool plus; /* is the last parameter greedy? */
140 bool nolist; /* is this macro listing-inhibited? */
141 int64_t in_progress; /* is this macro currently being expanded? */
142 int32_t max_depth; /* maximum number of recursive expansions allowed */
143 Token *dlist; /* All defaults as one list */
144 Token **defaults; /* Parameter default pointers */
145 int ndefs; /* number of default parameters */
146 Line *expansion;
148 MMacro *next_active;
149 MMacro *rep_nest; /* used for nesting %rep */
150 Token **params; /* actual parameters */
151 Token *iline; /* invocation line */
152 unsigned int nparam, rotate;
153 int *paramlen;
154 uint64_t unique;
155 int lineno; /* Current line number on expansion */
156 uint64_t condcnt; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation {
164 MMacroInvocation *prev; /* previous invocation */
165 Token **params; /* actual parameters */
166 Token *iline; /* invocation line */
167 unsigned int nparam, rotate;
168 int *paramlen;
169 uint64_t unique;
170 uint64_t condcnt;
175 * The context stack is composed of a linked list of these.
177 struct Context {
178 Context *next;
179 char *name;
180 struct hash_table localmac;
181 uint32_t number;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
196 * TOK_SMAC_PARAM+1.
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
203 enum pp_token_type {
204 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
205 TOK_PREPROC_ID, TOK_STRING,
206 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
207 TOK_INTERNAL_STRING,
208 TOK_PREPROC_Q, TOK_PREPROC_QQ,
209 TOK_PASTE, /* %+ */
210 TOK_INDIRECT, /* %[...] */
211 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
215 struct Token {
216 Token *next;
217 char *text;
218 union {
219 SMacro *mac; /* associated macro for TOK_SMAC_END */
220 size_t len; /* scratch length field */
221 } a; /* Auxiliary data */
222 enum pp_token_type type;
226 * Multi-line macro definitions are stored as a linked list of
227 * these, which is essentially a container to allow several linked
228 * lists of Tokens.
230 * Note that in this module, linked lists are treated as stacks
231 * wherever possible. For this reason, Lines are _pushed_ on to the
232 * `expansion' field in MMacro structures, so that the linked list,
233 * if walked, would give the macro lines in reverse order; this
234 * means that we can walk the list when expanding a macro, and thus
235 * push the lines on to the `expansion' field in _istk_ in reverse
236 * order (so that when popped back off they are in the right
237 * order). It may seem cockeyed, and it relies on my design having
238 * an even number of steps in, but it works...
240 * Some of these structures, rather than being actual lines, are
241 * markers delimiting the end of the expansion of a given macro.
242 * This is for use in the cycle-tracking and %rep-handling code.
243 * Such structures have `finishes' non-NULL, and `first' NULL. All
244 * others have `finishes' NULL, but `first' may still be NULL if
245 * the line is blank.
247 struct Line {
248 Line *next;
249 MMacro *finishes;
250 Token *first;
254 * To handle an arbitrary level of file inclusion, we maintain a
255 * stack (ie linked list) of these things.
257 struct Include {
258 Include *next;
259 FILE *fp;
260 Cond *conds;
261 Line *expansion;
262 char *fname;
263 int lineno, lineinc;
264 MMacro *mstk; /* stack of active macros/reps */
268 * Include search path. This is simply a list of strings which get
269 * prepended, in turn, to the name of an include file, in an
270 * attempt to find the file if it's not in the current directory.
272 struct IncPath {
273 IncPath *next;
274 char *path;
278 * Conditional assembly: we maintain a separate stack of these for
279 * each level of file inclusion. (The only reason we keep the
280 * stacks separate is to ensure that a stray `%endif' in a file
281 * included from within the true branch of a `%if' won't terminate
282 * it and cause confusion: instead, rightly, it'll cause an error.)
284 struct Cond {
285 Cond *next;
286 int state;
288 enum {
290 * These states are for use just after %if or %elif: IF_TRUE
291 * means the condition has evaluated to truth so we are
292 * currently emitting, whereas IF_FALSE means we are not
293 * currently emitting but will start doing so if a %else comes
294 * up. In these states, all directives are admissible: %elif,
295 * %else and %endif. (And of course %if.)
297 COND_IF_TRUE, COND_IF_FALSE,
299 * These states come up after a %else: ELSE_TRUE means we're
300 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
301 * any %elif or %else will cause an error.
303 COND_ELSE_TRUE, COND_ELSE_FALSE,
305 * These states mean that we're not emitting now, and also that
306 * nothing until %endif will be emitted at all. COND_DONE is
307 * used when we've had our moment of emission
308 * and have now started seeing %elifs. COND_NEVER is used when
309 * the condition construct in question is contained within a
310 * non-emitting branch of a larger condition construct,
311 * or if there is an error.
313 COND_DONE, COND_NEVER
315 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
318 * These defines are used as the possible return values for do_directive
320 #define NO_DIRECTIVE_FOUND 0
321 #define DIRECTIVE_FOUND 1
324 * This define sets the upper limit for smacro and recursive mmacro
325 * expansions
327 #define DEADMAN_LIMIT (1 << 20)
330 * Condition codes. Note that we use c_ prefix not C_ because C_ is
331 * used in nasm.h for the "real" condition codes. At _this_ level,
332 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
333 * ones, so we need a different enum...
335 static const char * const conditions[] = {
336 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
337 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
338 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
340 enum pp_conds {
341 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
342 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
343 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
344 c_none = -1
346 static const enum pp_conds inverse_ccs[] = {
347 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
348 c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
349 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
353 * Directive names.
355 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
356 static int is_condition(enum preproc_token arg)
358 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
361 /* For TASM compatibility we need to be able to recognise TASM compatible
362 * conditional compilation directives. Using the NASM pre-processor does
363 * not work, so we look for them specifically from the following list and
364 * then jam in the equivalent NASM directive into the input stream.
367 enum {
368 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
369 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
372 static const char * const tasm_directives[] = {
373 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
374 "ifndef", "include", "local"
377 static int StackSize = 4;
378 static char *StackPointer = "ebp";
379 static int ArgOffset = 8;
380 static int LocalOffset = 0;
382 static Context *cstk;
383 static Include *istk;
384 static IncPath *ipath = NULL;
386 static int pass; /* HACK: pass 0 = generate dependencies only */
387 static StrList **dephead, **deptail; /* Dependency list */
389 static uint64_t unique; /* unique identifier numbers */
391 static Line *predef = NULL;
392 static bool do_predef;
394 static ListGen *list;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro *defining;
412 static uint64_t nested_mac_count;
413 static uint64_t nested_rep_count;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t *stdmacpos;
427 * The extra standard macros that come from the object format, if
428 * any.
430 static macros_t *extrastdmac = NULL;
431 static bool any_extrastdmac;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token *freeTokens = NULL;
438 struct Blocks {
439 Blocks *next;
440 void *chunk;
443 static Blocks blocks = { NULL, NULL };
446 * Forward declarations.
448 static Token *expand_mmac_params(Token * tline);
449 static Token *expand_smacro(Token * tline);
450 static Token *expand_id(Token * tline);
451 static Context *get_ctx(const char *name, const char **namep,
452 bool all_contexts);
453 static void make_tok_num(Token * tok, int64_t val);
454 static void error(int severity, const char *fmt, ...);
455 static void error_precond(int severity, const char *fmt, ...);
456 static void *new_Block(size_t size);
457 static void delete_Blocks(void);
458 static Token *new_Token(Token * next, enum pp_token_type type,
459 const char *text, int txtlen);
460 static Token *delete_Token(Token * t);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * Handle TASM specific directives, which do not contain a % in
472 * front of them. We do it here because I could not find any other
473 * place to do it for the moment, and it is a hack (ideally it would
474 * be nice to be able to use the NASM pre-processor to do it).
476 static char *check_tasm_directive(char *line)
478 int32_t i, j, k, m, len;
479 char *p, *q, *oldline, oldchar;
481 p = nasm_skip_spaces(line);
483 /* Binary search for the directive name */
484 i = -1;
485 j = elements(tasm_directives);
486 q = nasm_skip_word(p);
487 len = q - p;
488 if (len) {
489 oldchar = p[len];
490 p[len] = 0;
491 while (j - i > 1) {
492 k = (j + i) / 2;
493 m = nasm_stricmp(p, tasm_directives[k]);
494 if (m == 0) {
495 /* We have found a directive, so jam a % in front of it
496 * so that NASM will then recognise it as one if it's own.
498 p[len] = oldchar;
499 len = strlen(p);
500 oldline = line;
501 line = nasm_malloc(len + 2);
502 line[0] = '%';
503 if (k == TM_IFDIFI) {
505 * NASM does not recognise IFDIFI, so we convert
506 * it to %if 0. This is not used in NASM
507 * compatible code, but does need to parse for the
508 * TASM macro package.
510 strcpy(line + 1, "if 0");
511 } else {
512 memcpy(line + 1, p, len + 1);
514 nasm_free(oldline);
515 return line;
516 } else if (m < 0) {
517 j = k;
518 } else
519 i = k;
521 p[len] = oldchar;
523 return line;
527 * The pre-preprocessing stage... This function translates line
528 * number indications as they emerge from GNU cpp (`# lineno "file"
529 * flags') into NASM preprocessor line number indications (`%line
530 * lineno file').
532 static char *prepreproc(char *line)
534 int lineno, fnlen;
535 char *fname, *oldline;
537 if (line[0] == '#' && line[1] == ' ') {
538 oldline = line;
539 fname = oldline + 2;
540 lineno = atoi(fname);
541 fname += strspn(fname, "0123456789 ");
542 if (*fname == '"')
543 fname++;
544 fnlen = strcspn(fname, "\"");
545 line = nasm_malloc(20 + fnlen);
546 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
547 nasm_free(oldline);
549 if (tasm_compatible_mode)
550 return check_tasm_directive(line);
551 return line;
555 * Free a linked list of tokens.
557 static void free_tlist(Token * list)
559 while (list) {
560 list = delete_Token(list);
565 * Free a linked list of lines.
567 static void free_llist(Line * list)
569 Line *l;
570 while (list) {
571 l = list;
572 list = list->next;
573 free_tlist(l->first);
574 nasm_free(l);
579 * Free an MMacro
581 static void free_mmacro(MMacro * m)
583 nasm_free(m->name);
584 free_tlist(m->dlist);
585 nasm_free(m->defaults);
586 free_llist(m->expansion);
587 nasm_free(m);
591 * Free all currently defined macros, and free the hash tables
593 static void free_smacro_table(struct hash_table *smt)
595 SMacro *s;
596 const char *key;
597 struct hash_tbl_node *it = NULL;
599 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
600 nasm_free((void *)key);
601 while (s) {
602 SMacro *ns = s->next;
603 nasm_free(s->name);
604 free_tlist(s->expansion);
605 nasm_free(s);
606 s = ns;
609 hash_free(smt);
612 static void free_mmacro_table(struct hash_table *mmt)
614 MMacro *m;
615 const char *key;
616 struct hash_tbl_node *it = NULL;
618 it = NULL;
619 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
620 nasm_free((void *)key);
621 while (m) {
622 MMacro *nm = m->next;
623 free_mmacro(m);
624 m = nm;
627 hash_free(mmt);
630 static void free_macros(void)
632 free_smacro_table(&smacros);
633 free_mmacro_table(&mmacros);
637 * Initialize the hash tables
639 static void init_macros(void)
641 hash_init(&smacros, HASH_LARGE);
642 hash_init(&mmacros, HASH_LARGE);
646 * Pop the context stack.
648 static void ctx_pop(void)
650 Context *c = cstk;
652 cstk = cstk->next;
653 free_smacro_table(&c->localmac);
654 nasm_free(c->name);
655 nasm_free(c);
659 * Search for a key in the hash index; adding it if necessary
660 * (in which case we initialize the data pointer to NULL.)
662 static void **
663 hash_findi_add(struct hash_table *hash, const char *str)
665 struct hash_insert hi;
666 void **r;
667 char *strx;
669 r = hash_findi(hash, str, &hi);
670 if (r)
671 return r;
673 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
674 return hash_add(&hi, strx, NULL);
678 * Like hash_findi, but returns the data element rather than a pointer
679 * to it. Used only when not adding a new element, hence no third
680 * argument.
682 static void *
683 hash_findix(struct hash_table *hash, const char *str)
685 void **p;
687 p = hash_findi(hash, str, NULL);
688 return p ? *p : NULL;
691 #define BUF_DELTA 512
693 * Read a line from the top file in istk, handling multiple CR/LFs
694 * at the end of the line read, and handling spurious ^Zs. Will
695 * return lines from the standard macro set if this has not already
696 * been done.
698 static char *read_line(void)
700 char *buffer, *p, *q;
701 int bufsize, continued_count;
703 if (stdmacpos) {
704 unsigned char c;
705 const unsigned char *p = stdmacpos;
706 char *ret, *q;
707 size_t len = 0;
708 while ((c = *p++)) {
709 if (c >= 0x80)
710 len += pp_directives_len[c-0x80]+1;
711 else
712 len++;
714 ret = nasm_malloc(len+1);
715 q = ret;
716 while ((c = *stdmacpos++)) {
717 if (c >= 0x80) {
718 memcpy(q, pp_directives[c-0x80], pp_directives_len[c-0x80]);
719 q += pp_directives_len[c-0x80];
720 *q++ = ' ';
721 } else {
722 *q++ = c;
725 stdmacpos = p;
726 *q = '\0';
728 if (!*stdmacpos) {
729 /* This was the last of the standard macro chain... */
730 stdmacpos = NULL;
731 if (any_extrastdmac) {
732 stdmacpos = extrastdmac;
733 any_extrastdmac = false;
734 } else if (do_predef) {
735 Line *pd, *l;
736 Token *head, **tail, *t;
739 * Nasty hack: here we push the contents of
740 * `predef' on to the top-level expansion stack,
741 * since this is the most convenient way to
742 * implement the pre-include and pre-define
743 * features.
745 for (pd = predef; pd; pd = pd->next) {
746 head = NULL;
747 tail = &head;
748 for (t = pd->first; t; t = t->next) {
749 *tail = new_Token(NULL, t->type, t->text, 0);
750 tail = &(*tail)->next;
752 l = nasm_malloc(sizeof(Line));
753 l->next = istk->expansion;
754 l->first = head;
755 l->finishes = NULL;
756 istk->expansion = l;
758 do_predef = false;
761 return ret;
764 bufsize = BUF_DELTA;
765 buffer = nasm_malloc(BUF_DELTA);
766 p = buffer;
767 continued_count = 0;
768 while (1) {
769 q = fgets(p, bufsize - (p - buffer), istk->fp);
770 if (!q)
771 break;
772 p += strlen(p);
773 if (p > buffer && p[-1] == '\n') {
775 * Convert backslash-CRLF line continuation sequences into
776 * nothing at all (for DOS and Windows)
778 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
779 p -= 3;
780 *p = 0;
781 continued_count++;
784 * Also convert backslash-LF line continuation sequences into
785 * nothing at all (for Unix)
787 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
788 p -= 2;
789 *p = 0;
790 continued_count++;
791 } else {
792 break;
795 if (p - buffer > bufsize - 10) {
796 int32_t offset = p - buffer;
797 bufsize += BUF_DELTA;
798 buffer = nasm_realloc(buffer, bufsize);
799 p = buffer + offset; /* prevent stale-pointer problems */
803 if (!q && p == buffer) {
804 nasm_free(buffer);
805 return NULL;
808 src_set_linnum(src_get_linnum() + istk->lineinc +
809 (continued_count * istk->lineinc));
812 * Play safe: remove CRs as well as LFs, if any of either are
813 * present at the end of the line.
815 while (--p >= buffer && (*p == '\n' || *p == '\r'))
816 *p = '\0';
819 * Handle spurious ^Z, which may be inserted into source files
820 * by some file transfer utilities.
822 buffer[strcspn(buffer, "\032")] = '\0';
824 list->line(LIST_READ, buffer);
826 return buffer;
830 * Tokenize a line of text. This is a very simple process since we
831 * don't need to parse the value out of e.g. numeric tokens: we
832 * simply split one string into many.
834 static Token *tokenize(char *line)
836 char c, *p = line;
837 enum pp_token_type type;
838 Token *list = NULL;
839 Token *t, **tail = &list;
841 while (*line) {
842 p = line;
843 if (*p == '%') {
844 p++;
845 if (*p == '+' && !nasm_isdigit(p[1])) {
846 p++;
847 type = TOK_PASTE;
848 } else if (nasm_isdigit(*p) ||
849 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
850 do {
851 p++;
853 while (nasm_isdigit(*p));
854 type = TOK_PREPROC_ID;
855 } else if (*p == '{') {
856 p++;
857 while (*p && *p != '}') {
858 p[-1] = *p;
859 p++;
861 p[-1] = '\0';
862 if (*p)
863 p++;
864 type = TOK_PREPROC_ID;
865 } else if (*p == '[') {
866 int lvl = 1;
867 line += 2; /* Skip the leading %[ */
868 p++;
869 while (lvl && (c = *p++)) {
870 switch (c) {
871 case ']':
872 lvl--;
873 break;
874 case '%':
875 if (*p == '[')
876 lvl++;
877 break;
878 case '\'':
879 case '\"':
880 case '`':
881 p = nasm_skip_string(p)+1;
882 break;
883 default:
884 break;
887 p--;
888 if (*p)
889 *p++ = '\0';
890 if (lvl)
891 error(ERR_NONFATAL, "unterminated %[ construct");
892 type = TOK_INDIRECT;
893 } else if (*p == '?') {
894 type = TOK_PREPROC_Q; /* %? */
895 p++;
896 if (*p == '?') {
897 type = TOK_PREPROC_QQ; /* %?? */
898 p++;
900 } else if (isidchar(*p) ||
901 ((*p == '!' || *p == '%' || *p == '$') &&
902 isidchar(p[1]))) {
903 do {
904 p++;
906 while (isidchar(*p));
907 type = TOK_PREPROC_ID;
908 } else {
909 type = TOK_OTHER;
910 if (*p == '%')
911 p++;
913 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
914 type = TOK_ID;
915 p++;
916 while (*p && isidchar(*p))
917 p++;
918 } else if (*p == '\'' || *p == '"' || *p == '`') {
920 * A string token.
922 type = TOK_STRING;
923 p = nasm_skip_string(p);
925 if (*p) {
926 p++;
927 } else {
928 error(ERR_WARNING|ERR_PASS1, "unterminated string");
929 /* Handling unterminated strings by UNV */
930 /* type = -1; */
932 } else if (p[0] == '$' && p[1] == '$') {
933 type = TOK_OTHER; /* TOKEN_BASE */
934 p += 2;
935 } else if (isnumstart(*p)) {
936 bool is_hex = false;
937 bool is_float = false;
938 bool has_e = false;
939 char c, *r;
942 * A numeric token.
945 if (*p == '$') {
946 p++;
947 is_hex = true;
950 for (;;) {
951 c = *p++;
953 if (!is_hex && (c == 'e' || c == 'E')) {
954 has_e = true;
955 if (*p == '+' || *p == '-') {
957 * e can only be followed by +/- if it is either a
958 * prefixed hex number or a floating-point number
960 p++;
961 is_float = true;
963 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
964 is_hex = true;
965 } else if (c == 'P' || c == 'p') {
966 is_float = true;
967 if (*p == '+' || *p == '-')
968 p++;
969 } else if (isnumchar(c) || c == '_')
970 ; /* just advance */
971 else if (c == '.') {
973 * we need to deal with consequences of the legacy
974 * parser, like "1.nolist" being two tokens
975 * (TOK_NUMBER, TOK_ID) here; at least give it
976 * a shot for now. In the future, we probably need
977 * a flex-based scanner with proper pattern matching
978 * to do it as well as it can be done. Nothing in
979 * the world is going to help the person who wants
980 * 0x123.p16 interpreted as two tokens, though.
982 r = p;
983 while (*r == '_')
984 r++;
986 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
987 (!is_hex && (*r == 'e' || *r == 'E')) ||
988 (*r == 'p' || *r == 'P')) {
989 p = r;
990 is_float = true;
991 } else
992 break; /* Terminate the token */
993 } else
994 break;
996 p--; /* Point to first character beyond number */
998 if (p == line+1 && *line == '$') {
999 type = TOK_OTHER; /* TOKEN_HERE */
1000 } else {
1001 if (has_e && !is_hex) {
1002 /* 1e13 is floating-point, but 1e13h is not */
1003 is_float = true;
1006 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1008 } else if (nasm_isspace(*p)) {
1009 type = TOK_WHITESPACE;
1010 p = nasm_skip_spaces(p);
1012 * Whitespace just before end-of-line is discarded by
1013 * pretending it's a comment; whitespace just before a
1014 * comment gets lumped into the comment.
1016 if (!*p || *p == ';') {
1017 type = TOK_COMMENT;
1018 while (*p)
1019 p++;
1021 } else if (*p == ';') {
1022 type = TOK_COMMENT;
1023 while (*p)
1024 p++;
1025 } else {
1027 * Anything else is an operator of some kind. We check
1028 * for all the double-character operators (>>, <<, //,
1029 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1030 * else is a single-character operator.
1032 type = TOK_OTHER;
1033 if ((p[0] == '>' && p[1] == '>') ||
1034 (p[0] == '<' && p[1] == '<') ||
1035 (p[0] == '/' && p[1] == '/') ||
1036 (p[0] == '<' && p[1] == '=') ||
1037 (p[0] == '>' && p[1] == '=') ||
1038 (p[0] == '=' && p[1] == '=') ||
1039 (p[0] == '!' && p[1] == '=') ||
1040 (p[0] == '<' && p[1] == '>') ||
1041 (p[0] == '&' && p[1] == '&') ||
1042 (p[0] == '|' && p[1] == '|') ||
1043 (p[0] == '^' && p[1] == '^')) {
1044 p++;
1046 p++;
1049 /* Handling unterminated string by UNV */
1050 /*if (type == -1)
1052 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1053 t->text[p-line] = *line;
1054 tail = &t->next;
1056 else */
1057 if (type != TOK_COMMENT) {
1058 *tail = t = new_Token(NULL, type, line, p - line);
1059 tail = &t->next;
1061 line = p;
1063 return list;
1067 * this function allocates a new managed block of memory and
1068 * returns a pointer to the block. The managed blocks are
1069 * deleted only all at once by the delete_Blocks function.
1071 static void *new_Block(size_t size)
1073 Blocks *b = &blocks;
1075 /* first, get to the end of the linked list */
1076 while (b->next)
1077 b = b->next;
1078 /* now allocate the requested chunk */
1079 b->chunk = nasm_malloc(size);
1081 /* now allocate a new block for the next request */
1082 b->next = nasm_malloc(sizeof(Blocks));
1083 /* and initialize the contents of the new block */
1084 b->next->next = NULL;
1085 b->next->chunk = NULL;
1086 return b->chunk;
1090 * this function deletes all managed blocks of memory
1092 static void delete_Blocks(void)
1094 Blocks *a, *b = &blocks;
1097 * keep in mind that the first block, pointed to by blocks
1098 * is a static and not dynamically allocated, so we don't
1099 * free it.
1101 while (b) {
1102 if (b->chunk)
1103 nasm_free(b->chunk);
1104 a = b;
1105 b = b->next;
1106 if (a != &blocks)
1107 nasm_free(a);
1112 * this function creates a new Token and passes a pointer to it
1113 * back to the caller. It sets the type and text elements, and
1114 * also the a.mac and next elements to NULL.
1116 static Token *new_Token(Token * next, enum pp_token_type type,
1117 const char *text, int txtlen)
1119 Token *t;
1120 int i;
1122 if (!freeTokens) {
1123 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1124 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1125 freeTokens[i].next = &freeTokens[i + 1];
1126 freeTokens[i].next = NULL;
1128 t = freeTokens;
1129 freeTokens = t->next;
1130 t->next = next;
1131 t->a.mac = NULL;
1132 t->type = type;
1133 if (type == TOK_WHITESPACE || !text) {
1134 t->text = NULL;
1135 } else {
1136 if (txtlen == 0)
1137 txtlen = strlen(text);
1138 t->text = nasm_malloc(txtlen+1);
1139 memcpy(t->text, text, txtlen);
1140 t->text[txtlen] = '\0';
1142 return t;
1145 static Token *delete_Token(Token * t)
1147 Token *next = t->next;
1148 nasm_free(t->text);
1149 t->next = freeTokens;
1150 freeTokens = t;
1151 return next;
1155 * Convert a line of tokens back into text.
1156 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1157 * will be transformed into ..@ctxnum.xxx
1159 static char *detoken(Token * tlist, bool expand_locals)
1161 Token *t;
1162 int len;
1163 char *line, *p;
1164 const char *q;
1166 len = 0;
1167 for (t = tlist; t; t = t->next) {
1168 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1169 char *p = getenv(t->text + 2);
1170 nasm_free(t->text);
1171 if (p)
1172 t->text = nasm_strdup(p);
1173 else
1174 t->text = NULL;
1176 /* Expand local macros here and not during preprocessing */
1177 if (expand_locals &&
1178 t->type == TOK_PREPROC_ID && t->text &&
1179 t->text[0] == '%' && t->text[1] == '$') {
1180 const char *q;
1181 char *p;
1182 Context *ctx = get_ctx(t->text, &q, false);
1183 if (ctx) {
1184 char buffer[40];
1185 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1186 p = nasm_strcat(buffer, q);
1187 nasm_free(t->text);
1188 t->text = p;
1191 if (t->type == TOK_WHITESPACE) {
1192 len++;
1193 } else if (t->text) {
1194 len += strlen(t->text);
1197 p = line = nasm_malloc(len + 1);
1198 for (t = tlist; t; t = t->next) {
1199 if (t->type == TOK_WHITESPACE) {
1200 *p++ = ' ';
1201 } else if (t->text) {
1202 q = t->text;
1203 while (*q)
1204 *p++ = *q++;
1207 *p = '\0';
1208 return line;
1212 * A scanner, suitable for use by the expression evaluator, which
1213 * operates on a line of Tokens. Expects a pointer to a pointer to
1214 * the first token in the line to be passed in as its private_data
1215 * field.
1217 * FIX: This really needs to be unified with stdscan.
1219 static int ppscan(void *private_data, struct tokenval *tokval)
1221 Token **tlineptr = private_data;
1222 Token *tline;
1223 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1225 do {
1226 tline = *tlineptr;
1227 *tlineptr = tline ? tline->next : NULL;
1229 while (tline && (tline->type == TOK_WHITESPACE ||
1230 tline->type == TOK_COMMENT));
1232 if (!tline)
1233 return tokval->t_type = TOKEN_EOS;
1235 tokval->t_charptr = tline->text;
1237 if (tline->text[0] == '$' && !tline->text[1])
1238 return tokval->t_type = TOKEN_HERE;
1239 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1240 return tokval->t_type = TOKEN_BASE;
1242 if (tline->type == TOK_ID) {
1243 p = tokval->t_charptr = tline->text;
1244 if (p[0] == '$') {
1245 tokval->t_charptr++;
1246 return tokval->t_type = TOKEN_ID;
1249 for (r = p, s = ourcopy; *r; r++) {
1250 if (r >= p+MAX_KEYWORD)
1251 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1252 *s++ = nasm_tolower(*r);
1254 *s = '\0';
1255 /* right, so we have an identifier sitting in temp storage. now,
1256 * is it actually a register or instruction name, or what? */
1257 return nasm_token_hash(ourcopy, tokval);
1260 if (tline->type == TOK_NUMBER) {
1261 bool rn_error;
1262 tokval->t_integer = readnum(tline->text, &rn_error);
1263 tokval->t_charptr = tline->text;
1264 if (rn_error)
1265 return tokval->t_type = TOKEN_ERRNUM;
1266 else
1267 return tokval->t_type = TOKEN_NUM;
1270 if (tline->type == TOK_FLOAT) {
1271 return tokval->t_type = TOKEN_FLOAT;
1274 if (tline->type == TOK_STRING) {
1275 char bq, *ep;
1277 bq = tline->text[0];
1278 tokval->t_charptr = tline->text;
1279 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1281 if (ep[0] != bq || ep[1] != '\0')
1282 return tokval->t_type = TOKEN_ERRSTR;
1283 else
1284 return tokval->t_type = TOKEN_STR;
1287 if (tline->type == TOK_OTHER) {
1288 if (!strcmp(tline->text, "<<"))
1289 return tokval->t_type = TOKEN_SHL;
1290 if (!strcmp(tline->text, ">>"))
1291 return tokval->t_type = TOKEN_SHR;
1292 if (!strcmp(tline->text, "//"))
1293 return tokval->t_type = TOKEN_SDIV;
1294 if (!strcmp(tline->text, "%%"))
1295 return tokval->t_type = TOKEN_SMOD;
1296 if (!strcmp(tline->text, "=="))
1297 return tokval->t_type = TOKEN_EQ;
1298 if (!strcmp(tline->text, "<>"))
1299 return tokval->t_type = TOKEN_NE;
1300 if (!strcmp(tline->text, "!="))
1301 return tokval->t_type = TOKEN_NE;
1302 if (!strcmp(tline->text, "<="))
1303 return tokval->t_type = TOKEN_LE;
1304 if (!strcmp(tline->text, ">="))
1305 return tokval->t_type = TOKEN_GE;
1306 if (!strcmp(tline->text, "&&"))
1307 return tokval->t_type = TOKEN_DBL_AND;
1308 if (!strcmp(tline->text, "^^"))
1309 return tokval->t_type = TOKEN_DBL_XOR;
1310 if (!strcmp(tline->text, "||"))
1311 return tokval->t_type = TOKEN_DBL_OR;
1315 * We have no other options: just return the first character of
1316 * the token text.
1318 return tokval->t_type = tline->text[0];
1322 * Compare a string to the name of an existing macro; this is a
1323 * simple wrapper which calls either strcmp or nasm_stricmp
1324 * depending on the value of the `casesense' parameter.
1326 static int mstrcmp(const char *p, const char *q, bool casesense)
1328 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1332 * Compare a string to the name of an existing macro; this is a
1333 * simple wrapper which calls either strcmp or nasm_stricmp
1334 * depending on the value of the `casesense' parameter.
1336 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1338 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1342 * Return the Context structure associated with a %$ token. Return
1343 * NULL, having _already_ reported an error condition, if the
1344 * context stack isn't deep enough for the supplied number of $
1345 * signs.
1346 * If all_contexts == true, contexts that enclose current are
1347 * also scanned for such smacro, until it is found; if not -
1348 * only the context that directly results from the number of $'s
1349 * in variable's name.
1351 * If "namep" is non-NULL, set it to the pointer to the macro name
1352 * tail, i.e. the part beyond %$...
1354 static Context *get_ctx(const char *name, const char **namep,
1355 bool all_contexts)
1357 Context *ctx;
1358 SMacro *m;
1359 int i;
1361 if (namep)
1362 *namep = name;
1364 if (!name || name[0] != '%' || name[1] != '$')
1365 return NULL;
1367 if (!cstk) {
1368 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1369 return NULL;
1372 name += 2;
1373 ctx = cstk;
1374 i = 0;
1375 while (ctx && *name == '$') {
1376 name++;
1377 i++;
1378 ctx = ctx->next;
1380 if (!ctx) {
1381 error(ERR_NONFATAL, "`%s': context stack is only"
1382 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1383 return NULL;
1386 if (namep)
1387 *namep = name;
1389 if (!all_contexts)
1390 return ctx;
1392 do {
1393 /* Search for this smacro in found context */
1394 m = hash_findix(&ctx->localmac, name);
1395 while (m) {
1396 if (!mstrcmp(m->name, name, m->casesense))
1397 return ctx;
1398 m = m->next;
1400 ctx = ctx->next;
1402 while (ctx);
1403 return NULL;
1407 * Check to see if a file is already in a string list
1409 static bool in_list(const StrList *list, const char *str)
1411 while (list) {
1412 if (!strcmp(list->str, str))
1413 return true;
1414 list = list->next;
1416 return false;
1420 * Open an include file. This routine must always return a valid
1421 * file pointer if it returns - it's responsible for throwing an
1422 * ERR_FATAL and bombing out completely if not. It should also try
1423 * the include path one by one until it finds the file or reaches
1424 * the end of the path.
1426 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1427 bool missing_ok)
1429 FILE *fp;
1430 char *prefix = "";
1431 IncPath *ip = ipath;
1432 int len = strlen(file);
1433 size_t prefix_len = 0;
1434 StrList *sl;
1436 while (1) {
1437 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1438 memcpy(sl->str, prefix, prefix_len);
1439 memcpy(sl->str+prefix_len, file, len+1);
1440 fp = fopen(sl->str, "r");
1441 if (fp && dhead && !in_list(*dhead, sl->str)) {
1442 sl->next = NULL;
1443 **dtail = sl;
1444 *dtail = &sl->next;
1445 } else {
1446 nasm_free(sl);
1448 if (fp)
1449 return fp;
1450 if (!ip) {
1451 if (!missing_ok)
1452 break;
1453 prefix = NULL;
1454 } else {
1455 prefix = ip->path;
1456 ip = ip->next;
1458 if (prefix) {
1459 prefix_len = strlen(prefix);
1460 } else {
1461 /* -MG given and file not found */
1462 if (dhead && !in_list(*dhead, file)) {
1463 sl = nasm_malloc(len+1+sizeof sl->next);
1464 sl->next = NULL;
1465 strcpy(sl->str, file);
1466 **dtail = sl;
1467 *dtail = &sl->next;
1469 return NULL;
1473 error(ERR_FATAL, "unable to open include file `%s'", file);
1474 return NULL;
1478 * Determine if we should warn on defining a single-line macro of
1479 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1480 * return true if _any_ single-line macro of that name is defined.
1481 * Otherwise, will return true if a single-line macro with either
1482 * `nparam' or no parameters is defined.
1484 * If a macro with precisely the right number of parameters is
1485 * defined, or nparam is -1, the address of the definition structure
1486 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1487 * is NULL, no action will be taken regarding its contents, and no
1488 * error will occur.
1490 * Note that this is also called with nparam zero to resolve
1491 * `ifdef'.
1493 * If you already know which context macro belongs to, you can pass
1494 * the context pointer as first parameter; if you won't but name begins
1495 * with %$ the context will be automatically computed. If all_contexts
1496 * is true, macro will be searched in outer contexts as well.
1498 static bool
1499 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1500 bool nocase)
1502 struct hash_table *smtbl;
1503 SMacro *m;
1505 if (ctx) {
1506 smtbl = &ctx->localmac;
1507 } else if (name[0] == '%' && name[1] == '$') {
1508 if (cstk)
1509 ctx = get_ctx(name, &name, false);
1510 if (!ctx)
1511 return false; /* got to return _something_ */
1512 smtbl = &ctx->localmac;
1513 } else {
1514 smtbl = &smacros;
1516 m = (SMacro *) hash_findix(smtbl, name);
1518 while (m) {
1519 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1520 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1521 if (defn) {
1522 if (nparam == (int) m->nparam || nparam == -1)
1523 *defn = m;
1524 else
1525 *defn = NULL;
1527 return true;
1529 m = m->next;
1532 return false;
1536 * Count and mark off the parameters in a multi-line macro call.
1537 * This is called both from within the multi-line macro expansion
1538 * code, and also to mark off the default parameters when provided
1539 * in a %macro definition line.
1541 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1543 int paramsize, brace;
1545 *nparam = paramsize = 0;
1546 *params = NULL;
1547 while (t) {
1548 /* +1: we need space for the final NULL */
1549 if (*nparam+1 >= paramsize) {
1550 paramsize += PARAM_DELTA;
1551 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1553 skip_white_(t);
1554 brace = false;
1555 if (tok_is_(t, "{"))
1556 brace = true;
1557 (*params)[(*nparam)++] = t;
1558 while (tok_isnt_(t, brace ? "}" : ","))
1559 t = t->next;
1560 if (t) { /* got a comma/brace */
1561 t = t->next;
1562 if (brace) {
1564 * Now we've found the closing brace, look further
1565 * for the comma.
1567 skip_white_(t);
1568 if (tok_isnt_(t, ",")) {
1569 error(ERR_NONFATAL,
1570 "braces do not enclose all of macro parameter");
1571 while (tok_isnt_(t, ","))
1572 t = t->next;
1574 if (t)
1575 t = t->next; /* eat the comma */
1582 * Determine whether one of the various `if' conditions is true or
1583 * not.
1585 * We must free the tline we get passed.
1587 static bool if_condition(Token * tline, enum preproc_token ct)
1589 enum pp_conditional i = PP_COND(ct);
1590 bool j;
1591 Token *t, *tt, **tptr, *origline;
1592 struct tokenval tokval;
1593 expr *evalresult;
1594 enum pp_token_type needtype;
1596 origline = tline;
1598 switch (i) {
1599 case PPC_IFCTX:
1600 j = false; /* have we matched yet? */
1601 while (true) {
1602 skip_white_(tline);
1603 if (!tline)
1604 break;
1605 if (tline->type != TOK_ID) {
1606 error(ERR_NONFATAL,
1607 "`%s' expects context identifiers", pp_directives[ct]);
1608 free_tlist(origline);
1609 return -1;
1611 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1612 j = true;
1613 tline = tline->next;
1615 break;
1617 case PPC_IFDEF:
1618 j = false; /* have we matched yet? */
1619 while (tline) {
1620 skip_white_(tline);
1621 if (!tline || (tline->type != TOK_ID &&
1622 (tline->type != TOK_PREPROC_ID ||
1623 tline->text[1] != '$'))) {
1624 error(ERR_NONFATAL,
1625 "`%s' expects macro identifiers", pp_directives[ct]);
1626 goto fail;
1628 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1629 j = true;
1630 tline = tline->next;
1632 break;
1634 case PPC_IFIDN:
1635 case PPC_IFIDNI:
1636 tline = expand_smacro(tline);
1637 t = tt = tline;
1638 while (tok_isnt_(tt, ","))
1639 tt = tt->next;
1640 if (!tt) {
1641 error(ERR_NONFATAL,
1642 "`%s' expects two comma-separated arguments",
1643 pp_directives[ct]);
1644 goto fail;
1646 tt = tt->next;
1647 j = true; /* assume equality unless proved not */
1648 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1649 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1650 error(ERR_NONFATAL, "`%s': more than one comma on line",
1651 pp_directives[ct]);
1652 goto fail;
1654 if (t->type == TOK_WHITESPACE) {
1655 t = t->next;
1656 continue;
1658 if (tt->type == TOK_WHITESPACE) {
1659 tt = tt->next;
1660 continue;
1662 if (tt->type != t->type) {
1663 j = false; /* found mismatching tokens */
1664 break;
1666 /* When comparing strings, need to unquote them first */
1667 if (t->type == TOK_STRING) {
1668 size_t l1 = nasm_unquote(t->text, NULL);
1669 size_t l2 = nasm_unquote(tt->text, NULL);
1671 if (l1 != l2) {
1672 j = false;
1673 break;
1675 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1676 j = false;
1677 break;
1679 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1680 j = false; /* found mismatching tokens */
1681 break;
1684 t = t->next;
1685 tt = tt->next;
1687 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1688 j = false; /* trailing gunk on one end or other */
1689 break;
1691 case PPC_IFMACRO:
1693 bool found = false;
1694 MMacro searching, *mmac;
1696 skip_white_(tline);
1697 tline = expand_id(tline);
1698 if (!tok_type_(tline, TOK_ID)) {
1699 error(ERR_NONFATAL,
1700 "`%s' expects a macro name", pp_directives[ct]);
1701 goto fail;
1703 searching.name = nasm_strdup(tline->text);
1704 searching.casesense = true;
1705 searching.plus = false;
1706 searching.nolist = false;
1707 searching.in_progress = 0;
1708 searching.max_depth = 0;
1709 searching.rep_nest = NULL;
1710 searching.nparam_min = 0;
1711 searching.nparam_max = INT_MAX;
1712 tline = expand_smacro(tline->next);
1713 skip_white_(tline);
1714 if (!tline) {
1715 } else if (!tok_type_(tline, TOK_NUMBER)) {
1716 error(ERR_NONFATAL,
1717 "`%s' expects a parameter count or nothing",
1718 pp_directives[ct]);
1719 } else {
1720 searching.nparam_min = searching.nparam_max =
1721 readnum(tline->text, &j);
1722 if (j)
1723 error(ERR_NONFATAL,
1724 "unable to parse parameter count `%s'",
1725 tline->text);
1727 if (tline && tok_is_(tline->next, "-")) {
1728 tline = tline->next->next;
1729 if (tok_is_(tline, "*"))
1730 searching.nparam_max = INT_MAX;
1731 else if (!tok_type_(tline, TOK_NUMBER))
1732 error(ERR_NONFATAL,
1733 "`%s' expects a parameter count after `-'",
1734 pp_directives[ct]);
1735 else {
1736 searching.nparam_max = readnum(tline->text, &j);
1737 if (j)
1738 error(ERR_NONFATAL,
1739 "unable to parse parameter count `%s'",
1740 tline->text);
1741 if (searching.nparam_min > searching.nparam_max)
1742 error(ERR_NONFATAL,
1743 "minimum parameter count exceeds maximum");
1746 if (tline && tok_is_(tline->next, "+")) {
1747 tline = tline->next;
1748 searching.plus = true;
1750 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1751 while (mmac) {
1752 if (!strcmp(mmac->name, searching.name) &&
1753 (mmac->nparam_min <= searching.nparam_max
1754 || searching.plus)
1755 && (searching.nparam_min <= mmac->nparam_max
1756 || mmac->plus)) {
1757 found = true;
1758 break;
1760 mmac = mmac->next;
1762 if (tline && tline->next)
1763 error(ERR_WARNING|ERR_PASS1,
1764 "trailing garbage after %%ifmacro ignored");
1765 nasm_free(searching.name);
1766 j = found;
1767 break;
1770 case PPC_IFID:
1771 needtype = TOK_ID;
1772 goto iftype;
1773 case PPC_IFNUM:
1774 needtype = TOK_NUMBER;
1775 goto iftype;
1776 case PPC_IFSTR:
1777 needtype = TOK_STRING;
1778 goto iftype;
1780 iftype:
1781 t = tline = expand_smacro(tline);
1783 while (tok_type_(t, TOK_WHITESPACE) ||
1784 (needtype == TOK_NUMBER &&
1785 tok_type_(t, TOK_OTHER) &&
1786 (t->text[0] == '-' || t->text[0] == '+') &&
1787 !t->text[1]))
1788 t = t->next;
1790 j = tok_type_(t, needtype);
1791 break;
1793 case PPC_IFTOKEN:
1794 t = tline = expand_smacro(tline);
1795 while (tok_type_(t, TOK_WHITESPACE))
1796 t = t->next;
1798 j = false;
1799 if (t) {
1800 t = t->next; /* Skip the actual token */
1801 while (tok_type_(t, TOK_WHITESPACE))
1802 t = t->next;
1803 j = !t; /* Should be nothing left */
1805 break;
1807 case PPC_IFEMPTY:
1808 t = tline = expand_smacro(tline);
1809 while (tok_type_(t, TOK_WHITESPACE))
1810 t = t->next;
1812 j = !t; /* Should be empty */
1813 break;
1815 case PPC_IF:
1816 t = tline = expand_smacro(tline);
1817 tptr = &t;
1818 tokval.t_type = TOKEN_INVALID;
1819 evalresult = evaluate(ppscan, tptr, &tokval,
1820 NULL, pass | CRITICAL, error, NULL);
1821 if (!evalresult)
1822 return -1;
1823 if (tokval.t_type)
1824 error(ERR_WARNING|ERR_PASS1,
1825 "trailing garbage after expression ignored");
1826 if (!is_simple(evalresult)) {
1827 error(ERR_NONFATAL,
1828 "non-constant value given to `%s'", pp_directives[ct]);
1829 goto fail;
1831 j = reloc_value(evalresult) != 0;
1832 break;
1834 default:
1835 error(ERR_FATAL,
1836 "preprocessor directive `%s' not yet implemented",
1837 pp_directives[ct]);
1838 goto fail;
1841 free_tlist(origline);
1842 return j ^ PP_NEGATIVE(ct);
1844 fail:
1845 free_tlist(origline);
1846 return -1;
1850 * Common code for defining an smacro
1852 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1853 int nparam, Token *expansion)
1855 SMacro *smac, **smhead;
1856 struct hash_table *smtbl;
1858 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1859 if (!smac) {
1860 error(ERR_WARNING|ERR_PASS1,
1861 "single-line macro `%s' defined both with and"
1862 " without parameters", mname);
1864 * Some instances of the old code considered this a failure,
1865 * some others didn't. What is the right thing to do here?
1867 free_tlist(expansion);
1868 return false; /* Failure */
1869 } else {
1871 * We're redefining, so we have to take over an
1872 * existing SMacro structure. This means freeing
1873 * what was already in it.
1875 nasm_free(smac->name);
1876 free_tlist(smac->expansion);
1878 } else {
1879 smtbl = ctx ? &ctx->localmac : &smacros;
1880 smhead = (SMacro **) hash_findi_add(smtbl, mname);
1881 smac = nasm_malloc(sizeof(SMacro));
1882 smac->next = *smhead;
1883 *smhead = smac;
1885 smac->name = nasm_strdup(mname);
1886 smac->casesense = casesense;
1887 smac->nparam = nparam;
1888 smac->expansion = expansion;
1889 smac->in_progress = false;
1890 return true; /* Success */
1894 * Undefine an smacro
1896 static void undef_smacro(Context *ctx, const char *mname)
1898 SMacro **smhead, *s, **sp;
1899 struct hash_table *smtbl;
1901 smtbl = ctx ? &ctx->localmac : &smacros;
1902 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
1904 if (smhead) {
1906 * We now have a macro name... go hunt for it.
1908 sp = smhead;
1909 while ((s = *sp) != NULL) {
1910 if (!mstrcmp(s->name, mname, s->casesense)) {
1911 *sp = s->next;
1912 nasm_free(s->name);
1913 free_tlist(s->expansion);
1914 nasm_free(s);
1915 } else {
1916 sp = &s->next;
1923 * Parse a mmacro specification.
1925 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
1927 bool err;
1929 tline = tline->next;
1930 skip_white_(tline);
1931 tline = expand_id(tline);
1932 if (!tok_type_(tline, TOK_ID)) {
1933 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
1934 return false;
1937 def->prev = NULL;
1938 def->name = nasm_strdup(tline->text);
1939 def->plus = false;
1940 def->nolist = false;
1941 def->in_progress = 0;
1942 def->rep_nest = NULL;
1943 def->nparam_min = 0;
1944 def->nparam_max = 0;
1946 tline = expand_smacro(tline->next);
1947 skip_white_(tline);
1948 if (!tok_type_(tline, TOK_NUMBER)) {
1949 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
1950 } else {
1951 def->nparam_min = def->nparam_max =
1952 readnum(tline->text, &err);
1953 if (err)
1954 error(ERR_NONFATAL,
1955 "unable to parse parameter count `%s'", tline->text);
1957 if (tline && tok_is_(tline->next, "-")) {
1958 tline = tline->next->next;
1959 if (tok_is_(tline, "*")) {
1960 def->nparam_max = INT_MAX;
1961 } else if (!tok_type_(tline, TOK_NUMBER)) {
1962 error(ERR_NONFATAL,
1963 "`%s' expects a parameter count after `-'", directive);
1964 } else {
1965 def->nparam_max = readnum(tline->text, &err);
1966 if (err) {
1967 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
1968 tline->text);
1970 if (def->nparam_min > def->nparam_max) {
1971 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
1975 if (tline && tok_is_(tline->next, "+")) {
1976 tline = tline->next;
1977 def->plus = true;
1979 if (tline && tok_type_(tline->next, TOK_ID) &&
1980 !nasm_stricmp(tline->next->text, ".nolist")) {
1981 tline = tline->next;
1982 def->nolist = true;
1986 * Handle default parameters.
1988 if (tline && tline->next) {
1989 def->dlist = tline->next;
1990 tline->next = NULL;
1991 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
1992 } else {
1993 def->dlist = NULL;
1994 def->defaults = NULL;
1996 def->expansion = NULL;
1998 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
1999 !def->plus)
2000 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2001 "too many default macro parameters");
2003 return true;
2008 * Decode a size directive
2010 static int parse_size(const char *str) {
2011 static const char *size_names[] =
2012 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2013 static const int sizes[] =
2014 { 0, 1, 4, 16, 8, 10, 2, 32 };
2016 return sizes[bsii(str, size_names, elements(size_names))+1];
2020 * nasm_unquote with error if the string contains NUL characters.
2021 * If the string contains NUL characters, issue an error and return
2022 * the C len, i.e. truncate at the NUL.
2024 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
2026 size_t len = nasm_unquote(qstr, NULL);
2027 size_t clen = strlen(qstr);
2029 if (len != clen)
2030 error(ERR_NONFATAL, "NUL character in `%s' directive",
2031 pp_directives[directive]);
2033 return clen;
2037 * find and process preprocessor directive in passed line
2038 * Find out if a line contains a preprocessor directive, and deal
2039 * with it if so.
2041 * If a directive _is_ found, it is the responsibility of this routine
2042 * (and not the caller) to free_tlist() the line.
2044 * @param tline a pointer to the current tokeninzed line linked list
2045 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2048 static int do_directive(Token * tline)
2050 enum preproc_token i;
2051 int j;
2052 bool err;
2053 int nparam;
2054 bool nolist;
2055 bool casesense;
2056 int k, m;
2057 int offset;
2058 char *p, *pp;
2059 const char *mname;
2060 Include *inc;
2061 Context *ctx;
2062 Cond *cond;
2063 MMacro *mmac, **mmhead;
2064 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2065 Line *l;
2066 struct tokenval tokval;
2067 expr *evalresult;
2068 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2069 int64_t count;
2070 size_t len;
2071 int severity;
2073 origline = tline;
2075 skip_white_(tline);
2076 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2077 (tline->text[1] == '%' || tline->text[1] == '$'
2078 || tline->text[1] == '!'))
2079 return NO_DIRECTIVE_FOUND;
2081 i = pp_token_hash(tline->text);
2084 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2085 * since they are known to be buggy at moment, we need to fix them
2086 * in future release (2.09-2.10)
2088 if (i == PP_RMACRO || i == PP_RMACRO || i == PP_EXITMACRO) {
2089 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2090 tline->text);
2091 return NO_DIRECTIVE_FOUND;
2095 * If we're in a non-emitting branch of a condition construct,
2096 * or walking to the end of an already terminated %rep block,
2097 * we should ignore all directives except for condition
2098 * directives.
2100 if (((istk->conds && !emitting(istk->conds->state)) ||
2101 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2102 return NO_DIRECTIVE_FOUND;
2106 * If we're defining a macro or reading a %rep block, we should
2107 * ignore all directives except for %macro/%imacro (which nest),
2108 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2109 * If we're in a %rep block, another %rep nests, so should be let through.
2111 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2112 i != PP_RMACRO && i != PP_IRMACRO &&
2113 i != PP_ENDMACRO && i != PP_ENDM &&
2114 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2115 return NO_DIRECTIVE_FOUND;
2118 if (defining) {
2119 if (i == PP_MACRO || i == PP_IMACRO ||
2120 i == PP_RMACRO || i == PP_IRMACRO) {
2121 nested_mac_count++;
2122 return NO_DIRECTIVE_FOUND;
2123 } else if (nested_mac_count > 0) {
2124 if (i == PP_ENDMACRO) {
2125 nested_mac_count--;
2126 return NO_DIRECTIVE_FOUND;
2129 if (!defining->name) {
2130 if (i == PP_REP) {
2131 nested_rep_count++;
2132 return NO_DIRECTIVE_FOUND;
2133 } else if (nested_rep_count > 0) {
2134 if (i == PP_ENDREP) {
2135 nested_rep_count--;
2136 return NO_DIRECTIVE_FOUND;
2142 switch (i) {
2143 case PP_INVALID:
2144 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2145 tline->text);
2146 return NO_DIRECTIVE_FOUND; /* didn't get it */
2148 case PP_STACKSIZE:
2149 /* Directive to tell NASM what the default stack size is. The
2150 * default is for a 16-bit stack, and this can be overriden with
2151 * %stacksize large.
2153 tline = tline->next;
2154 if (tline && tline->type == TOK_WHITESPACE)
2155 tline = tline->next;
2156 if (!tline || tline->type != TOK_ID) {
2157 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2158 free_tlist(origline);
2159 return DIRECTIVE_FOUND;
2161 if (nasm_stricmp(tline->text, "flat") == 0) {
2162 /* All subsequent ARG directives are for a 32-bit stack */
2163 StackSize = 4;
2164 StackPointer = "ebp";
2165 ArgOffset = 8;
2166 LocalOffset = 0;
2167 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2168 /* All subsequent ARG directives are for a 64-bit stack */
2169 StackSize = 8;
2170 StackPointer = "rbp";
2171 ArgOffset = 16;
2172 LocalOffset = 0;
2173 } else if (nasm_stricmp(tline->text, "large") == 0) {
2174 /* All subsequent ARG directives are for a 16-bit stack,
2175 * far function call.
2177 StackSize = 2;
2178 StackPointer = "bp";
2179 ArgOffset = 4;
2180 LocalOffset = 0;
2181 } else if (nasm_stricmp(tline->text, "small") == 0) {
2182 /* All subsequent ARG directives are for a 16-bit stack,
2183 * far function call. We don't support near functions.
2185 StackSize = 2;
2186 StackPointer = "bp";
2187 ArgOffset = 6;
2188 LocalOffset = 0;
2189 } else {
2190 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2191 free_tlist(origline);
2192 return DIRECTIVE_FOUND;
2194 free_tlist(origline);
2195 return DIRECTIVE_FOUND;
2197 case PP_ARG:
2198 /* TASM like ARG directive to define arguments to functions, in
2199 * the following form:
2201 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2203 offset = ArgOffset;
2204 do {
2205 char *arg, directive[256];
2206 int size = StackSize;
2208 /* Find the argument name */
2209 tline = tline->next;
2210 if (tline && tline->type == TOK_WHITESPACE)
2211 tline = tline->next;
2212 if (!tline || tline->type != TOK_ID) {
2213 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2214 free_tlist(origline);
2215 return DIRECTIVE_FOUND;
2217 arg = tline->text;
2219 /* Find the argument size type */
2220 tline = tline->next;
2221 if (!tline || tline->type != TOK_OTHER
2222 || tline->text[0] != ':') {
2223 error(ERR_NONFATAL,
2224 "Syntax error processing `%%arg' directive");
2225 free_tlist(origline);
2226 return DIRECTIVE_FOUND;
2228 tline = tline->next;
2229 if (!tline || tline->type != TOK_ID) {
2230 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2231 free_tlist(origline);
2232 return DIRECTIVE_FOUND;
2235 /* Allow macro expansion of type parameter */
2236 tt = tokenize(tline->text);
2237 tt = expand_smacro(tt);
2238 size = parse_size(tt->text);
2239 if (!size) {
2240 error(ERR_NONFATAL,
2241 "Invalid size type for `%%arg' missing directive");
2242 free_tlist(tt);
2243 free_tlist(origline);
2244 return DIRECTIVE_FOUND;
2246 free_tlist(tt);
2248 /* Round up to even stack slots */
2249 size = ALIGN(size, StackSize);
2251 /* Now define the macro for the argument */
2252 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2253 arg, StackPointer, offset);
2254 do_directive(tokenize(directive));
2255 offset += size;
2257 /* Move to the next argument in the list */
2258 tline = tline->next;
2259 if (tline && tline->type == TOK_WHITESPACE)
2260 tline = tline->next;
2261 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2262 ArgOffset = offset;
2263 free_tlist(origline);
2264 return DIRECTIVE_FOUND;
2266 case PP_LOCAL:
2267 /* TASM like LOCAL directive to define local variables for a
2268 * function, in the following form:
2270 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2272 * The '= LocalSize' at the end is ignored by NASM, but is
2273 * required by TASM to define the local parameter size (and used
2274 * by the TASM macro package).
2276 offset = LocalOffset;
2277 do {
2278 char *local, directive[256];
2279 int size = StackSize;
2281 /* Find the argument name */
2282 tline = tline->next;
2283 if (tline && tline->type == TOK_WHITESPACE)
2284 tline = tline->next;
2285 if (!tline || tline->type != TOK_ID) {
2286 error(ERR_NONFATAL,
2287 "`%%local' missing argument parameter");
2288 free_tlist(origline);
2289 return DIRECTIVE_FOUND;
2291 local = tline->text;
2293 /* Find the argument size type */
2294 tline = tline->next;
2295 if (!tline || tline->type != TOK_OTHER
2296 || tline->text[0] != ':') {
2297 error(ERR_NONFATAL,
2298 "Syntax error processing `%%local' directive");
2299 free_tlist(origline);
2300 return DIRECTIVE_FOUND;
2302 tline = tline->next;
2303 if (!tline || tline->type != TOK_ID) {
2304 error(ERR_NONFATAL,
2305 "`%%local' missing size type parameter");
2306 free_tlist(origline);
2307 return DIRECTIVE_FOUND;
2310 /* Allow macro expansion of type parameter */
2311 tt = tokenize(tline->text);
2312 tt = expand_smacro(tt);
2313 size = parse_size(tt->text);
2314 if (!size) {
2315 error(ERR_NONFATAL,
2316 "Invalid size type for `%%local' missing directive");
2317 free_tlist(tt);
2318 free_tlist(origline);
2319 return DIRECTIVE_FOUND;
2321 free_tlist(tt);
2323 /* Round up to even stack slots */
2324 size = ALIGN(size, StackSize);
2326 offset += size; /* Negative offset, increment before */
2328 /* Now define the macro for the argument */
2329 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2330 local, StackPointer, offset);
2331 do_directive(tokenize(directive));
2333 /* Now define the assign to setup the enter_c macro correctly */
2334 snprintf(directive, sizeof(directive),
2335 "%%assign %%$localsize %%$localsize+%d", size);
2336 do_directive(tokenize(directive));
2338 /* Move to the next argument in the list */
2339 tline = tline->next;
2340 if (tline && tline->type == TOK_WHITESPACE)
2341 tline = tline->next;
2342 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2343 LocalOffset = offset;
2344 free_tlist(origline);
2345 return DIRECTIVE_FOUND;
2347 case PP_CLEAR:
2348 if (tline->next)
2349 error(ERR_WARNING|ERR_PASS1,
2350 "trailing garbage after `%%clear' ignored");
2351 free_macros();
2352 init_macros();
2353 free_tlist(origline);
2354 return DIRECTIVE_FOUND;
2356 case PP_DEPEND:
2357 t = tline->next = expand_smacro(tline->next);
2358 skip_white_(t);
2359 if (!t || (t->type != TOK_STRING &&
2360 t->type != TOK_INTERNAL_STRING)) {
2361 error(ERR_NONFATAL, "`%%depend' expects a file name");
2362 free_tlist(origline);
2363 return DIRECTIVE_FOUND; /* but we did _something_ */
2365 if (t->next)
2366 error(ERR_WARNING|ERR_PASS1,
2367 "trailing garbage after `%%depend' ignored");
2368 p = t->text;
2369 if (t->type != TOK_INTERNAL_STRING)
2370 nasm_unquote_cstr(p, i);
2371 if (dephead && !in_list(*dephead, p)) {
2372 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2373 sl->next = NULL;
2374 strcpy(sl->str, p);
2375 *deptail = sl;
2376 deptail = &sl->next;
2378 free_tlist(origline);
2379 return DIRECTIVE_FOUND;
2381 case PP_INCLUDE:
2382 t = tline->next = expand_smacro(tline->next);
2383 skip_white_(t);
2385 if (!t || (t->type != TOK_STRING &&
2386 t->type != TOK_INTERNAL_STRING)) {
2387 error(ERR_NONFATAL, "`%%include' expects a file name");
2388 free_tlist(origline);
2389 return DIRECTIVE_FOUND; /* but we did _something_ */
2391 if (t->next)
2392 error(ERR_WARNING|ERR_PASS1,
2393 "trailing garbage after `%%include' ignored");
2394 p = t->text;
2395 if (t->type != TOK_INTERNAL_STRING)
2396 nasm_unquote_cstr(p, i);
2397 inc = nasm_malloc(sizeof(Include));
2398 inc->next = istk;
2399 inc->conds = NULL;
2400 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2401 if (!inc->fp) {
2402 /* -MG given but file not found */
2403 nasm_free(inc);
2404 } else {
2405 inc->fname = src_set_fname(nasm_strdup(p));
2406 inc->lineno = src_set_linnum(0);
2407 inc->lineinc = 1;
2408 inc->expansion = NULL;
2409 inc->mstk = NULL;
2410 istk = inc;
2411 list->uplevel(LIST_INCLUDE);
2413 free_tlist(origline);
2414 return DIRECTIVE_FOUND;
2416 case PP_USE:
2418 static macros_t *use_pkg;
2419 const char *pkg_macro = NULL;
2421 tline = tline->next;
2422 skip_white_(tline);
2423 tline = expand_id(tline);
2425 if (!tline || (tline->type != TOK_STRING &&
2426 tline->type != TOK_INTERNAL_STRING &&
2427 tline->type != TOK_ID)) {
2428 error(ERR_NONFATAL, "`%%use' expects a package name");
2429 free_tlist(origline);
2430 return DIRECTIVE_FOUND; /* but we did _something_ */
2432 if (tline->next)
2433 error(ERR_WARNING|ERR_PASS1,
2434 "trailing garbage after `%%use' ignored");
2435 if (tline->type == TOK_STRING)
2436 nasm_unquote_cstr(tline->text, i);
2437 use_pkg = nasm_stdmac_find_package(tline->text);
2438 if (!use_pkg)
2439 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2440 else
2441 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2442 if (use_pkg && smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2443 /* Not already included, go ahead and include it */
2444 stdmacpos = use_pkg;
2446 free_tlist(origline);
2447 return DIRECTIVE_FOUND;
2449 case PP_PUSH:
2450 case PP_REPL:
2451 case PP_POP:
2452 tline = tline->next;
2453 skip_white_(tline);
2454 tline = expand_id(tline);
2455 if (tline) {
2456 if (!tok_type_(tline, TOK_ID)) {
2457 error(ERR_NONFATAL, "`%s' expects a context identifier",
2458 pp_directives[i]);
2459 free_tlist(origline);
2460 return DIRECTIVE_FOUND; /* but we did _something_ */
2462 if (tline->next)
2463 error(ERR_WARNING|ERR_PASS1,
2464 "trailing garbage after `%s' ignored",
2465 pp_directives[i]);
2466 p = nasm_strdup(tline->text);
2467 } else {
2468 p = NULL; /* Anonymous */
2471 if (i == PP_PUSH) {
2472 ctx = nasm_malloc(sizeof(Context));
2473 ctx->next = cstk;
2474 hash_init(&ctx->localmac, HASH_SMALL);
2475 ctx->name = p;
2476 ctx->number = unique++;
2477 cstk = ctx;
2478 } else {
2479 /* %pop or %repl */
2480 if (!cstk) {
2481 error(ERR_NONFATAL, "`%s': context stack is empty",
2482 pp_directives[i]);
2483 } else if (i == PP_POP) {
2484 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2485 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2486 "expected %s",
2487 cstk->name ? cstk->name : "anonymous", p);
2488 else
2489 ctx_pop();
2490 } else {
2491 /* i == PP_REPL */
2492 nasm_free(cstk->name);
2493 cstk->name = p;
2494 p = NULL;
2496 nasm_free(p);
2498 free_tlist(origline);
2499 return DIRECTIVE_FOUND;
2500 case PP_FATAL:
2501 severity = ERR_FATAL;
2502 goto issue_error;
2503 case PP_ERROR:
2504 severity = ERR_NONFATAL;
2505 goto issue_error;
2506 case PP_WARNING:
2507 severity = ERR_WARNING|ERR_WARN_USER;
2508 goto issue_error;
2510 issue_error:
2512 /* Only error out if this is the final pass */
2513 if (pass != 2 && i != PP_FATAL)
2514 return DIRECTIVE_FOUND;
2516 tline->next = expand_smacro(tline->next);
2517 tline = tline->next;
2518 skip_white_(tline);
2519 t = tline ? tline->next : NULL;
2520 skip_white_(t);
2521 if (tok_type_(tline, TOK_STRING) && !t) {
2522 /* The line contains only a quoted string */
2523 p = tline->text;
2524 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2525 error(severity, "%s", p);
2526 } else {
2527 /* Not a quoted string, or more than a quoted string */
2528 p = detoken(tline, false);
2529 error(severity, "%s", p);
2530 nasm_free(p);
2532 free_tlist(origline);
2533 return DIRECTIVE_FOUND;
2536 CASE_PP_IF:
2537 if (istk->conds && !emitting(istk->conds->state))
2538 j = COND_NEVER;
2539 else {
2540 j = if_condition(tline->next, i);
2541 tline->next = NULL; /* it got freed */
2542 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2544 cond = nasm_malloc(sizeof(Cond));
2545 cond->next = istk->conds;
2546 cond->state = j;
2547 istk->conds = cond;
2548 if(istk->mstk)
2549 istk->mstk->condcnt ++;
2550 free_tlist(origline);
2551 return DIRECTIVE_FOUND;
2553 CASE_PP_ELIF:
2554 if (!istk->conds)
2555 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2556 switch(istk->conds->state) {
2557 case COND_IF_TRUE:
2558 istk->conds->state = COND_DONE;
2559 break;
2561 case COND_DONE:
2562 case COND_NEVER:
2563 break;
2565 case COND_ELSE_TRUE:
2566 case COND_ELSE_FALSE:
2567 error_precond(ERR_WARNING|ERR_PASS1,
2568 "`%%elif' after `%%else' ignored");
2569 istk->conds->state = COND_NEVER;
2570 break;
2572 case COND_IF_FALSE:
2574 * IMPORTANT: In the case of %if, we will already have
2575 * called expand_mmac_params(); however, if we're
2576 * processing an %elif we must have been in a
2577 * non-emitting mode, which would have inhibited
2578 * the normal invocation of expand_mmac_params().
2579 * Therefore, we have to do it explicitly here.
2581 j = if_condition(expand_mmac_params(tline->next), i);
2582 tline->next = NULL; /* it got freed */
2583 istk->conds->state =
2584 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2585 break;
2587 free_tlist(origline);
2588 return DIRECTIVE_FOUND;
2590 case PP_ELSE:
2591 if (tline->next)
2592 error_precond(ERR_WARNING|ERR_PASS1,
2593 "trailing garbage after `%%else' ignored");
2594 if (!istk->conds)
2595 error(ERR_FATAL, "`%%else': no matching `%%if'");
2596 switch(istk->conds->state) {
2597 case COND_IF_TRUE:
2598 case COND_DONE:
2599 istk->conds->state = COND_ELSE_FALSE;
2600 break;
2602 case COND_NEVER:
2603 break;
2605 case COND_IF_FALSE:
2606 istk->conds->state = COND_ELSE_TRUE;
2607 break;
2609 case COND_ELSE_TRUE:
2610 case COND_ELSE_FALSE:
2611 error_precond(ERR_WARNING|ERR_PASS1,
2612 "`%%else' after `%%else' ignored.");
2613 istk->conds->state = COND_NEVER;
2614 break;
2616 free_tlist(origline);
2617 return DIRECTIVE_FOUND;
2619 case PP_ENDIF:
2620 if (tline->next)
2621 error_precond(ERR_WARNING|ERR_PASS1,
2622 "trailing garbage after `%%endif' ignored");
2623 if (!istk->conds)
2624 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2625 cond = istk->conds;
2626 istk->conds = cond->next;
2627 nasm_free(cond);
2628 if(istk->mstk)
2629 istk->mstk->condcnt --;
2630 free_tlist(origline);
2631 return DIRECTIVE_FOUND;
2633 case PP_RMACRO:
2634 case PP_IRMACRO:
2635 case PP_MACRO:
2636 case PP_IMACRO:
2637 if (defining) {
2638 error(ERR_FATAL, "`%s': already defining a macro",
2639 pp_directives[i]);
2640 return DIRECTIVE_FOUND;
2642 defining = nasm_malloc(sizeof(MMacro));
2643 defining->max_depth =
2644 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2645 defining->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2646 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2647 nasm_free(defining);
2648 defining = NULL;
2649 return DIRECTIVE_FOUND;
2652 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2653 while (mmac) {
2654 if (!strcmp(mmac->name, defining->name) &&
2655 (mmac->nparam_min <= defining->nparam_max
2656 || defining->plus)
2657 && (defining->nparam_min <= mmac->nparam_max
2658 || mmac->plus)) {
2659 error(ERR_WARNING|ERR_PASS1,
2660 "redefining multi-line macro `%s'", defining->name);
2661 return DIRECTIVE_FOUND;
2663 mmac = mmac->next;
2665 free_tlist(origline);
2666 return DIRECTIVE_FOUND;
2668 case PP_ENDM:
2669 case PP_ENDMACRO:
2670 if (! (defining && defining->name)) {
2671 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2672 return DIRECTIVE_FOUND;
2674 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2675 defining->next = *mmhead;
2676 *mmhead = defining;
2677 defining = NULL;
2678 free_tlist(origline);
2679 return DIRECTIVE_FOUND;
2681 case PP_EXITMACRO:
2683 * We must search along istk->expansion until we hit a
2684 * macro-end marker for a macro with a name. Then we
2685 * bypass all lines between exitmacro and endmacro.
2687 for (l = istk->expansion; l; l = l->next)
2688 if (l->finishes && l->finishes->name)
2689 break;
2691 if (l) {
2693 * Remove all conditional entries relative to this
2694 * macro invocation. (safe to do in this context)
2696 for ( ; l->finishes->condcnt > 0; l->finishes->condcnt --) {
2697 cond = istk->conds;
2698 istk->conds = cond->next;
2699 nasm_free(cond);
2701 istk->expansion = l;
2702 } else {
2703 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2705 free_tlist(origline);
2706 return DIRECTIVE_FOUND;
2708 case PP_UNMACRO:
2709 case PP_UNIMACRO:
2711 MMacro **mmac_p;
2712 MMacro spec;
2714 spec.casesense = (i == PP_UNMACRO);
2715 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2716 return DIRECTIVE_FOUND;
2718 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2719 while (mmac_p && *mmac_p) {
2720 mmac = *mmac_p;
2721 if (mmac->casesense == spec.casesense &&
2722 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2723 mmac->nparam_min == spec.nparam_min &&
2724 mmac->nparam_max == spec.nparam_max &&
2725 mmac->plus == spec.plus) {
2726 *mmac_p = mmac->next;
2727 free_mmacro(mmac);
2728 } else {
2729 mmac_p = &mmac->next;
2732 free_tlist(origline);
2733 free_tlist(spec.dlist);
2734 return DIRECTIVE_FOUND;
2737 case PP_ROTATE:
2738 if (tline->next && tline->next->type == TOK_WHITESPACE)
2739 tline = tline->next;
2740 if (!tline->next) {
2741 free_tlist(origline);
2742 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2743 return DIRECTIVE_FOUND;
2745 t = expand_smacro(tline->next);
2746 tline->next = NULL;
2747 free_tlist(origline);
2748 tline = t;
2749 tptr = &t;
2750 tokval.t_type = TOKEN_INVALID;
2751 evalresult =
2752 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2753 free_tlist(tline);
2754 if (!evalresult)
2755 return DIRECTIVE_FOUND;
2756 if (tokval.t_type)
2757 error(ERR_WARNING|ERR_PASS1,
2758 "trailing garbage after expression ignored");
2759 if (!is_simple(evalresult)) {
2760 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2761 return DIRECTIVE_FOUND;
2763 mmac = istk->mstk;
2764 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2765 mmac = mmac->next_active;
2766 if (!mmac) {
2767 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2768 } else if (mmac->nparam == 0) {
2769 error(ERR_NONFATAL,
2770 "`%%rotate' invoked within macro without parameters");
2771 } else {
2772 int rotate = mmac->rotate + reloc_value(evalresult);
2774 rotate %= (int)mmac->nparam;
2775 if (rotate < 0)
2776 rotate += mmac->nparam;
2778 mmac->rotate = rotate;
2780 return DIRECTIVE_FOUND;
2782 case PP_REP:
2783 nolist = false;
2784 do {
2785 tline = tline->next;
2786 } while (tok_type_(tline, TOK_WHITESPACE));
2788 if (tok_type_(tline, TOK_ID) &&
2789 nasm_stricmp(tline->text, ".nolist") == 0) {
2790 nolist = true;
2791 do {
2792 tline = tline->next;
2793 } while (tok_type_(tline, TOK_WHITESPACE));
2796 if (tline) {
2797 t = expand_smacro(tline);
2798 tptr = &t;
2799 tokval.t_type = TOKEN_INVALID;
2800 evalresult =
2801 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2802 if (!evalresult) {
2803 free_tlist(origline);
2804 return DIRECTIVE_FOUND;
2806 if (tokval.t_type)
2807 error(ERR_WARNING|ERR_PASS1,
2808 "trailing garbage after expression ignored");
2809 if (!is_simple(evalresult)) {
2810 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2811 return DIRECTIVE_FOUND;
2813 count = reloc_value(evalresult) + 1;
2814 } else {
2815 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2816 count = 0;
2818 free_tlist(origline);
2820 tmp_defining = defining;
2821 defining = nasm_malloc(sizeof(MMacro));
2822 defining->prev = NULL;
2823 defining->name = NULL; /* flags this macro as a %rep block */
2824 defining->casesense = false;
2825 defining->plus = false;
2826 defining->nolist = nolist;
2827 defining->in_progress = count;
2828 defining->max_depth = 0;
2829 defining->nparam_min = defining->nparam_max = 0;
2830 defining->defaults = NULL;
2831 defining->dlist = NULL;
2832 defining->expansion = NULL;
2833 defining->next_active = istk->mstk;
2834 defining->rep_nest = tmp_defining;
2835 return DIRECTIVE_FOUND;
2837 case PP_ENDREP:
2838 if (!defining || defining->name) {
2839 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2840 return DIRECTIVE_FOUND;
2844 * Now we have a "macro" defined - although it has no name
2845 * and we won't be entering it in the hash tables - we must
2846 * push a macro-end marker for it on to istk->expansion.
2847 * After that, it will take care of propagating itself (a
2848 * macro-end marker line for a macro which is really a %rep
2849 * block will cause the macro to be re-expanded, complete
2850 * with another macro-end marker to ensure the process
2851 * continues) until the whole expansion is forcibly removed
2852 * from istk->expansion by a %exitrep.
2854 l = nasm_malloc(sizeof(Line));
2855 l->next = istk->expansion;
2856 l->finishes = defining;
2857 l->first = NULL;
2858 istk->expansion = l;
2860 istk->mstk = defining;
2862 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2863 tmp_defining = defining;
2864 defining = defining->rep_nest;
2865 free_tlist(origline);
2866 return DIRECTIVE_FOUND;
2868 case PP_EXITREP:
2870 * We must search along istk->expansion until we hit a
2871 * macro-end marker for a macro with no name. Then we set
2872 * its `in_progress' flag to 0.
2874 for (l = istk->expansion; l; l = l->next)
2875 if (l->finishes && !l->finishes->name)
2876 break;
2878 if (l)
2879 l->finishes->in_progress = 1;
2880 else
2881 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2882 free_tlist(origline);
2883 return DIRECTIVE_FOUND;
2885 case PP_XDEFINE:
2886 case PP_IXDEFINE:
2887 case PP_DEFINE:
2888 case PP_IDEFINE:
2889 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2891 tline = tline->next;
2892 skip_white_(tline);
2893 tline = expand_id(tline);
2894 if (!tline || (tline->type != TOK_ID &&
2895 (tline->type != TOK_PREPROC_ID ||
2896 tline->text[1] != '$'))) {
2897 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2898 pp_directives[i]);
2899 free_tlist(origline);
2900 return DIRECTIVE_FOUND;
2903 ctx = get_ctx(tline->text, &mname, false);
2904 last = tline;
2905 param_start = tline = tline->next;
2906 nparam = 0;
2908 /* Expand the macro definition now for %xdefine and %ixdefine */
2909 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2910 tline = expand_smacro(tline);
2912 if (tok_is_(tline, "(")) {
2914 * This macro has parameters.
2917 tline = tline->next;
2918 while (1) {
2919 skip_white_(tline);
2920 if (!tline) {
2921 error(ERR_NONFATAL, "parameter identifier expected");
2922 free_tlist(origline);
2923 return DIRECTIVE_FOUND;
2925 if (tline->type != TOK_ID) {
2926 error(ERR_NONFATAL,
2927 "`%s': parameter identifier expected",
2928 tline->text);
2929 free_tlist(origline);
2930 return DIRECTIVE_FOUND;
2932 tline->type = TOK_SMAC_PARAM + nparam++;
2933 tline = tline->next;
2934 skip_white_(tline);
2935 if (tok_is_(tline, ",")) {
2936 tline = tline->next;
2937 } else {
2938 if (!tok_is_(tline, ")")) {
2939 error(ERR_NONFATAL,
2940 "`)' expected to terminate macro template");
2941 free_tlist(origline);
2942 return DIRECTIVE_FOUND;
2944 break;
2947 last = tline;
2948 tline = tline->next;
2950 if (tok_type_(tline, TOK_WHITESPACE))
2951 last = tline, tline = tline->next;
2952 macro_start = NULL;
2953 last->next = NULL;
2954 t = tline;
2955 while (t) {
2956 if (t->type == TOK_ID) {
2957 for (tt = param_start; tt; tt = tt->next)
2958 if (tt->type >= TOK_SMAC_PARAM &&
2959 !strcmp(tt->text, t->text))
2960 t->type = tt->type;
2962 tt = t->next;
2963 t->next = macro_start;
2964 macro_start = t;
2965 t = tt;
2968 * Good. We now have a macro name, a parameter count, and a
2969 * token list (in reverse order) for an expansion. We ought
2970 * to be OK just to create an SMacro, store it, and let
2971 * free_tlist have the rest of the line (which we have
2972 * carefully re-terminated after chopping off the expansion
2973 * from the end).
2975 define_smacro(ctx, mname, casesense, nparam, macro_start);
2976 free_tlist(origline);
2977 return DIRECTIVE_FOUND;
2979 case PP_UNDEF:
2980 tline = tline->next;
2981 skip_white_(tline);
2982 tline = expand_id(tline);
2983 if (!tline || (tline->type != TOK_ID &&
2984 (tline->type != TOK_PREPROC_ID ||
2985 tline->text[1] != '$'))) {
2986 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2987 free_tlist(origline);
2988 return DIRECTIVE_FOUND;
2990 if (tline->next) {
2991 error(ERR_WARNING|ERR_PASS1,
2992 "trailing garbage after macro name ignored");
2995 /* Find the context that symbol belongs to */
2996 ctx = get_ctx(tline->text, &mname, false);
2997 undef_smacro(ctx, mname);
2998 free_tlist(origline);
2999 return DIRECTIVE_FOUND;
3001 case PP_DEFSTR:
3002 case PP_IDEFSTR:
3003 casesense = (i == PP_DEFSTR);
3005 tline = tline->next;
3006 skip_white_(tline);
3007 tline = expand_id(tline);
3008 if (!tline || (tline->type != TOK_ID &&
3009 (tline->type != TOK_PREPROC_ID ||
3010 tline->text[1] != '$'))) {
3011 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3012 pp_directives[i]);
3013 free_tlist(origline);
3014 return DIRECTIVE_FOUND;
3017 ctx = get_ctx(tline->text, &mname, false);
3018 last = tline;
3019 tline = expand_smacro(tline->next);
3020 last->next = NULL;
3022 while (tok_type_(tline, TOK_WHITESPACE))
3023 tline = delete_Token(tline);
3025 p = detoken(tline, false);
3026 macro_start = nasm_malloc(sizeof(*macro_start));
3027 macro_start->next = NULL;
3028 macro_start->text = nasm_quote(p, strlen(p));
3029 macro_start->type = TOK_STRING;
3030 macro_start->a.mac = NULL;
3031 nasm_free(p);
3034 * We now have a macro name, an implicit parameter count of
3035 * zero, and a string token to use as an expansion. Create
3036 * and store an SMacro.
3038 define_smacro(ctx, mname, casesense, 0, macro_start);
3039 free_tlist(origline);
3040 return DIRECTIVE_FOUND;
3042 case PP_DEFTOK:
3043 case PP_IDEFTOK:
3044 casesense = (i == PP_DEFTOK);
3046 tline = tline->next;
3047 skip_white_(tline);
3048 tline = expand_id(tline);
3049 if (!tline || (tline->type != TOK_ID &&
3050 (tline->type != TOK_PREPROC_ID ||
3051 tline->text[1] != '$'))) {
3052 error(ERR_NONFATAL,
3053 "`%s' expects a macro identifier as first parameter",
3054 pp_directives[i]);
3055 free_tlist(origline);
3056 return DIRECTIVE_FOUND;
3058 ctx = get_ctx(tline->text, &mname, false);
3059 last = tline;
3060 tline = expand_smacro(tline->next);
3061 last->next = NULL;
3063 t = tline;
3064 while (tok_type_(t, TOK_WHITESPACE))
3065 t = t->next;
3066 /* t should now point to the string */
3067 if (t->type != TOK_STRING) {
3068 error(ERR_NONFATAL,
3069 "`%s` requires string as second parameter",
3070 pp_directives[i]);
3071 free_tlist(tline);
3072 free_tlist(origline);
3073 return DIRECTIVE_FOUND;
3076 nasm_unquote_cstr(t->text, i);
3077 macro_start = tokenize(t->text);
3080 * We now have a macro name, an implicit parameter count of
3081 * zero, and a numeric token to use as an expansion. Create
3082 * and store an SMacro.
3084 define_smacro(ctx, mname, casesense, 0, macro_start);
3085 free_tlist(tline);
3086 free_tlist(origline);
3087 return DIRECTIVE_FOUND;
3089 case PP_PATHSEARCH:
3091 FILE *fp;
3092 StrList *xsl = NULL;
3093 StrList **xst = &xsl;
3095 casesense = true;
3097 tline = tline->next;
3098 skip_white_(tline);
3099 tline = expand_id(tline);
3100 if (!tline || (tline->type != TOK_ID &&
3101 (tline->type != TOK_PREPROC_ID ||
3102 tline->text[1] != '$'))) {
3103 error(ERR_NONFATAL,
3104 "`%%pathsearch' expects a macro identifier as first parameter");
3105 free_tlist(origline);
3106 return DIRECTIVE_FOUND;
3108 ctx = get_ctx(tline->text, &mname, false);
3109 last = tline;
3110 tline = expand_smacro(tline->next);
3111 last->next = NULL;
3113 t = tline;
3114 while (tok_type_(t, TOK_WHITESPACE))
3115 t = t->next;
3117 if (!t || (t->type != TOK_STRING &&
3118 t->type != TOK_INTERNAL_STRING)) {
3119 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3120 free_tlist(tline);
3121 free_tlist(origline);
3122 return DIRECTIVE_FOUND; /* but we did _something_ */
3124 if (t->next)
3125 error(ERR_WARNING|ERR_PASS1,
3126 "trailing garbage after `%%pathsearch' ignored");
3127 p = t->text;
3128 if (t->type != TOK_INTERNAL_STRING)
3129 nasm_unquote(p, NULL);
3131 fp = inc_fopen(p, &xsl, &xst, true);
3132 if (fp) {
3133 p = xsl->str;
3134 fclose(fp); /* Don't actually care about the file */
3136 macro_start = nasm_malloc(sizeof(*macro_start));
3137 macro_start->next = NULL;
3138 macro_start->text = nasm_quote(p, strlen(p));
3139 macro_start->type = TOK_STRING;
3140 macro_start->a.mac = NULL;
3141 if (xsl)
3142 nasm_free(xsl);
3145 * We now have a macro name, an implicit parameter count of
3146 * zero, and a string token to use as an expansion. Create
3147 * and store an SMacro.
3149 define_smacro(ctx, mname, casesense, 0, macro_start);
3150 free_tlist(tline);
3151 free_tlist(origline);
3152 return DIRECTIVE_FOUND;
3155 case PP_STRLEN:
3156 casesense = true;
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 "`%%strlen' expects a macro identifier as first parameter");
3166 free_tlist(origline);
3167 return DIRECTIVE_FOUND;
3169 ctx = get_ctx(tline->text, &mname, false);
3170 last = tline;
3171 tline = expand_smacro(tline->next);
3172 last->next = NULL;
3174 t = tline;
3175 while (tok_type_(t, TOK_WHITESPACE))
3176 t = t->next;
3177 /* t should now point to the string */
3178 if (t->type != TOK_STRING) {
3179 error(ERR_NONFATAL,
3180 "`%%strlen` requires string as second parameter");
3181 free_tlist(tline);
3182 free_tlist(origline);
3183 return DIRECTIVE_FOUND;
3186 macro_start = nasm_malloc(sizeof(*macro_start));
3187 macro_start->next = NULL;
3188 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3189 macro_start->a.mac = NULL;
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_STRCAT:
3202 casesense = true;
3204 tline = tline->next;
3205 skip_white_(tline);
3206 tline = expand_id(tline);
3207 if (!tline || (tline->type != TOK_ID &&
3208 (tline->type != TOK_PREPROC_ID ||
3209 tline->text[1] != '$'))) {
3210 error(ERR_NONFATAL,
3211 "`%%strcat' expects a macro identifier as first parameter");
3212 free_tlist(origline);
3213 return DIRECTIVE_FOUND;
3215 ctx = get_ctx(tline->text, &mname, false);
3216 last = tline;
3217 tline = expand_smacro(tline->next);
3218 last->next = NULL;
3220 len = 0;
3221 for (t = tline; t; t = t->next) {
3222 switch (t->type) {
3223 case TOK_WHITESPACE:
3224 break;
3225 case TOK_STRING:
3226 len += t->a.len = nasm_unquote(t->text, NULL);
3227 break;
3228 case TOK_OTHER:
3229 if (!strcmp(t->text, ",")) /* permit comma separators */
3230 break;
3231 /* else fall through */
3232 default:
3233 error(ERR_NONFATAL,
3234 "non-string passed to `%%strcat' (%d)", t->type);
3235 free_tlist(tline);
3236 free_tlist(origline);
3237 return DIRECTIVE_FOUND;
3241 p = pp = nasm_malloc(len);
3242 for (t = tline; t; t = t->next) {
3243 if (t->type == TOK_STRING) {
3244 memcpy(p, t->text, t->a.len);
3245 p += t->a.len;
3250 * We now have a macro name, an implicit parameter count of
3251 * zero, and a numeric token to use as an expansion. Create
3252 * and store an SMacro.
3254 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3255 macro_start->text = nasm_quote(pp, len);
3256 nasm_free(pp);
3257 define_smacro(ctx, mname, casesense, 0, macro_start);
3258 free_tlist(tline);
3259 free_tlist(origline);
3260 return DIRECTIVE_FOUND;
3262 case PP_SUBSTR:
3264 int64_t a1, a2;
3265 size_t len;
3267 casesense = true;
3269 tline = tline->next;
3270 skip_white_(tline);
3271 tline = expand_id(tline);
3272 if (!tline || (tline->type != TOK_ID &&
3273 (tline->type != TOK_PREPROC_ID ||
3274 tline->text[1] != '$'))) {
3275 error(ERR_NONFATAL,
3276 "`%%substr' expects a macro identifier as first parameter");
3277 free_tlist(origline);
3278 return DIRECTIVE_FOUND;
3280 ctx = get_ctx(tline->text, &mname, false);
3281 last = tline;
3282 tline = expand_smacro(tline->next);
3283 last->next = NULL;
3285 t = tline->next;
3286 while (tok_type_(t, TOK_WHITESPACE))
3287 t = t->next;
3289 /* t should now point to the string */
3290 if (t->type != TOK_STRING) {
3291 error(ERR_NONFATAL,
3292 "`%%substr` requires string as second parameter");
3293 free_tlist(tline);
3294 free_tlist(origline);
3295 return DIRECTIVE_FOUND;
3298 tt = t->next;
3299 tptr = &tt;
3300 tokval.t_type = TOKEN_INVALID;
3301 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3302 pass, error, NULL);
3303 if (!evalresult) {
3304 free_tlist(tline);
3305 free_tlist(origline);
3306 return DIRECTIVE_FOUND;
3307 } else if (!is_simple(evalresult)) {
3308 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3309 free_tlist(tline);
3310 free_tlist(origline);
3311 return DIRECTIVE_FOUND;
3313 a1 = evalresult->value-1;
3315 while (tok_type_(tt, TOK_WHITESPACE))
3316 tt = tt->next;
3317 if (!tt) {
3318 a2 = 1; /* Backwards compatibility: one character */
3319 } else {
3320 tokval.t_type = TOKEN_INVALID;
3321 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3322 pass, error, NULL);
3323 if (!evalresult) {
3324 free_tlist(tline);
3325 free_tlist(origline);
3326 return DIRECTIVE_FOUND;
3327 } else if (!is_simple(evalresult)) {
3328 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3329 free_tlist(tline);
3330 free_tlist(origline);
3331 return DIRECTIVE_FOUND;
3333 a2 = evalresult->value;
3336 len = nasm_unquote(t->text, NULL);
3337 if (a2 < 0)
3338 a2 = a2+1+len-a1;
3339 if (a1+a2 > (int64_t)len)
3340 a2 = len-a1;
3342 macro_start = nasm_malloc(sizeof(*macro_start));
3343 macro_start->next = NULL;
3344 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3345 macro_start->type = TOK_STRING;
3346 macro_start->a.mac = NULL;
3349 * We now have a macro name, an implicit parameter count of
3350 * zero, and a numeric token to use as an expansion. Create
3351 * and store an SMacro.
3353 define_smacro(ctx, mname, casesense, 0, macro_start);
3354 free_tlist(tline);
3355 free_tlist(origline);
3356 return DIRECTIVE_FOUND;
3359 case PP_ASSIGN:
3360 case PP_IASSIGN:
3361 casesense = (i == PP_ASSIGN);
3363 tline = tline->next;
3364 skip_white_(tline);
3365 tline = expand_id(tline);
3366 if (!tline || (tline->type != TOK_ID &&
3367 (tline->type != TOK_PREPROC_ID ||
3368 tline->text[1] != '$'))) {
3369 error(ERR_NONFATAL,
3370 "`%%%sassign' expects a macro identifier",
3371 (i == PP_IASSIGN ? "i" : ""));
3372 free_tlist(origline);
3373 return DIRECTIVE_FOUND;
3375 ctx = get_ctx(tline->text, &mname, false);
3376 last = tline;
3377 tline = expand_smacro(tline->next);
3378 last->next = NULL;
3380 t = tline;
3381 tptr = &t;
3382 tokval.t_type = TOKEN_INVALID;
3383 evalresult =
3384 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3385 free_tlist(tline);
3386 if (!evalresult) {
3387 free_tlist(origline);
3388 return DIRECTIVE_FOUND;
3391 if (tokval.t_type)
3392 error(ERR_WARNING|ERR_PASS1,
3393 "trailing garbage after expression ignored");
3395 if (!is_simple(evalresult)) {
3396 error(ERR_NONFATAL,
3397 "non-constant value given to `%%%sassign'",
3398 (i == PP_IASSIGN ? "i" : ""));
3399 free_tlist(origline);
3400 return DIRECTIVE_FOUND;
3403 macro_start = nasm_malloc(sizeof(*macro_start));
3404 macro_start->next = NULL;
3405 make_tok_num(macro_start, reloc_value(evalresult));
3406 macro_start->a.mac = NULL;
3409 * We now have a macro name, an implicit parameter count of
3410 * zero, and a numeric token to use as an expansion. Create
3411 * and store an SMacro.
3413 define_smacro(ctx, mname, casesense, 0, macro_start);
3414 free_tlist(origline);
3415 return DIRECTIVE_FOUND;
3417 case PP_LINE:
3419 * Syntax is `%line nnn[+mmm] [filename]'
3421 tline = tline->next;
3422 skip_white_(tline);
3423 if (!tok_type_(tline, TOK_NUMBER)) {
3424 error(ERR_NONFATAL, "`%%line' expects line number");
3425 free_tlist(origline);
3426 return DIRECTIVE_FOUND;
3428 k = readnum(tline->text, &err);
3429 m = 1;
3430 tline = tline->next;
3431 if (tok_is_(tline, "+")) {
3432 tline = tline->next;
3433 if (!tok_type_(tline, TOK_NUMBER)) {
3434 error(ERR_NONFATAL, "`%%line' expects line increment");
3435 free_tlist(origline);
3436 return DIRECTIVE_FOUND;
3438 m = readnum(tline->text, &err);
3439 tline = tline->next;
3441 skip_white_(tline);
3442 src_set_linnum(k);
3443 istk->lineinc = m;
3444 if (tline) {
3445 nasm_free(src_set_fname(detoken(tline, false)));
3447 free_tlist(origline);
3448 return DIRECTIVE_FOUND;
3450 default:
3451 error(ERR_FATAL,
3452 "preprocessor directive `%s' not yet implemented",
3453 pp_directives[i]);
3454 return DIRECTIVE_FOUND;
3459 * Ensure that a macro parameter contains a condition code and
3460 * nothing else. Return the condition code index if so, or -1
3461 * otherwise.
3463 static int find_cc(Token * t)
3465 Token *tt;
3466 int i, j, k, m;
3468 if (!t)
3469 return -1; /* Probably a %+ without a space */
3471 skip_white_(t);
3472 if (t->type != TOK_ID)
3473 return -1;
3474 tt = t->next;
3475 skip_white_(tt);
3476 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3477 return -1;
3479 i = -1;
3480 j = elements(conditions);
3481 while (j - i > 1) {
3482 k = (j + i) / 2;
3483 m = nasm_stricmp(t->text, conditions[k]);
3484 if (m == 0) {
3485 i = k;
3486 j = -2;
3487 break;
3488 } else if (m < 0) {
3489 j = k;
3490 } else
3491 i = k;
3493 if (j != -2)
3494 return -1;
3495 return i;
3498 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3500 Token **tail, *t, *tt;
3501 Token **paste_head;
3502 bool did_paste = false;
3503 char *tmp;
3505 /* Now handle token pasting... */
3506 paste_head = NULL;
3507 tail = head;
3508 while ((t = *tail) && (tt = t->next)) {
3509 switch (t->type) {
3510 case TOK_WHITESPACE:
3511 if (tt->type == TOK_WHITESPACE) {
3512 /* Zap adjacent whitespace tokens */
3513 t->next = delete_Token(tt);
3514 } else {
3515 /* Do not advance paste_head here */
3516 tail = &t->next;
3518 break;
3519 case TOK_ID:
3520 case TOK_PREPROC_ID:
3521 case TOK_NUMBER:
3522 case TOK_FLOAT:
3524 size_t len = 0;
3525 char *tmp, *p;
3527 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3528 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3529 tt->type == TOK_OTHER)) {
3530 len += strlen(tt->text);
3531 tt = tt->next;
3535 * Now tt points to the first token after
3536 * the potential paste area...
3538 if (tt != t->next) {
3539 /* We have at least two tokens... */
3540 len += strlen(t->text);
3541 p = tmp = nasm_malloc(len+1);
3543 while (t != tt) {
3544 strcpy(p, t->text);
3545 p = strchr(p, '\0');
3546 t = delete_Token(t);
3549 t = *tail = tokenize(tmp);
3550 nasm_free(tmp);
3552 while (t->next) {
3553 tail = &t->next;
3554 t = t->next;
3556 t->next = tt; /* Attach the remaining token chain */
3558 did_paste = true;
3560 paste_head = tail;
3561 tail = &t->next;
3562 break;
3564 case TOK_PASTE: /* %+ */
3565 if (handle_paste_tokens) {
3566 /* Zap %+ and whitespace tokens to the right */
3567 while (t && (t->type == TOK_WHITESPACE ||
3568 t->type == TOK_PASTE))
3569 t = *tail = delete_Token(t);
3570 if (!paste_head || !t)
3571 break; /* Nothing to paste with */
3572 tail = paste_head;
3573 t = *tail;
3574 tt = t->next;
3575 while (tok_type_(tt, TOK_WHITESPACE))
3576 tt = t->next = delete_Token(tt);
3578 if (tt) {
3579 tmp = nasm_strcat(t->text, tt->text);
3580 delete_Token(t);
3581 tt = delete_Token(tt);
3582 t = *tail = tokenize(tmp);
3583 nasm_free(tmp);
3584 while (t->next) {
3585 tail = &t->next;
3586 t = t->next;
3588 t->next = tt; /* Attach the remaining token chain */
3589 did_paste = true;
3591 paste_head = tail;
3592 tail = &t->next;
3593 break;
3595 /* else fall through */
3596 default:
3597 tail = paste_head = &t->next;
3598 break;
3601 return did_paste;
3604 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3605 * %-n) and MMacro-local identifiers (%%foo) as well as
3606 * macro indirection (%[...]).
3608 static Token *expand_mmac_params(Token * tline)
3610 Token *t, *tt, **tail, *thead;
3611 bool changed = false;
3613 tail = &thead;
3614 thead = NULL;
3616 while (tline) {
3617 if (tline->type == TOK_PREPROC_ID &&
3618 (((tline->text[1] == '+' || tline->text[1] == '-')
3619 && tline->text[2]) || tline->text[1] == '%'
3620 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
3621 char *text = NULL;
3622 int type = 0, cc; /* type = 0 to placate optimisers */
3623 char tmpbuf[30];
3624 unsigned int n;
3625 int i;
3626 MMacro *mac;
3628 t = tline;
3629 tline = tline->next;
3631 mac = istk->mstk;
3632 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3633 mac = mac->next_active;
3634 if (!mac)
3635 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3636 else
3637 switch (t->text[1]) {
3639 * We have to make a substitution of one of the
3640 * forms %1, %-1, %+1, %%foo, %0.
3642 case '0':
3643 type = TOK_NUMBER;
3644 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3645 text = nasm_strdup(tmpbuf);
3646 break;
3647 case '%':
3648 type = TOK_ID;
3649 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3650 mac->unique);
3651 text = nasm_strcat(tmpbuf, t->text + 2);
3652 break;
3653 case '-':
3654 n = atoi(t->text + 2) - 1;
3655 if (n >= mac->nparam)
3656 tt = NULL;
3657 else {
3658 if (mac->nparam > 1)
3659 n = (n + mac->rotate) % mac->nparam;
3660 tt = mac->params[n];
3662 cc = find_cc(tt);
3663 if (cc == -1) {
3664 error(ERR_NONFATAL,
3665 "macro parameter %d is not a condition code",
3666 n + 1);
3667 text = NULL;
3668 } else {
3669 type = TOK_ID;
3670 if (inverse_ccs[cc] == -1) {
3671 error(ERR_NONFATAL,
3672 "condition code `%s' is not invertible",
3673 conditions[cc]);
3674 text = NULL;
3675 } else
3676 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3678 break;
3679 case '+':
3680 n = atoi(t->text + 2) - 1;
3681 if (n >= mac->nparam)
3682 tt = NULL;
3683 else {
3684 if (mac->nparam > 1)
3685 n = (n + mac->rotate) % mac->nparam;
3686 tt = mac->params[n];
3688 cc = find_cc(tt);
3689 if (cc == -1) {
3690 error(ERR_NONFATAL,
3691 "macro parameter %d is not a condition code",
3692 n + 1);
3693 text = NULL;
3694 } else {
3695 type = TOK_ID;
3696 text = nasm_strdup(conditions[cc]);
3698 break;
3699 default:
3700 n = atoi(t->text + 1) - 1;
3701 if (n >= mac->nparam)
3702 tt = NULL;
3703 else {
3704 if (mac->nparam > 1)
3705 n = (n + mac->rotate) % mac->nparam;
3706 tt = mac->params[n];
3708 if (tt) {
3709 for (i = 0; i < mac->paramlen[n]; i++) {
3710 *tail = new_Token(NULL, tt->type, tt->text, 0);
3711 tail = &(*tail)->next;
3712 tt = tt->next;
3715 text = NULL; /* we've done it here */
3716 break;
3718 if (!text) {
3719 delete_Token(t);
3720 } else {
3721 *tail = t;
3722 tail = &t->next;
3723 t->type = type;
3724 nasm_free(t->text);
3725 t->text = text;
3726 t->a.mac = NULL;
3728 changed = true;
3729 continue;
3730 } else if (tline->type == TOK_INDIRECT) {
3731 t = tline;
3732 tline = tline->next;
3733 tt = tokenize(t->text);
3734 tt = expand_mmac_params(tt);
3735 tt = expand_smacro(tt);
3736 *tail = tt;
3737 while (tt) {
3738 tt->a.mac = NULL; /* Necessary? */
3739 tail = &tt->next;
3740 tt = tt->next;
3742 delete_Token(t);
3743 changed = true;
3744 } else {
3745 t = *tail = tline;
3746 tline = tline->next;
3747 t->a.mac = NULL;
3748 tail = &t->next;
3751 *tail = NULL;
3753 if (changed)
3754 paste_tokens(&thead, false);
3756 return thead;
3760 * Expand all single-line macro calls made in the given line.
3761 * Return the expanded version of the line. The original is deemed
3762 * to be destroyed in the process. (In reality we'll just move
3763 * Tokens from input to output a lot of the time, rather than
3764 * actually bothering to destroy and replicate.)
3767 static Token *expand_smacro(Token * tline)
3769 Token *t, *tt, *mstart, **tail, *thead;
3770 SMacro *head = NULL, *m;
3771 Token **params;
3772 int *paramsize;
3773 unsigned int nparam, sparam;
3774 int brackets;
3775 Token *org_tline = tline;
3776 Context *ctx;
3777 const char *mname;
3778 int deadman = DEADMAN_LIMIT;
3779 bool expanded;
3782 * Trick: we should avoid changing the start token pointer since it can
3783 * be contained in "next" field of other token. Because of this
3784 * we allocate a copy of first token and work with it; at the end of
3785 * routine we copy it back
3787 if (org_tline) {
3788 tline =
3789 new_Token(org_tline->next, org_tline->type, org_tline->text,
3791 tline->a.mac = org_tline->a.mac;
3792 nasm_free(org_tline->text);
3793 org_tline->text = NULL;
3796 expanded = true; /* Always expand %+ at least once */
3798 again:
3799 tail = &thead;
3800 thead = NULL;
3802 while (tline) { /* main token loop */
3803 if (!--deadman) {
3804 error(ERR_NONFATAL, "interminable macro recursion");
3805 goto err;
3808 if ((mname = tline->text)) {
3809 /* if this token is a local macro, look in local context */
3810 if (tline->type == TOK_ID) {
3811 head = (SMacro *)hash_findix(&smacros, mname);
3812 } else if (tline->type == TOK_PREPROC_ID) {
3813 ctx = get_ctx(mname, &mname, true);
3814 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
3815 } else
3816 head = NULL;
3819 * We've hit an identifier. As in is_mmacro below, we first
3820 * check whether the identifier is a single-line macro at
3821 * all, then think about checking for parameters if
3822 * necessary.
3824 for (m = head; m; m = m->next)
3825 if (!mstrcmp(m->name, mname, m->casesense))
3826 break;
3827 if (m) {
3828 mstart = tline;
3829 params = NULL;
3830 paramsize = NULL;
3831 if (m->nparam == 0) {
3833 * Simple case: the macro is parameterless. Discard the
3834 * one token that the macro call took, and push the
3835 * expansion back on the to-do stack.
3837 if (!m->expansion) {
3838 if (!strcmp("__FILE__", m->name)) {
3839 int32_t num = 0;
3840 char *file = NULL;
3841 src_get(&num, &file);
3842 tline->text = nasm_quote(file, strlen(file));
3843 tline->type = TOK_STRING;
3844 nasm_free(file);
3845 continue;
3847 if (!strcmp("__LINE__", m->name)) {
3848 nasm_free(tline->text);
3849 make_tok_num(tline, src_get_linnum());
3850 continue;
3852 if (!strcmp("__BITS__", m->name)) {
3853 nasm_free(tline->text);
3854 make_tok_num(tline, globalbits);
3855 continue;
3857 tline = delete_Token(tline);
3858 continue;
3860 } else {
3862 * Complicated case: at least one macro with this name
3863 * exists and takes parameters. We must find the
3864 * parameters in the call, count them, find the SMacro
3865 * that corresponds to that form of the macro call, and
3866 * substitute for the parameters when we expand. What a
3867 * pain.
3869 /*tline = tline->next;
3870 skip_white_(tline); */
3871 do {
3872 t = tline->next;
3873 while (tok_type_(t, TOK_SMAC_END)) {
3874 t->a.mac->in_progress = false;
3875 t->text = NULL;
3876 t = tline->next = delete_Token(t);
3878 tline = t;
3879 } while (tok_type_(tline, TOK_WHITESPACE));
3880 if (!tok_is_(tline, "(")) {
3882 * This macro wasn't called with parameters: ignore
3883 * the call. (Behaviour borrowed from gnu cpp.)
3885 tline = mstart;
3886 m = NULL;
3887 } else {
3888 int paren = 0;
3889 int white = 0;
3890 brackets = 0;
3891 nparam = 0;
3892 sparam = PARAM_DELTA;
3893 params = nasm_malloc(sparam * sizeof(Token *));
3894 params[0] = tline->next;
3895 paramsize = nasm_malloc(sparam * sizeof(int));
3896 paramsize[0] = 0;
3897 while (true) { /* parameter loop */
3899 * For some unusual expansions
3900 * which concatenates function call
3902 t = tline->next;
3903 while (tok_type_(t, TOK_SMAC_END)) {
3904 t->a.mac->in_progress = false;
3905 t->text = NULL;
3906 t = tline->next = delete_Token(t);
3908 tline = t;
3910 if (!tline) {
3911 error(ERR_NONFATAL,
3912 "macro call expects terminating `)'");
3913 break;
3915 if (tline->type == TOK_WHITESPACE
3916 && brackets <= 0) {
3917 if (paramsize[nparam])
3918 white++;
3919 else
3920 params[nparam] = tline->next;
3921 continue; /* parameter loop */
3923 if (tline->type == TOK_OTHER
3924 && tline->text[1] == 0) {
3925 char ch = tline->text[0];
3926 if (ch == ',' && !paren && brackets <= 0) {
3927 if (++nparam >= sparam) {
3928 sparam += PARAM_DELTA;
3929 params = nasm_realloc(params,
3930 sparam *
3931 sizeof(Token
3932 *));
3933 paramsize =
3934 nasm_realloc(paramsize,
3935 sparam *
3936 sizeof(int));
3938 params[nparam] = tline->next;
3939 paramsize[nparam] = 0;
3940 white = 0;
3941 continue; /* parameter loop */
3943 if (ch == '{' &&
3944 (brackets > 0 || (brackets == 0 &&
3945 !paramsize[nparam])))
3947 if (!(brackets++)) {
3948 params[nparam] = tline->next;
3949 continue; /* parameter loop */
3952 if (ch == '}' && brackets > 0)
3953 if (--brackets == 0) {
3954 brackets = -1;
3955 continue; /* parameter loop */
3957 if (ch == '(' && !brackets)
3958 paren++;
3959 if (ch == ')' && brackets <= 0)
3960 if (--paren < 0)
3961 break;
3963 if (brackets < 0) {
3964 brackets = 0;
3965 error(ERR_NONFATAL, "braces do not "
3966 "enclose all of macro parameter");
3968 paramsize[nparam] += white + 1;
3969 white = 0;
3970 } /* parameter loop */
3971 nparam++;
3972 while (m && (m->nparam != nparam ||
3973 mstrcmp(m->name, mname,
3974 m->casesense)))
3975 m = m->next;
3976 if (!m)
3977 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
3978 "macro `%s' exists, "
3979 "but not taking %d parameters",
3980 mstart->text, nparam);
3983 if (m && m->in_progress)
3984 m = NULL;
3985 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3987 * Design question: should we handle !tline, which
3988 * indicates missing ')' here, or expand those
3989 * macros anyway, which requires the (t) test a few
3990 * lines down?
3992 nasm_free(params);
3993 nasm_free(paramsize);
3994 tline = mstart;
3995 } else {
3997 * Expand the macro: we are placed on the last token of the
3998 * call, so that we can easily split the call from the
3999 * following tokens. We also start by pushing an SMAC_END
4000 * token for the cycle removal.
4002 t = tline;
4003 if (t) {
4004 tline = t->next;
4005 t->next = NULL;
4007 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4008 tt->a.mac = m;
4009 m->in_progress = true;
4010 tline = tt;
4011 for (t = m->expansion; t; t = t->next) {
4012 if (t->type >= TOK_SMAC_PARAM) {
4013 Token *pcopy = tline, **ptail = &pcopy;
4014 Token *ttt, *pt;
4015 int i;
4017 ttt = params[t->type - TOK_SMAC_PARAM];
4018 for (i = paramsize[t->type - TOK_SMAC_PARAM];
4019 --i >= 0;) {
4020 pt = *ptail =
4021 new_Token(tline, ttt->type, ttt->text,
4023 ptail = &pt->next;
4024 ttt = ttt->next;
4026 tline = pcopy;
4027 } else if (t->type == TOK_PREPROC_Q) {
4028 tt = new_Token(tline, TOK_ID, mname, 0);
4029 tline = tt;
4030 } else if (t->type == TOK_PREPROC_QQ) {
4031 tt = new_Token(tline, TOK_ID, m->name, 0);
4032 tline = tt;
4033 } else {
4034 tt = new_Token(tline, t->type, t->text, 0);
4035 tline = tt;
4040 * Having done that, get rid of the macro call, and clean
4041 * up the parameters.
4043 nasm_free(params);
4044 nasm_free(paramsize);
4045 free_tlist(mstart);
4046 expanded = true;
4047 continue; /* main token loop */
4052 if (tline->type == TOK_SMAC_END) {
4053 tline->a.mac->in_progress = false;
4054 tline = delete_Token(tline);
4055 } else {
4056 t = *tail = tline;
4057 tline = tline->next;
4058 t->a.mac = NULL;
4059 t->next = NULL;
4060 tail = &t->next;
4065 * Now scan the entire line and look for successive TOK_IDs that resulted
4066 * after expansion (they can't be produced by tokenize()). The successive
4067 * TOK_IDs should be concatenated.
4068 * Also we look for %+ tokens and concatenate the tokens before and after
4069 * them (without white spaces in between).
4071 if (expanded && paste_tokens(&thead, true)) {
4073 * If we concatenated something, *and* we had previously expanded
4074 * an actual macro, scan the lines again for macros...
4076 tline = thead;
4077 expanded = false;
4078 goto again;
4081 err:
4082 if (org_tline) {
4083 if (thead) {
4084 *org_tline = *thead;
4085 /* since we just gave text to org_line, don't free it */
4086 thead->text = NULL;
4087 delete_Token(thead);
4088 } else {
4089 /* the expression expanded to empty line;
4090 we can't return NULL for some reasons
4091 we just set the line to a single WHITESPACE token. */
4092 memset(org_tline, 0, sizeof(*org_tline));
4093 org_tline->text = NULL;
4094 org_tline->type = TOK_WHITESPACE;
4096 thead = org_tline;
4099 return thead;
4103 * Similar to expand_smacro but used exclusively with macro identifiers
4104 * right before they are fetched in. The reason is that there can be
4105 * identifiers consisting of several subparts. We consider that if there
4106 * are more than one element forming the name, user wants a expansion,
4107 * otherwise it will be left as-is. Example:
4109 * %define %$abc cde
4111 * the identifier %$abc will be left as-is so that the handler for %define
4112 * will suck it and define the corresponding value. Other case:
4114 * %define _%$abc cde
4116 * In this case user wants name to be expanded *before* %define starts
4117 * working, so we'll expand %$abc into something (if it has a value;
4118 * otherwise it will be left as-is) then concatenate all successive
4119 * PP_IDs into one.
4121 static Token *expand_id(Token * tline)
4123 Token *cur, *oldnext = NULL;
4125 if (!tline || !tline->next)
4126 return tline;
4128 cur = tline;
4129 while (cur->next &&
4130 (cur->next->type == TOK_ID ||
4131 cur->next->type == TOK_PREPROC_ID
4132 || cur->next->type == TOK_NUMBER))
4133 cur = cur->next;
4135 /* If identifier consists of just one token, don't expand */
4136 if (cur == tline)
4137 return tline;
4139 if (cur) {
4140 oldnext = cur->next; /* Detach the tail past identifier */
4141 cur->next = NULL; /* so that expand_smacro stops here */
4144 tline = expand_smacro(tline);
4146 if (cur) {
4147 /* expand_smacro possibly changhed tline; re-scan for EOL */
4148 cur = tline;
4149 while (cur && cur->next)
4150 cur = cur->next;
4151 if (cur)
4152 cur->next = oldnext;
4155 return tline;
4159 * Determine whether the given line constitutes a multi-line macro
4160 * call, and return the MMacro structure called if so. Doesn't have
4161 * to check for an initial label - that's taken care of in
4162 * expand_mmacro - but must check numbers of parameters. Guaranteed
4163 * to be called with tline->type == TOK_ID, so the putative macro
4164 * name is easy to find.
4166 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4168 MMacro *head, *m;
4169 Token **params;
4170 int nparam;
4172 head = (MMacro *) hash_findix(&mmacros, tline->text);
4175 * Efficiency: first we see if any macro exists with the given
4176 * name. If not, we can return NULL immediately. _Then_ we
4177 * count the parameters, and then we look further along the
4178 * list if necessary to find the proper MMacro.
4180 for (m = head; m; m = m->next)
4181 if (!mstrcmp(m->name, tline->text, m->casesense))
4182 break;
4183 if (!m)
4184 return NULL;
4187 * OK, we have a potential macro. Count and demarcate the
4188 * parameters.
4190 count_mmac_params(tline->next, &nparam, &params);
4193 * So we know how many parameters we've got. Find the MMacro
4194 * structure that handles this number.
4196 while (m) {
4197 if (m->nparam_min <= nparam
4198 && (m->plus || nparam <= m->nparam_max)) {
4200 * This one is right. Just check if cycle removal
4201 * prohibits us using it before we actually celebrate...
4203 if (m->in_progress > m->max_depth) {
4204 if (m->max_depth > 0) {
4205 error(ERR_WARNING,
4206 "reached maximum recursion depth of %i",
4207 m->max_depth);
4209 nasm_free(params);
4210 return NULL;
4213 * It's right, and we can use it. Add its default
4214 * parameters to the end of our list if necessary.
4216 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4217 params =
4218 nasm_realloc(params,
4219 ((m->nparam_min + m->ndefs +
4220 1) * sizeof(*params)));
4221 while (nparam < m->nparam_min + m->ndefs) {
4222 params[nparam] = m->defaults[nparam - m->nparam_min];
4223 nparam++;
4227 * If we've gone over the maximum parameter count (and
4228 * we're in Plus mode), ignore parameters beyond
4229 * nparam_max.
4231 if (m->plus && nparam > m->nparam_max)
4232 nparam = m->nparam_max;
4234 * Then terminate the parameter list, and leave.
4236 if (!params) { /* need this special case */
4237 params = nasm_malloc(sizeof(*params));
4238 nparam = 0;
4240 params[nparam] = NULL;
4241 *params_array = params;
4242 return m;
4245 * This one wasn't right: look for the next one with the
4246 * same name.
4248 for (m = m->next; m; m = m->next)
4249 if (!mstrcmp(m->name, tline->text, m->casesense))
4250 break;
4254 * After all that, we didn't find one with the right number of
4255 * parameters. Issue a warning, and fail to expand the macro.
4257 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4258 "macro `%s' exists, but not taking %d parameters",
4259 tline->text, nparam);
4260 nasm_free(params);
4261 return NULL;
4266 * Save MMacro invocation specific fields in
4267 * preparation for a recursive macro expansion
4269 static void push_mmacro(MMacro *m)
4271 MMacroInvocation *i;
4273 i = nasm_malloc(sizeof(MMacroInvocation));
4274 i->prev = m->prev;
4275 i->params = m->params;
4276 i->iline = m->iline;
4277 i->nparam = m->nparam;
4278 i->rotate = m->rotate;
4279 i->paramlen = m->paramlen;
4280 i->unique = m->unique;
4281 i->condcnt = m->condcnt;
4282 m->prev = i;
4287 * Restore MMacro invocation specific fields that were
4288 * saved during a previous recursive macro expansion
4290 static void pop_mmacro(MMacro *m)
4292 MMacroInvocation *i;
4294 if (m->prev) {
4295 i = m->prev;
4296 m->prev = i->prev;
4297 m->params = i->params;
4298 m->iline = i->iline;
4299 m->nparam = i->nparam;
4300 m->rotate = i->rotate;
4301 m->paramlen = i->paramlen;
4302 m->unique = i->unique;
4303 m->condcnt = i->condcnt;
4304 nasm_free(i);
4310 * Expand the multi-line macro call made by the given line, if
4311 * there is one to be expanded. If there is, push the expansion on
4312 * istk->expansion and return 1. Otherwise return 0.
4314 static int expand_mmacro(Token * tline)
4316 Token *startline = tline;
4317 Token *label = NULL;
4318 int dont_prepend = 0;
4319 Token **params, *t, *mtok, *tt;
4320 MMacro *m;
4321 Line *l, *ll;
4322 int i, nparam, *paramlen;
4323 const char *mname;
4325 t = tline;
4326 skip_white_(t);
4327 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4328 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4329 return 0;
4330 mtok = t;
4331 m = is_mmacro(t, &params);
4332 if (m) {
4333 mname = t->text;
4334 } else {
4335 Token *last;
4337 * We have an id which isn't a macro call. We'll assume
4338 * it might be a label; we'll also check to see if a
4339 * colon follows it. Then, if there's another id after
4340 * that lot, we'll check it again for macro-hood.
4342 label = last = t;
4343 t = t->next;
4344 if (tok_type_(t, TOK_WHITESPACE))
4345 last = t, t = t->next;
4346 if (tok_is_(t, ":")) {
4347 dont_prepend = 1;
4348 last = t, t = t->next;
4349 if (tok_type_(t, TOK_WHITESPACE))
4350 last = t, t = t->next;
4352 if (!tok_type_(t, TOK_ID) || !(m = is_mmacro(t, &params)))
4353 return 0;
4354 last->next = NULL;
4355 mname = t->text;
4356 tline = t;
4360 * Fix up the parameters: this involves stripping leading and
4361 * trailing whitespace, then stripping braces if they are
4362 * present.
4364 for (nparam = 0; params[nparam]; nparam++) ;
4365 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4367 for (i = 0; params[i]; i++) {
4368 int brace = false;
4369 int comma = (!m->plus || i < nparam - 1);
4371 t = params[i];
4372 skip_white_(t);
4373 if (tok_is_(t, "{"))
4374 t = t->next, brace = true, comma = false;
4375 params[i] = t;
4376 paramlen[i] = 0;
4377 while (t) {
4378 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4379 break; /* ... because we have hit a comma */
4380 if (comma && t->type == TOK_WHITESPACE
4381 && tok_is_(t->next, ","))
4382 break; /* ... or a space then a comma */
4383 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4384 break; /* ... or a brace */
4385 t = t->next;
4386 paramlen[i]++;
4391 * OK, we have a MMacro structure together with a set of
4392 * parameters. We must now go through the expansion and push
4393 * copies of each Line on to istk->expansion. Substitution of
4394 * parameter tokens and macro-local tokens doesn't get done
4395 * until the single-line macro substitution process; this is
4396 * because delaying them allows us to change the semantics
4397 * later through %rotate.
4399 * First, push an end marker on to istk->expansion, mark this
4400 * macro as in progress, and set up its invocation-specific
4401 * variables.
4403 ll = nasm_malloc(sizeof(Line));
4404 ll->next = istk->expansion;
4405 ll->finishes = m;
4406 ll->first = NULL;
4407 istk->expansion = ll;
4410 * Save the previous MMacro expansion in the case of
4411 * macro recursion
4413 if (m->max_depth && m->in_progress)
4414 push_mmacro(m);
4416 m->in_progress ++;
4417 m->params = params;
4418 m->iline = tline;
4419 m->nparam = nparam;
4420 m->rotate = 0;
4421 m->paramlen = paramlen;
4422 m->unique = unique++;
4423 m->lineno = 0;
4424 m->condcnt = 0;
4426 m->next_active = istk->mstk;
4427 istk->mstk = m;
4429 for (l = m->expansion; l; l = l->next) {
4430 Token **tail;
4432 ll = nasm_malloc(sizeof(Line));
4433 ll->finishes = NULL;
4434 ll->next = istk->expansion;
4435 istk->expansion = ll;
4436 tail = &ll->first;
4438 for (t = l->first; t; t = t->next) {
4439 Token *x = t;
4440 switch (t->type) {
4441 case TOK_PREPROC_Q:
4442 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4443 break;
4444 case TOK_PREPROC_QQ:
4445 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4446 break;
4447 case TOK_PREPROC_ID:
4448 if (t->text[1] == '0' && t->text[2] == '0') {
4449 dont_prepend = -1;
4450 x = label;
4451 if (!x)
4452 continue;
4454 /* fall through */
4455 default:
4456 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4457 break;
4459 tail = &tt->next;
4461 *tail = NULL;
4465 * If we had a label, push it on as the first line of
4466 * the macro expansion.
4468 if (label) {
4469 if (dont_prepend < 0)
4470 free_tlist(startline);
4471 else {
4472 ll = nasm_malloc(sizeof(Line));
4473 ll->finishes = NULL;
4474 ll->next = istk->expansion;
4475 istk->expansion = ll;
4476 ll->first = startline;
4477 if (!dont_prepend) {
4478 while (label->next)
4479 label = label->next;
4480 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4485 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4487 return 1;
4490 /* The function that actually does the error reporting */
4491 static void verror(int severity, const char *fmt, va_list arg)
4493 char buff[1024];
4495 vsnprintf(buff, sizeof(buff), fmt, arg);
4497 if (istk && istk->mstk && istk->mstk->name)
4498 nasm_error(severity, "(%s:%d) %s", istk->mstk->name,
4499 istk->mstk->lineno, buff);
4500 else
4501 nasm_error(severity, "%s", buff);
4505 * Since preprocessor always operate only on the line that didn't
4506 * arrived yet, we should always use ERR_OFFBY1.
4508 static void error(int severity, const char *fmt, ...)
4510 va_list arg;
4512 /* If we're in a dead branch of IF or something like it, ignore the error */
4513 if (istk && istk->conds && !emitting(istk->conds->state))
4514 return;
4516 va_start(arg, fmt);
4517 verror(severity, fmt, arg);
4518 va_end(arg);
4522 * Because %else etc are evaluated in the state context
4523 * of the previous branch, errors might get lost with error():
4524 * %if 0 ... %else trailing garbage ... %endif
4525 * So %else etc should report errors with this function.
4527 static void error_precond(int severity, const char *fmt, ...)
4529 va_list arg;
4531 /* Only ignore the error if it's really in a dead branch */
4532 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4533 return;
4535 va_start(arg, fmt);
4536 verror(severity, fmt, arg);
4537 va_end(arg);
4540 static void
4541 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
4543 Token *t;
4545 cstk = NULL;
4546 istk = nasm_malloc(sizeof(Include));
4547 istk->next = NULL;
4548 istk->conds = NULL;
4549 istk->expansion = NULL;
4550 istk->mstk = NULL;
4551 istk->fp = fopen(file, "r");
4552 istk->fname = NULL;
4553 src_set_fname(nasm_strdup(file));
4554 src_set_linnum(0);
4555 istk->lineinc = 1;
4556 if (!istk->fp)
4557 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4558 file);
4559 defining = NULL;
4560 nested_mac_count = 0;
4561 nested_rep_count = 0;
4562 init_macros();
4563 unique = 0;
4564 if (tasm_compatible_mode) {
4565 stdmacpos = nasm_stdmac;
4566 } else {
4567 stdmacpos = nasm_stdmac_after_tasm;
4569 any_extrastdmac = extrastdmac && *extrastdmac;
4570 do_predef = true;
4571 list = listgen;
4574 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4575 * The caller, however, will also pass in 3 for preprocess-only so
4576 * we can set __PASS__ accordingly.
4578 pass = apass > 2 ? 2 : apass;
4580 dephead = deptail = deplist;
4581 if (deplist) {
4582 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4583 sl->next = NULL;
4584 strcpy(sl->str, file);
4585 *deptail = sl;
4586 deptail = &sl->next;
4590 * Define the __PASS__ macro. This is defined here unlike
4591 * all the other builtins, because it is special -- it varies between
4592 * passes.
4594 t = nasm_malloc(sizeof(*t));
4595 t->next = NULL;
4596 make_tok_num(t, apass);
4597 t->a.mac = NULL;
4598 define_smacro(NULL, "__PASS__", true, 0, t);
4601 static char *pp_getline(void)
4603 char *line;
4604 Token *tline;
4606 while (1) {
4608 * Fetch a tokenized line, either from the macro-expansion
4609 * buffer or from the input file.
4611 tline = NULL;
4612 while (istk->expansion && istk->expansion->finishes) {
4613 Line *l = istk->expansion;
4614 if (!l->finishes->name && l->finishes->in_progress > 1) {
4615 Line *ll;
4618 * This is a macro-end marker for a macro with no
4619 * name, which means it's not really a macro at all
4620 * but a %rep block, and the `in_progress' field is
4621 * more than 1, meaning that we still need to
4622 * repeat. (1 means the natural last repetition; 0
4623 * means termination by %exitrep.) We have
4624 * therefore expanded up to the %endrep, and must
4625 * push the whole block on to the expansion buffer
4626 * again. We don't bother to remove the macro-end
4627 * marker: we'd only have to generate another one
4628 * if we did.
4630 l->finishes->in_progress--;
4631 for (l = l->finishes->expansion; l; l = l->next) {
4632 Token *t, *tt, **tail;
4634 ll = nasm_malloc(sizeof(Line));
4635 ll->next = istk->expansion;
4636 ll->finishes = NULL;
4637 ll->first = NULL;
4638 tail = &ll->first;
4640 for (t = l->first; t; t = t->next) {
4641 if (t->text || t->type == TOK_WHITESPACE) {
4642 tt = *tail =
4643 new_Token(NULL, t->type, t->text, 0);
4644 tail = &tt->next;
4648 istk->expansion = ll;
4650 } else {
4652 * Check whether a `%rep' was started and not ended
4653 * within this macro expansion. This can happen and
4654 * should be detected. It's a fatal error because
4655 * I'm too confused to work out how to recover
4656 * sensibly from it.
4658 if (defining) {
4659 if (defining->name)
4660 error(ERR_PANIC,
4661 "defining with name in expansion");
4662 else if (istk->mstk->name)
4663 error(ERR_FATAL,
4664 "`%%rep' without `%%endrep' within"
4665 " expansion of macro `%s'",
4666 istk->mstk->name);
4670 * FIXME: investigate the relationship at this point between
4671 * istk->mstk and l->finishes
4674 MMacro *m = istk->mstk;
4675 istk->mstk = m->next_active;
4676 if (m->name) {
4678 * This was a real macro call, not a %rep, and
4679 * therefore the parameter information needs to
4680 * be freed.
4682 if (m->prev) {
4683 pop_mmacro(m);
4684 l->finishes->in_progress --;
4685 } else {
4686 nasm_free(m->params);
4687 free_tlist(m->iline);
4688 nasm_free(m->paramlen);
4689 l->finishes->in_progress = 0;
4691 } else
4692 free_mmacro(m);
4694 istk->expansion = l->next;
4695 nasm_free(l);
4696 list->downlevel(LIST_MACRO);
4699 while (1) { /* until we get a line we can use */
4701 if (istk->expansion) { /* from a macro expansion */
4702 char *p;
4703 Line *l = istk->expansion;
4704 if (istk->mstk)
4705 istk->mstk->lineno++;
4706 tline = l->first;
4707 istk->expansion = l->next;
4708 nasm_free(l);
4709 p = detoken(tline, false);
4710 list->line(LIST_MACRO, p);
4711 nasm_free(p);
4712 break;
4714 line = read_line();
4715 if (line) { /* from the current input file */
4716 line = prepreproc(line);
4717 tline = tokenize(line);
4718 nasm_free(line);
4719 break;
4722 * The current file has ended; work down the istk
4725 Include *i = istk;
4726 fclose(i->fp);
4727 if (i->conds)
4728 error(ERR_FATAL,
4729 "expected `%%endif' before end of file");
4730 /* only set line and file name if there's a next node */
4731 if (i->next) {
4732 src_set_linnum(i->lineno);
4733 nasm_free(src_set_fname(i->fname));
4735 istk = i->next;
4736 list->downlevel(LIST_INCLUDE);
4737 nasm_free(i);
4738 if (!istk)
4739 return NULL;
4740 if (istk->expansion && istk->expansion->finishes)
4741 break;
4746 * We must expand MMacro parameters and MMacro-local labels
4747 * _before_ we plunge into directive processing, to cope
4748 * with things like `%define something %1' such as STRUC
4749 * uses. Unless we're _defining_ a MMacro, in which case
4750 * those tokens should be left alone to go into the
4751 * definition; and unless we're in a non-emitting
4752 * condition, in which case we don't want to meddle with
4753 * anything.
4755 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4756 && !(istk->mstk && !istk->mstk->in_progress)) {
4757 tline = expand_mmac_params(tline);
4761 * Check the line to see if it's a preprocessor directive.
4763 if (do_directive(tline) == DIRECTIVE_FOUND) {
4764 continue;
4765 } else if (defining) {
4767 * We're defining a multi-line macro. We emit nothing
4768 * at all, and just
4769 * shove the tokenized line on to the macro definition.
4771 Line *l = nasm_malloc(sizeof(Line));
4772 l->next = defining->expansion;
4773 l->first = tline;
4774 l->finishes = NULL;
4775 defining->expansion = l;
4776 continue;
4777 } else if (istk->conds && !emitting(istk->conds->state)) {
4779 * We're in a non-emitting branch of a condition block.
4780 * Emit nothing at all, not even a blank line: when we
4781 * emerge from the condition we'll give a line-number
4782 * directive so we keep our place correctly.
4784 free_tlist(tline);
4785 continue;
4786 } else if (istk->mstk && !istk->mstk->in_progress) {
4788 * We're in a %rep block which has been terminated, so
4789 * we're walking through to the %endrep without
4790 * emitting anything. Emit nothing at all, not even a
4791 * blank line: when we emerge from the %rep block we'll
4792 * give a line-number directive so we keep our place
4793 * correctly.
4795 free_tlist(tline);
4796 continue;
4797 } else {
4798 tline = expand_smacro(tline);
4799 if (!expand_mmacro(tline)) {
4801 * De-tokenize the line again, and emit it.
4803 line = detoken(tline, true);
4804 free_tlist(tline);
4805 break;
4806 } else {
4807 continue; /* expand_mmacro calls free_tlist */
4812 return line;
4815 static void pp_cleanup(int pass)
4817 if (defining) {
4818 if (defining->name) {
4819 error(ERR_NONFATAL,
4820 "end of file while still defining macro `%s'",
4821 defining->name);
4822 } else {
4823 error(ERR_NONFATAL, "end of file while still in %%rep");
4826 free_mmacro(defining);
4827 defining = NULL;
4829 while (cstk)
4830 ctx_pop();
4831 free_macros();
4832 while (istk) {
4833 Include *i = istk;
4834 istk = istk->next;
4835 fclose(i->fp);
4836 nasm_free(i->fname);
4837 nasm_free(i);
4839 while (cstk)
4840 ctx_pop();
4841 nasm_free(src_set_fname(NULL));
4842 if (pass == 0) {
4843 IncPath *i;
4844 free_llist(predef);
4845 delete_Blocks();
4846 while ((i = ipath)) {
4847 ipath = i->next;
4848 if (i->path)
4849 nasm_free(i->path);
4850 nasm_free(i);
4855 void pp_include_path(char *path)
4857 IncPath *i;
4859 i = nasm_malloc(sizeof(IncPath));
4860 i->path = path ? nasm_strdup(path) : NULL;
4861 i->next = NULL;
4863 if (ipath) {
4864 IncPath *j = ipath;
4865 while (j->next)
4866 j = j->next;
4867 j->next = i;
4868 } else {
4869 ipath = i;
4873 void pp_pre_include(char *fname)
4875 Token *inc, *space, *name;
4876 Line *l;
4878 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4879 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4880 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4882 l = nasm_malloc(sizeof(Line));
4883 l->next = predef;
4884 l->first = inc;
4885 l->finishes = NULL;
4886 predef = l;
4889 void pp_pre_define(char *definition)
4891 Token *def, *space;
4892 Line *l;
4893 char *equals;
4895 equals = strchr(definition, '=');
4896 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4897 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4898 if (equals)
4899 *equals = ' ';
4900 space->next = tokenize(definition);
4901 if (equals)
4902 *equals = '=';
4904 l = nasm_malloc(sizeof(Line));
4905 l->next = predef;
4906 l->first = def;
4907 l->finishes = NULL;
4908 predef = l;
4911 void pp_pre_undefine(char *definition)
4913 Token *def, *space;
4914 Line *l;
4916 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4917 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4918 space->next = tokenize(definition);
4920 l = nasm_malloc(sizeof(Line));
4921 l->next = predef;
4922 l->first = def;
4923 l->finishes = NULL;
4924 predef = l;
4928 * Added by Keith Kanios:
4930 * This function is used to assist with "runtime" preprocessor
4931 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4933 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4934 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4937 void pp_runtime(char *definition)
4939 Token *def;
4941 def = tokenize(definition);
4942 if (do_directive(def) == NO_DIRECTIVE_FOUND)
4943 free_tlist(def);
4947 void pp_extra_stdmac(macros_t *macros)
4949 extrastdmac = macros;
4952 static void make_tok_num(Token * tok, int64_t val)
4954 char numbuf[20];
4955 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4956 tok->text = nasm_strdup(numbuf);
4957 tok->type = TOK_NUMBER;
4960 Preproc nasmpp = {
4961 pp_reset,
4962 pp_getline,
4963 pp_cleanup