version: changed version to 2.10rc1 (unofficial/tentative)
[nasm.git] / preproc.c
blob30b0ca2ec3371ef314f665c33fd24c29bcfa393f
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 ExpDef ExpDef;
86 typedef struct ExpInv ExpInv;
87 typedef struct Context Context;
88 typedef struct Token Token;
89 typedef struct Blocks Blocks;
90 typedef struct Line Line;
91 typedef struct Include Include;
92 typedef struct Cond Cond;
93 typedef struct IncPath IncPath;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
107 struct SMacro {
108 SMacro *next;
109 char *name;
110 bool casesense;
111 bool in_progress;
112 unsigned int nparam;
113 Token *expansion;
117 * The context stack is composed of a linked list of these.
119 struct Context {
120 Context *next;
121 char *name;
122 struct hash_table localmac;
123 uint32_t number;
127 * This is the internal form which we break input lines up into.
128 * Typically stored in linked lists.
130 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
131 * necessarily used as-is, but is intended to denote the number of
132 * the substituted parameter. So in the definition
134 * %define a(x,y) ( (x) & ~(y) )
136 * the token representing `x' will have its type changed to
137 * TOK_SMAC_PARAM, but the one representing `y' will be
138 * TOK_SMAC_PARAM+1.
140 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
141 * which doesn't need quotes around it. Used in the pre-include
142 * mechanism as an alternative to trying to find a sensible type of
143 * quote to use on the filename we were passed.
145 enum pp_token_type {
146 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
147 TOK_PREPROC_ID, TOK_STRING,
148 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
149 TOK_INTERNAL_STRING,
150 TOK_PREPROC_Q, TOK_PREPROC_QQ,
151 TOK_PASTE, /* %+ */
152 TOK_INDIRECT, /* %[...] */
153 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
154 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
157 struct Token {
158 Token *next;
159 char *text;
160 union {
161 SMacro *mac; /* associated macro for TOK_SMAC_END */
162 size_t len; /* scratch length field */
163 } a; /* Auxiliary data */
164 enum pp_token_type type;
168 * Expansion definitions are stored as a linked list of
169 * these, which is essentially a container to allow several linked
170 * lists of Tokens.
172 * Note that in this module, linked lists are treated as stacks
173 * wherever possible. For this reason, Lines are _pushed_ on to the
174 * `last' field in ExpDef structures, so that the linked list,
175 * if walked, would emit the expansion lines in the proper order.
177 struct Line {
178 Line *next;
179 Token *first;
183 * Expansion Types
185 enum pp_exp_type {
186 EXP_NONE = 0, EXP_PREDEF,
187 EXP_MMACRO, EXP_REP,
188 EXP_IF, EXP_WHILE,
189 EXP_COMMENT, EXP_FINAL,
190 EXP_MAX = INT_MAX /* Keep compiler from reducing the range */
194 * Store the definition of an expansion, in which is any
195 * preprocessor directive that has an ending pair.
197 * This design allows for arbitrary expansion/recursion depth,
198 * upto the DEADMAN_LIMIT.
200 * The `next' field is used for storing ExpDef in hash tables; the
201 * `prev' field is for the global `expansions` linked-list.
203 struct ExpDef {
204 ExpDef *prev; /* previous definition */
205 ExpDef *next; /* next in hash table */
206 enum pp_exp_type type; /* expansion type */
207 char *name;
208 int nparam_min, nparam_max;
209 bool casesense;
210 bool plus; /* is the last parameter greedy? */
211 bool nolist; /* is this expansion listing-inhibited? */
212 Token *dlist; /* all defaults as one list */
213 Token **defaults; /* parameter default pointers */
214 int ndefs; /* number of default parameters */
216 Line *label;
217 Line *line;
218 Line *last;
220 uint32_t def_depth; /* current number of definition pairs deep */
221 uint32_t cur_depth; /* current number of expansions */
222 uint32_t max_depth; /* maximum number of expansions allowed */
224 int state; /* condition state */
225 bool ignoring; /* ignoring definition lines */
229 * Store the invocation of an expansion.
231 * The `prev' field is for the `istk->expansion` linked-list.
233 * When an expansion is being expanded, `params', `iline', `nparam',
234 * `paramlen', `rotate' and `unique' are local to the invocation.
236 struct ExpInv {
237 ExpInv *prev; /* previous invocation */
238 enum pp_exp_type type; /* expansion type */
239 ExpDef *def; /* pointer to expansion definition */
240 Line *label; /* pointer to label */
241 char *label_text; /* pointer to label text */
242 Line *current; /* pointer to current line in invocation */
244 Token **params; /* actual parameters */
245 Token *iline; /* invocation line */
246 unsigned int nparam, rotate;
247 int *paramlen;
249 uint64_t unique;
250 bool emitting;
251 int lineno; /* current line number in expansion */
255 * To handle an arbitrary level of file inclusion, we maintain a
256 * stack (ie linked list) of these things.
258 struct Include {
259 Include *next;
260 FILE *fp;
261 Cond *conds;
262 ExpInv *expansion;
263 char *fname;
264 int lineno, lineinc;
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 enum {
286 * These states are for use just after %if or %elif: IF_TRUE
287 * means the condition has evaluated to truth so we are
288 * currently emitting, whereas IF_FALSE means we are not
289 * currently emitting but will start doing so if a %else comes
290 * up. In these states, all directives are admissible: %elif,
291 * %else and %endif. (And of course %if.)
293 COND_IF_TRUE, COND_IF_FALSE,
295 * These states come up after a %else: ELSE_TRUE means we're
296 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
297 * any %elif or %else will cause an error.
299 COND_ELSE_TRUE, COND_ELSE_FALSE,
301 * These states mean that we're not emitting now, and also that
302 * nothing until %endif will be emitted at all. COND_DONE is
303 * used when we've had our moment of emission
304 * and have now started seeing %elifs. COND_NEVER is used when
305 * the condition construct in question is contained within a
306 * non-emitting branch of a larger condition construct,
307 * or if there is an error.
309 COND_DONE, COND_NEVER
311 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
314 * These defines are used as the possible return values for do_directive
316 #define NO_DIRECTIVE_FOUND 0
317 #define DIRECTIVE_FOUND 1
320 * This define sets the upper limit for smacro and expansions
322 #define DEADMAN_LIMIT (1 << 20)
325 * Condition codes. Note that we use c_ prefix not C_ because C_ is
326 * used in nasm.h for the "real" condition codes. At _this_ level,
327 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
328 * ones, so we need a different enum...
330 static const char * const conditions[] = {
331 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
332 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
333 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
335 enum pp_conds {
336 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
337 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
338 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
339 c_none = -1
341 static const enum pp_conds inverse_ccs[] = {
342 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
343 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,
344 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
347 /* For TASM compatibility we need to be able to recognise TASM compatible
348 * conditional compilation directives. Using the NASM pre-processor does
349 * not work, so we look for them specifically from the following list and
350 * then jam in the equivalent NASM directive into the input stream.
353 enum {
354 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
355 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
358 static const char * const tasm_directives[] = {
359 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
360 "ifndef", "include", "local"
363 static int StackSize = 4;
364 static char *StackPointer = "ebp";
365 static int ArgOffset = 8;
366 static int LocalOffset = 0;
368 static Context *cstk;
369 static Include *istk;
370 static IncPath *ipath = NULL;
372 static int pass; /* HACK: pass 0 = generate dependencies only */
373 static StrList **dephead, **deptail; /* Dependency list */
375 static uint64_t unique; /* unique identifier numbers */
377 static Line *predef = NULL;
378 static bool do_predef;
380 static ListGen *list;
383 * The current set of expansion definitions we have defined.
385 static struct hash_table expdefs;
388 * The current set of single-line macros we have defined.
390 static struct hash_table smacros;
393 * Linked List of all active expansion definitions
395 struct ExpDef *expansions = NULL;
398 * The expansion we are currently defining
400 static ExpDef *defining = NULL;
402 static uint64_t nested_mac_count;
403 static uint64_t nested_rep_count;
406 * Linked-list of lines to preprocess, prior to cleanup
408 static Line *finals = NULL;
409 static bool in_final = false;
412 * The number of macro parameters to allocate space for at a time.
414 #define PARAM_DELTA 16
417 * The standard macro set: defined in macros.c in the array nasm_stdmac.
418 * This gives our position in the macro set, when we're processing it.
420 static macros_t *stdmacpos;
423 * The extra standard macros that come from the object format, if
424 * any.
426 static macros_t *extrastdmac = NULL;
427 static bool any_extrastdmac;
430 * Tokens are allocated in blocks to improve speed
432 #define TOKEN_BLOCKSIZE 4096
433 static Token *freeTokens = NULL;
434 struct Blocks {
435 Blocks *next;
436 void *chunk;
439 static Blocks blocks = { NULL, NULL };
442 * Forward declarations.
444 static Token *expand_mmac_params(Token * tline);
445 static Token *expand_smacro(Token * tline);
446 static Token *expand_id(Token * tline);
447 static Context *get_ctx(const char *name, const char **namep,
448 bool all_contexts);
449 static void make_tok_num(Token * tok, int64_t val);
450 static void error(int severity, const char *fmt, ...);
451 static void error_precond(int severity, const char *fmt, ...);
452 static void *new_Block(size_t size);
453 static void delete_Blocks(void);
454 static Token *new_Token(Token * next, enum pp_token_type type,
455 const char *text, int txtlen);
456 static Token *copy_Token(Token * tline);
457 static Token *delete_Token(Token * t);
458 static Line *new_Line(void);
459 static ExpDef *new_ExpDef(void);
460 static ExpInv *new_ExpInv(void);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * nasm_unquote with error if the string contains NUL characters.
472 * If the string contains NUL characters, issue an error and return
473 * the C len, i.e. truncate at the NUL.
475 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
477 size_t len = nasm_unquote(qstr, NULL);
478 size_t clen = strlen(qstr);
480 if (len != clen)
481 error(ERR_NONFATAL, "NUL character in `%s' directive",
482 pp_directives[directive]);
484 return clen;
488 * Handle TASM specific directives, which do not contain a % in
489 * front of them. We do it here because I could not find any other
490 * place to do it for the moment, and it is a hack (ideally it would
491 * be nice to be able to use the NASM pre-processor to do it).
493 static char *check_tasm_directive(char *line)
495 int32_t i, j, k, m, len;
496 char *p, *q, *oldline, oldchar;
498 p = nasm_skip_spaces(line);
500 /* Binary search for the directive name */
501 i = -1;
502 j = ARRAY_SIZE(tasm_directives);
503 q = nasm_skip_word(p);
504 len = q - p;
505 if (len) {
506 oldchar = p[len];
507 p[len] = 0;
508 while (j - i > 1) {
509 k = (j + i) / 2;
510 m = nasm_stricmp(p, tasm_directives[k]);
511 if (m == 0) {
512 /* We have found a directive, so jam a % in front of it
513 * so that NASM will then recognise it as one if it's own.
515 p[len] = oldchar;
516 len = strlen(p);
517 oldline = line;
518 line = nasm_malloc(len + 2);
519 line[0] = '%';
520 if (k == TM_IFDIFI) {
522 * NASM does not recognise IFDIFI, so we convert
523 * it to %if 0. This is not used in NASM
524 * compatible code, but does need to parse for the
525 * TASM macro package.
527 strcpy(line + 1, "if 0");
528 } else {
529 memcpy(line + 1, p, len + 1);
531 nasm_free(oldline);
532 return line;
533 } else if (m < 0) {
534 j = k;
535 } else
536 i = k;
538 p[len] = oldchar;
540 return line;
544 * The pre-preprocessing stage... This function translates line
545 * number indications as they emerge from GNU cpp (`# lineno "file"
546 * flags') into NASM preprocessor line number indications (`%line
547 * lineno file').
549 static char *prepreproc(char *line)
551 int lineno, fnlen;
552 char *fname, *oldline;
554 if (line[0] == '#' && line[1] == ' ') {
555 oldline = line;
556 fname = oldline + 2;
557 lineno = atoi(fname);
558 fname += strspn(fname, "0123456789 ");
559 if (*fname == '"')
560 fname++;
561 fnlen = strcspn(fname, "\"");
562 line = nasm_malloc(20 + fnlen);
563 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
564 nasm_free(oldline);
566 if (tasm_compatible_mode)
567 return check_tasm_directive(line);
568 return line;
572 * Free a linked list of tokens.
574 static void free_tlist(Token * list)
576 while (list)
577 list = delete_Token(list);
581 * Free a linked list of lines.
583 static void free_llist(Line * list)
585 Line *l, *tmp;
586 list_for_each_safe(l, tmp, list) {
587 free_tlist(l->first);
588 nasm_free(l);
593 * Free an ExpDef
595 static void free_expdef(ExpDef * ed)
597 nasm_free(ed->name);
598 free_tlist(ed->dlist);
599 nasm_free(ed->defaults);
600 free_llist(ed->line);
601 nasm_free(ed);
605 * Free all currently defined macros, and free the hash tables
607 static void free_smacro_table(struct hash_table *smt)
609 SMacro *s, *tmp;
610 const char *key;
611 struct hash_tbl_node *it = NULL;
613 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
614 nasm_free((void *)key);
615 list_for_each_safe(s, tmp, s) {
616 nasm_free(s->name);
617 free_tlist(s->expansion);
618 nasm_free(s);
621 hash_free(smt);
624 static void free_expdef_table(struct hash_table *edt)
626 ExpDef *ed, *tmp;
627 const char *key;
628 struct hash_tbl_node *it = NULL;
630 it = NULL;
631 while ((ed = hash_iterate(edt, &it, &key)) != NULL) {
632 nasm_free((void *)key);
633 list_for_each_safe(ed ,tmp, ed)
634 free_expdef(ed);
636 hash_free(edt);
639 static void free_macros(void)
641 free_smacro_table(&smacros);
642 free_expdef_table(&expdefs);
646 * Initialize the hash tables
648 static void init_macros(void)
650 hash_init(&smacros, HASH_LARGE);
651 hash_init(&expdefs, HASH_LARGE);
655 * Pop the context stack.
657 static void ctx_pop(void)
659 Context *c = cstk;
661 cstk = cstk->next;
662 free_smacro_table(&c->localmac);
663 nasm_free(c->name);
664 nasm_free(c);
668 * Search for a key in the hash index; adding it if necessary
669 * (in which case we initialize the data pointer to NULL.)
671 static void **
672 hash_findi_add(struct hash_table *hash, const char *str)
674 struct hash_insert hi;
675 void **r;
676 char *strx;
678 r = hash_findi(hash, str, &hi);
679 if (r)
680 return r;
682 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
683 return hash_add(&hi, strx, NULL);
687 * Like hash_findi, but returns the data element rather than a pointer
688 * to it. Used only when not adding a new element, hence no third
689 * argument.
691 static void *
692 hash_findix(struct hash_table *hash, const char *str)
694 void **p;
696 p = hash_findi(hash, str, NULL);
697 return p ? *p : NULL;
701 * read line from standard macros set,
702 * if there no more left -- return NULL
704 static char *line_from_stdmac(void)
706 unsigned char c;
707 const unsigned char *p = stdmacpos;
708 char *line, *q;
709 size_t len = 0;
711 if (!stdmacpos)
712 return NULL;
714 while ((c = *p++)) {
715 if (c >= 0x80)
716 len += pp_directives_len[c - 0x80] + 1;
717 else
718 len++;
721 line = nasm_malloc(len + 1);
722 q = line;
723 while ((c = *stdmacpos++)) {
724 if (c >= 0x80) {
725 memcpy(q, pp_directives[c - 0x80], pp_directives_len[c - 0x80]);
726 q += pp_directives_len[c - 0x80];
727 *q++ = ' ';
728 } else {
729 *q++ = c;
732 stdmacpos = p;
733 *q = '\0';
735 if (!*stdmacpos) {
736 /* This was the last of the standard macro chain... */
737 stdmacpos = NULL;
738 if (any_extrastdmac) {
739 stdmacpos = extrastdmac;
740 any_extrastdmac = false;
741 } else if (do_predef) {
742 ExpInv *ei;
743 Line *pd, *l;
744 Token *head, **tail, *t;
747 * Nasty hack: here we push the contents of
748 * `predef' on to the top-level expansion stack,
749 * since this is the most convenient way to
750 * implement the pre-include and pre-define
751 * features.
753 list_for_each(pd, predef) {
754 head = NULL;
755 tail = &head;
756 list_for_each(t, pd->first) {
757 *tail = new_Token(NULL, t->type, t->text, 0);
758 tail = &(*tail)->next;
761 l = new_Line();
762 l->first = head;
763 ei = new_ExpInv();
764 ei->type = EXP_PREDEF;
765 ei->current = l;
766 ei->emitting = true;
767 ei->prev = istk->expansion;
768 istk->expansion = ei;
770 do_predef = false;
774 return line;
777 #define BUF_DELTA 512
779 * Read a line from the top file in istk, handling multiple CR/LFs
780 * at the end of the line read, and handling spurious ^Zs. Will
781 * return lines from the standard macro set if this has not already
782 * been done.
784 static char *read_line(void)
786 char *buffer, *p, *q;
787 int bufsize, continued_count;
790 * standart macros set (predefined) goes first
792 p = line_from_stdmac();
793 if (p)
794 return p;
797 * regular read from a file
799 bufsize = BUF_DELTA;
800 buffer = nasm_malloc(BUF_DELTA);
801 p = buffer;
802 continued_count = 0;
803 while (1) {
804 q = fgets(p, bufsize - (p - buffer), istk->fp);
805 if (!q)
806 break;
807 p += strlen(p);
808 if (p > buffer && p[-1] == '\n') {
810 * Convert backslash-CRLF line continuation sequences into
811 * nothing at all (for DOS and Windows)
813 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
814 p -= 3;
815 *p = 0;
816 continued_count++;
819 * Also convert backslash-LF line continuation sequences into
820 * nothing at all (for Unix)
822 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
823 p -= 2;
824 *p = 0;
825 continued_count++;
826 } else {
827 break;
830 if (p - buffer > bufsize - 10) {
831 int32_t offset = p - buffer;
832 bufsize += BUF_DELTA;
833 buffer = nasm_realloc(buffer, bufsize);
834 p = buffer + offset; /* prevent stale-pointer problems */
838 if (!q && p == buffer) {
839 nasm_free(buffer);
840 return NULL;
843 src_set_linnum(src_get_linnum() + istk->lineinc +
844 (continued_count * istk->lineinc));
847 * Play safe: remove CRs as well as LFs, if any of either are
848 * present at the end of the line.
850 while (--p >= buffer && (*p == '\n' || *p == '\r'))
851 *p = '\0';
854 * Handle spurious ^Z, which may be inserted into source files
855 * by some file transfer utilities.
857 buffer[strcspn(buffer, "\032")] = '\0';
859 list->line(LIST_READ, buffer);
861 return buffer;
865 * Tokenize a line of text. This is a very simple process since we
866 * don't need to parse the value out of e.g. numeric tokens: we
867 * simply split one string into many.
869 static Token *tokenize(char *line)
871 char c, *p = line;
872 enum pp_token_type type;
873 Token *list = NULL;
874 Token *t, **tail = &list;
876 while (*line) {
877 p = line;
878 if (*p == '%') {
879 p++;
880 if (*p == '+' && !nasm_isdigit(p[1])) {
881 p++;
882 type = TOK_PASTE;
883 } else if (nasm_isdigit(*p) ||
884 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
885 do {
886 p++;
888 while (nasm_isdigit(*p));
889 type = TOK_PREPROC_ID;
890 } else if (*p == '{') {
891 p++;
892 while (*p && *p != '}') {
893 p[-1] = *p;
894 p++;
896 p[-1] = '\0';
897 if (*p)
898 p++;
899 type = TOK_PREPROC_ID;
900 } else if (*p == '[') {
901 int lvl = 1;
902 line += 2; /* Skip the leading %[ */
903 p++;
904 while (lvl && (c = *p++)) {
905 switch (c) {
906 case ']':
907 lvl--;
908 break;
909 case '%':
910 if (*p == '[')
911 lvl++;
912 break;
913 case '\'':
914 case '\"':
915 case '`':
916 p = nasm_skip_string(p - 1) + 1;
917 break;
918 default:
919 break;
922 p--;
923 if (*p)
924 *p++ = '\0';
925 if (lvl)
926 error(ERR_NONFATAL, "unterminated %[ construct");
927 type = TOK_INDIRECT;
928 } else if (*p == '?') {
929 type = TOK_PREPROC_Q; /* %? */
930 p++;
931 if (*p == '?') {
932 type = TOK_PREPROC_QQ; /* %?? */
933 p++;
935 } else if (*p == '!') {
936 type = TOK_PREPROC_ID;
937 p++;
938 if (isidchar(*p)) {
939 do {
940 p++;
942 while (isidchar(*p));
943 } else if (*p == '\'' || *p == '\"' || *p == '`') {
944 p = nasm_skip_string(p);
945 if (*p)
946 p++;
947 else
948 error(ERR_NONFATAL|ERR_PASS1, "unterminated %! string");
949 } else {
950 /* %! without string or identifier */
951 type = TOK_OTHER; /* Legacy behavior... */
953 } else if (isidchar(*p) ||
954 ((*p == '!' || *p == '%' || *p == '$') &&
955 isidchar(p[1]))) {
956 do {
957 p++;
959 while (isidchar(*p));
960 type = TOK_PREPROC_ID;
961 } else {
962 type = TOK_OTHER;
963 if (*p == '%')
964 p++;
966 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
967 type = TOK_ID;
968 p++;
969 while (*p && isidchar(*p))
970 p++;
971 } else if (*p == '\'' || *p == '"' || *p == '`') {
973 * A string token.
975 type = TOK_STRING;
976 p = nasm_skip_string(p);
978 if (*p) {
979 p++;
980 } else {
981 error(ERR_WARNING|ERR_PASS1, "unterminated string");
982 /* Handling unterminated strings by UNV */
983 /* type = -1; */
985 } else if (p[0] == '$' && p[1] == '$') {
986 type = TOK_OTHER; /* TOKEN_BASE */
987 p += 2;
988 } else if (isnumstart(*p)) {
989 bool is_hex = false;
990 bool is_float = false;
991 bool has_e = false;
992 char c, *r;
995 * A numeric token.
998 if (*p == '$') {
999 p++;
1000 is_hex = true;
1003 for (;;) {
1004 c = *p++;
1006 if (!is_hex && (c == 'e' || c == 'E')) {
1007 has_e = true;
1008 if (*p == '+' || *p == '-') {
1010 * e can only be followed by +/- if it is either a
1011 * prefixed hex number or a floating-point number
1013 p++;
1014 is_float = true;
1016 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
1017 is_hex = true;
1018 } else if (c == 'P' || c == 'p') {
1019 is_float = true;
1020 if (*p == '+' || *p == '-')
1021 p++;
1022 } else if (isnumchar(c) || c == '_')
1023 ; /* just advance */
1024 else if (c == '.') {
1026 * we need to deal with consequences of the legacy
1027 * parser, like "1.nolist" being two tokens
1028 * (TOK_NUMBER, TOK_ID) here; at least give it
1029 * a shot for now. In the future, we probably need
1030 * a flex-based scanner with proper pattern matching
1031 * to do it as well as it can be done. Nothing in
1032 * the world is going to help the person who wants
1033 * 0x123.p16 interpreted as two tokens, though.
1035 r = p;
1036 while (*r == '_')
1037 r++;
1039 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
1040 (!is_hex && (*r == 'e' || *r == 'E')) ||
1041 (*r == 'p' || *r == 'P')) {
1042 p = r;
1043 is_float = true;
1044 } else
1045 break; /* Terminate the token */
1046 } else
1047 break;
1049 p--; /* Point to first character beyond number */
1051 if (p == line+1 && *line == '$') {
1052 type = TOK_OTHER; /* TOKEN_HERE */
1053 } else {
1054 if (has_e && !is_hex) {
1055 /* 1e13 is floating-point, but 1e13h is not */
1056 is_float = true;
1059 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1061 } else if (nasm_isspace(*p)) {
1062 type = TOK_WHITESPACE;
1063 p = nasm_skip_spaces(p);
1065 * Whitespace just before end-of-line is discarded by
1066 * pretending it's a comment; whitespace just before a
1067 * comment gets lumped into the comment.
1069 if (!*p || *p == ';') {
1070 type = TOK_COMMENT;
1071 while (*p)
1072 p++;
1074 } else if (*p == ';') {
1075 type = TOK_COMMENT;
1076 while (*p)
1077 p++;
1078 } else {
1080 * Anything else is an operator of some kind. We check
1081 * for all the double-character operators (>>, <<, //,
1082 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1083 * else is a single-character operator.
1085 type = TOK_OTHER;
1086 if ((p[0] == '>' && p[1] == '>') ||
1087 (p[0] == '<' && p[1] == '<') ||
1088 (p[0] == '/' && p[1] == '/') ||
1089 (p[0] == '<' && p[1] == '=') ||
1090 (p[0] == '>' && p[1] == '=') ||
1091 (p[0] == '=' && p[1] == '=') ||
1092 (p[0] == '!' && p[1] == '=') ||
1093 (p[0] == '<' && p[1] == '>') ||
1094 (p[0] == '&' && p[1] == '&') ||
1095 (p[0] == '|' && p[1] == '|') ||
1096 (p[0] == '^' && p[1] == '^')) {
1097 p++;
1099 p++;
1102 /* Handling unterminated string by UNV */
1103 /*if (type == -1)
1105 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1106 t->text[p-line] = *line;
1107 tail = &t->next;
1109 else */
1110 if (type != TOK_COMMENT) {
1111 *tail = t = new_Token(NULL, type, line, p - line);
1112 tail = &t->next;
1114 line = p;
1116 return list;
1120 * this function allocates a new managed block of memory and
1121 * returns a pointer to the block. The managed blocks are
1122 * deleted only all at once by the delete_Blocks function.
1124 static void *new_Block(size_t size)
1126 Blocks *b = &blocks;
1128 /* first, get to the end of the linked list */
1129 while (b->next)
1130 b = b->next;
1131 /* now allocate the requested chunk */
1132 b->chunk = nasm_malloc(size);
1134 /* now allocate a new block for the next request */
1135 b->next = nasm_malloc(sizeof(Blocks));
1136 /* and initialize the contents of the new block */
1137 b->next->next = NULL;
1138 b->next->chunk = NULL;
1139 return b->chunk;
1143 * this function deletes all managed blocks of memory
1145 static void delete_Blocks(void)
1147 Blocks *a, *b = &blocks;
1150 * keep in mind that the first block, pointed to by blocks
1151 * is a static and not dynamically allocated, so we don't
1152 * free it.
1154 while (b) {
1155 if (b->chunk)
1156 nasm_free(b->chunk);
1157 a = b;
1158 b = b->next;
1159 if (a != &blocks)
1160 nasm_free(a);
1165 * this function creates a new Token and passes a pointer to it
1166 * back to the caller. It sets the type and text elements, and
1167 * also the a.mac and next elements to NULL.
1169 static Token *new_Token(Token * next, enum pp_token_type type,
1170 const char *text, int txtlen)
1172 Token *t;
1173 int i;
1175 if (!freeTokens) {
1176 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1177 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1178 freeTokens[i].next = &freeTokens[i + 1];
1179 freeTokens[i].next = NULL;
1181 t = freeTokens;
1182 freeTokens = t->next;
1183 t->next = next;
1184 t->a.mac = NULL;
1185 t->type = type;
1186 if (type == TOK_WHITESPACE || !text) {
1187 t->text = NULL;
1188 } else {
1189 if (txtlen == 0)
1190 txtlen = strlen(text);
1191 t->text = nasm_malloc(txtlen+1);
1192 memcpy(t->text, text, txtlen);
1193 t->text[txtlen] = '\0';
1195 return t;
1198 static Token *copy_Token(Token * tline)
1200 Token *t, *tt, *first = NULL, *prev = NULL;
1201 int i;
1202 for (tt = tline; tt != NULL; tt = tt->next) {
1203 if (!freeTokens) {
1204 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1205 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1206 freeTokens[i].next = &freeTokens[i + 1];
1207 freeTokens[i].next = NULL;
1209 t = freeTokens;
1210 freeTokens = t->next;
1211 t->next = NULL;
1212 t->text = ((tt->text != NULL) ? strdup(tt->text) : NULL);
1213 t->a.mac = tt->a.mac;
1214 t->a.len = tt->a.len;
1215 t->type = tt->type;
1216 if (prev != NULL) {
1217 prev->next = t;
1218 } else {
1219 first = t;
1221 prev = t;
1223 return first;
1226 static Token *delete_Token(Token * t)
1228 Token *next = t->next;
1229 nasm_free(t->text);
1230 t->next = freeTokens;
1231 freeTokens = t;
1232 return next;
1236 * Convert a line of tokens back into text.
1237 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1238 * will be transformed into ..@ctxnum.xxx
1240 static char *detoken(Token * tlist, bool expand_locals)
1242 Token *t;
1243 char *line, *p;
1244 const char *q;
1245 int len = 0;
1247 list_for_each(t, tlist) {
1248 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1249 char *v;
1250 char *q = t->text;
1252 v = t->text + 2;
1253 if (*v == '\'' || *v == '\"' || *v == '`') {
1254 size_t len = nasm_unquote(v, NULL);
1255 size_t clen = strlen(v);
1257 if (len != clen) {
1258 error(ERR_NONFATAL | ERR_PASS1,
1259 "NUL character in %! string");
1260 v = NULL;
1264 if (v) {
1265 char *p = getenv(v);
1266 if (!p) {
1267 error(ERR_NONFATAL | ERR_PASS1,
1268 "nonexistent environment variable `%s'", v);
1269 p = "";
1271 t->text = nasm_strdup(p);
1273 nasm_free(q);
1276 /* Expand local macros here and not during preprocessing */
1277 if (expand_locals &&
1278 t->type == TOK_PREPROC_ID && t->text &&
1279 t->text[0] == '%' && t->text[1] == '$') {
1280 const char *q;
1281 char *p;
1282 Context *ctx = get_ctx(t->text, &q, false);
1283 if (ctx) {
1284 char buffer[40];
1285 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1286 p = nasm_strcat(buffer, q);
1287 nasm_free(t->text);
1288 t->text = p;
1291 if (t->type == TOK_WHITESPACE)
1292 len++;
1293 else if (t->text)
1294 len += strlen(t->text);
1297 p = line = nasm_malloc(len + 1);
1299 list_for_each(t, tlist) {
1300 if (t->type == TOK_WHITESPACE) {
1301 *p++ = ' ';
1302 } else if (t->text) {
1303 q = t->text;
1304 while (*q)
1305 *p++ = *q++;
1308 *p = '\0';
1310 return line;
1314 * Initialize a new Line
1316 static Line *new_Line(void)
1318 Line *l = nasm_malloc(sizeof(Line));
1319 l->next = NULL;
1320 l->first = NULL;
1321 return l;
1326 * Initialize a new Expansion Definition
1328 static ExpDef *new_ExpDef(void)
1330 ExpDef *ed = nasm_malloc(sizeof(ExpDef));
1331 ed->prev = NULL;
1332 ed->next = NULL;
1333 ed->type = EXP_NONE;
1334 ed->name = NULL;
1335 ed->nparam_min = 0;
1336 ed->nparam_max = 0;
1337 ed->casesense = true;
1338 ed->plus = false;
1339 ed->label = NULL;
1340 ed->line = NULL;
1341 ed->last = NULL;
1342 ed->dlist = NULL;
1343 ed->defaults = NULL;
1344 ed->ndefs = 0;
1345 ed->state = COND_NEVER;
1346 ed->nolist = false;
1347 ed->def_depth = 0;
1348 ed->cur_depth = 0;
1349 ed->max_depth = 0;
1350 ed->ignoring = false;
1351 return ed;
1356 * Initialize a new Expansion Instance
1358 static ExpInv *new_ExpInv(void)
1360 unique ++;
1361 ExpInv *ei = nasm_malloc(sizeof(ExpInv));
1362 ei->prev = NULL;
1363 ei->type = EXP_NONE;
1364 ei->def = NULL;
1365 ei->label = NULL;
1366 ei->label_text = NULL;
1367 ei->current = NULL;
1368 ei->params = NULL;
1369 ei->iline = NULL;
1370 ei->nparam = 0;
1371 ei->rotate = 0;
1372 ei->paramlen = NULL;
1373 ei->unique = unique;
1374 ei->emitting = false;
1375 ei->lineno = 0;
1376 return ei;
1380 * A scanner, suitable for use by the expression evaluator, which
1381 * operates on a line of Tokens. Expects a pointer to a pointer to
1382 * the first token in the line to be passed in as its private_data
1383 * field.
1385 * FIX: This really needs to be unified with stdscan.
1387 static int ppscan(void *private_data, struct tokenval *tokval)
1389 Token **tlineptr = private_data;
1390 Token *tline;
1391 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1393 do {
1394 tline = *tlineptr;
1395 *tlineptr = tline ? tline->next : NULL;
1396 } while (tline && (tline->type == TOK_WHITESPACE ||
1397 tline->type == TOK_COMMENT));
1399 if (!tline)
1400 return tokval->t_type = TOKEN_EOS;
1402 tokval->t_charptr = tline->text;
1404 if (tline->text[0] == '$' && !tline->text[1])
1405 return tokval->t_type = TOKEN_HERE;
1406 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1407 return tokval->t_type = TOKEN_BASE;
1409 if (tline->type == TOK_ID) {
1410 p = tokval->t_charptr = tline->text;
1411 if (p[0] == '$') {
1412 tokval->t_charptr++;
1413 return tokval->t_type = TOKEN_ID;
1416 for (r = p, s = ourcopy; *r; r++) {
1417 if (r >= p+MAX_KEYWORD)
1418 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1419 *s++ = nasm_tolower(*r);
1421 *s = '\0';
1422 /* right, so we have an identifier sitting in temp storage. now,
1423 * is it actually a register or instruction name, or what? */
1424 return nasm_token_hash(ourcopy, tokval);
1427 if (tline->type == TOK_NUMBER) {
1428 bool rn_error;
1429 tokval->t_integer = readnum(tline->text, &rn_error);
1430 tokval->t_charptr = tline->text;
1431 if (rn_error)
1432 return tokval->t_type = TOKEN_ERRNUM;
1433 else
1434 return tokval->t_type = TOKEN_NUM;
1437 if (tline->type == TOK_FLOAT) {
1438 return tokval->t_type = TOKEN_FLOAT;
1441 if (tline->type == TOK_STRING) {
1442 char bq, *ep;
1444 bq = tline->text[0];
1445 tokval->t_charptr = tline->text;
1446 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1448 if (ep[0] != bq || ep[1] != '\0')
1449 return tokval->t_type = TOKEN_ERRSTR;
1450 else
1451 return tokval->t_type = TOKEN_STR;
1454 if (tline->type == TOK_OTHER) {
1455 if (!strcmp(tline->text, "<<"))
1456 return tokval->t_type = TOKEN_SHL;
1457 if (!strcmp(tline->text, ">>"))
1458 return tokval->t_type = TOKEN_SHR;
1459 if (!strcmp(tline->text, "//"))
1460 return tokval->t_type = TOKEN_SDIV;
1461 if (!strcmp(tline->text, "%%"))
1462 return tokval->t_type = TOKEN_SMOD;
1463 if (!strcmp(tline->text, "=="))
1464 return tokval->t_type = TOKEN_EQ;
1465 if (!strcmp(tline->text, "<>"))
1466 return tokval->t_type = TOKEN_NE;
1467 if (!strcmp(tline->text, "!="))
1468 return tokval->t_type = TOKEN_NE;
1469 if (!strcmp(tline->text, "<="))
1470 return tokval->t_type = TOKEN_LE;
1471 if (!strcmp(tline->text, ">="))
1472 return tokval->t_type = TOKEN_GE;
1473 if (!strcmp(tline->text, "&&"))
1474 return tokval->t_type = TOKEN_DBL_AND;
1475 if (!strcmp(tline->text, "^^"))
1476 return tokval->t_type = TOKEN_DBL_XOR;
1477 if (!strcmp(tline->text, "||"))
1478 return tokval->t_type = TOKEN_DBL_OR;
1482 * We have no other options: just return the first character of
1483 * the token text.
1485 return tokval->t_type = tline->text[0];
1489 * Compare a string to the name of an existing macro; this is a
1490 * simple wrapper which calls either strcmp or nasm_stricmp
1491 * depending on the value of the `casesense' parameter.
1493 static int mstrcmp(const char *p, const char *q, bool casesense)
1495 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1499 * Compare a string to the name of an existing macro; this is a
1500 * simple wrapper which calls either strcmp or nasm_stricmp
1501 * depending on the value of the `casesense' parameter.
1503 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1505 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1509 * Return the Context structure associated with a %$ token. Return
1510 * NULL, having _already_ reported an error condition, if the
1511 * context stack isn't deep enough for the supplied number of $
1512 * signs.
1513 * If all_contexts == true, contexts that enclose current are
1514 * also scanned for such smacro, until it is found; if not -
1515 * only the context that directly results from the number of $'s
1516 * in variable's name.
1518 * If "namep" is non-NULL, set it to the pointer to the macro name
1519 * tail, i.e. the part beyond %$...
1521 static Context *get_ctx(const char *name, const char **namep,
1522 bool all_contexts)
1524 Context *ctx;
1525 SMacro *m;
1526 int i;
1528 if (namep)
1529 *namep = name;
1531 if (!name || name[0] != '%' || name[1] != '$')
1532 return NULL;
1534 if (!cstk) {
1535 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1536 return NULL;
1539 name += 2;
1540 ctx = cstk;
1541 i = 0;
1542 while (ctx && *name == '$') {
1543 name++;
1544 i++;
1545 ctx = ctx->next;
1547 if (!ctx) {
1548 error(ERR_NONFATAL, "`%s': context stack is only"
1549 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1550 return NULL;
1553 if (namep)
1554 *namep = name;
1556 if (!all_contexts)
1557 return ctx;
1559 do {
1560 /* Search for this smacro in found context */
1561 m = hash_findix(&ctx->localmac, name);
1562 while (m) {
1563 if (!mstrcmp(m->name, name, m->casesense))
1564 return ctx;
1565 m = m->next;
1567 ctx = ctx->next;
1569 while (ctx);
1570 return NULL;
1574 * Check to see if a file is already in a string list
1576 static bool in_list(const StrList *list, const char *str)
1578 while (list) {
1579 if (!strcmp(list->str, str))
1580 return true;
1581 list = list->next;
1583 return false;
1587 * Open an include file. This routine must always return a valid
1588 * file pointer if it returns - it's responsible for throwing an
1589 * ERR_FATAL and bombing out completely if not. It should also try
1590 * the include path one by one until it finds the file or reaches
1591 * the end of the path.
1593 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1594 bool missing_ok)
1596 FILE *fp;
1597 char *prefix = "";
1598 IncPath *ip = ipath;
1599 int len = strlen(file);
1600 size_t prefix_len = 0;
1601 StrList *sl;
1603 while (1) {
1604 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1605 memcpy(sl->str, prefix, prefix_len);
1606 memcpy(sl->str+prefix_len, file, len+1);
1607 fp = fopen(sl->str, "r");
1608 if (fp && dhead && !in_list(*dhead, sl->str)) {
1609 sl->next = NULL;
1610 **dtail = sl;
1611 *dtail = &sl->next;
1612 } else {
1613 nasm_free(sl);
1615 if (fp)
1616 return fp;
1617 if (!ip) {
1618 if (!missing_ok)
1619 break;
1620 prefix = NULL;
1621 } else {
1622 prefix = ip->path;
1623 ip = ip->next;
1625 if (prefix) {
1626 prefix_len = strlen(prefix);
1627 } else {
1628 /* -MG given and file not found */
1629 if (dhead && !in_list(*dhead, file)) {
1630 sl = nasm_malloc(len+1+sizeof sl->next);
1631 sl->next = NULL;
1632 strcpy(sl->str, file);
1633 **dtail = sl;
1634 *dtail = &sl->next;
1636 return NULL;
1640 error(ERR_FATAL, "unable to open include file `%s'", file);
1641 return NULL;
1645 * Determine if we should warn on defining a single-line macro of
1646 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1647 * return true if _any_ single-line macro of that name is defined.
1648 * Otherwise, will return true if a single-line macro with either
1649 * `nparam' or no parameters is defined.
1651 * If a macro with precisely the right number of parameters is
1652 * defined, or nparam is -1, the address of the definition structure
1653 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1654 * is NULL, no action will be taken regarding its contents, and no
1655 * error will occur.
1657 * Note that this is also called with nparam zero to resolve
1658 * `ifdef'.
1660 * If you already know which context macro belongs to, you can pass
1661 * the context pointer as first parameter; if you won't but name begins
1662 * with %$ the context will be automatically computed. If all_contexts
1663 * is true, macro will be searched in outer contexts as well.
1665 static bool
1666 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1667 bool nocase)
1669 struct hash_table *smtbl;
1670 SMacro *m;
1672 if (ctx) {
1673 smtbl = &ctx->localmac;
1674 } else if (name[0] == '%' && name[1] == '$') {
1675 if (cstk)
1676 ctx = get_ctx(name, &name, false);
1677 if (!ctx)
1678 return false; /* got to return _something_ */
1679 smtbl = &ctx->localmac;
1680 } else {
1681 smtbl = &smacros;
1683 m = (SMacro *) hash_findix(smtbl, name);
1685 while (m) {
1686 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1687 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1688 if (defn) {
1689 if (nparam == (int) m->nparam || nparam == -1)
1690 *defn = m;
1691 else
1692 *defn = NULL;
1694 return true;
1696 m = m->next;
1699 return false;
1703 * Count and mark off the parameters in a multi-line macro call.
1704 * This is called both from within the multi-line macro expansion
1705 * code, and also to mark off the default parameters when provided
1706 * in a %macro definition line.
1708 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1710 int paramsize, brace;
1712 *nparam = paramsize = 0;
1713 *params = NULL;
1714 while (t) {
1715 /* +1: we need space for the final NULL */
1716 if (*nparam+1 >= paramsize) {
1717 paramsize += PARAM_DELTA;
1718 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1720 skip_white_(t);
1721 brace = false;
1722 if (tok_is_(t, "{"))
1723 brace = true;
1724 (*params)[(*nparam)++] = t;
1725 while (tok_isnt_(t, brace ? "}" : ","))
1726 t = t->next;
1727 if (t) { /* got a comma/brace */
1728 t = t->next;
1729 if (brace) {
1731 * Now we've found the closing brace, look further
1732 * for the comma.
1734 skip_white_(t);
1735 if (tok_isnt_(t, ",")) {
1736 error(ERR_NONFATAL,
1737 "braces do not enclose all of macro parameter");
1738 while (tok_isnt_(t, ","))
1739 t = t->next;
1741 if (t)
1742 t = t->next; /* eat the comma */
1749 * Determine whether one of the various `if' conditions is true or
1750 * not.
1752 * We must free the tline we get passed.
1754 static bool if_condition(Token * tline, enum preproc_token ct)
1756 enum pp_conditional i = PP_COND(ct);
1757 bool j;
1758 Token *t, *tt, **tptr, *origline;
1759 struct tokenval tokval;
1760 expr *evalresult;
1761 enum pp_token_type needtype;
1762 char *p;
1764 origline = tline;
1766 switch (i) {
1767 case PPC_IFCTX:
1768 j = false; /* have we matched yet? */
1769 while (true) {
1770 skip_white_(tline);
1771 if (!tline)
1772 break;
1773 if (tline->type != TOK_ID) {
1774 error(ERR_NONFATAL,
1775 "`%s' expects context identifiers", pp_directives[ct]);
1776 free_tlist(origline);
1777 return -1;
1779 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1780 j = true;
1781 tline = tline->next;
1783 break;
1785 case PPC_IFDEF:
1786 j = false; /* have we matched yet? */
1787 while (tline) {
1788 skip_white_(tline);
1789 if (!tline || (tline->type != TOK_ID &&
1790 (tline->type != TOK_PREPROC_ID ||
1791 tline->text[1] != '$'))) {
1792 error(ERR_NONFATAL,
1793 "`%s' expects macro identifiers", pp_directives[ct]);
1794 goto fail;
1796 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1797 j = true;
1798 tline = tline->next;
1800 break;
1802 case PPC_IFENV:
1803 tline = expand_smacro(tline);
1804 j = false; /* have we matched yet? */
1805 while (tline) {
1806 skip_white_(tline);
1807 if (!tline || (tline->type != TOK_ID &&
1808 tline->type != TOK_STRING &&
1809 (tline->type != TOK_PREPROC_ID ||
1810 tline->text[1] != '!'))) {
1811 error(ERR_NONFATAL,
1812 "`%s' expects environment variable names",
1813 pp_directives[ct]);
1814 goto fail;
1816 p = tline->text;
1817 if (tline->type == TOK_PREPROC_ID)
1818 p += 2; /* Skip leading %! */
1819 if (*p == '\'' || *p == '\"' || *p == '`')
1820 nasm_unquote_cstr(p, ct);
1821 if (getenv(p))
1822 j = true;
1823 tline = tline->next;
1825 break;
1827 case PPC_IFIDN:
1828 case PPC_IFIDNI:
1829 tline = expand_smacro(tline);
1830 t = tt = tline;
1831 while (tok_isnt_(tt, ","))
1832 tt = tt->next;
1833 if (!tt) {
1834 error(ERR_NONFATAL,
1835 "`%s' expects two comma-separated arguments",
1836 pp_directives[ct]);
1837 goto fail;
1839 tt = tt->next;
1840 j = true; /* assume equality unless proved not */
1841 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1842 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1843 error(ERR_NONFATAL, "`%s': more than one comma on line",
1844 pp_directives[ct]);
1845 goto fail;
1847 if (t->type == TOK_WHITESPACE) {
1848 t = t->next;
1849 continue;
1851 if (tt->type == TOK_WHITESPACE) {
1852 tt = tt->next;
1853 continue;
1855 if (tt->type != t->type) {
1856 j = false; /* found mismatching tokens */
1857 break;
1859 /* When comparing strings, need to unquote them first */
1860 if (t->type == TOK_STRING) {
1861 size_t l1 = nasm_unquote(t->text, NULL);
1862 size_t l2 = nasm_unquote(tt->text, NULL);
1864 if (l1 != l2) {
1865 j = false;
1866 break;
1868 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1869 j = false;
1870 break;
1872 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1873 j = false; /* found mismatching tokens */
1874 break;
1877 t = t->next;
1878 tt = tt->next;
1880 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1881 j = false; /* trailing gunk on one end or other */
1882 break;
1884 case PPC_IFMACRO:
1886 bool found = false;
1887 ExpDef searching, *ed;
1889 skip_white_(tline);
1890 tline = expand_id(tline);
1891 if (!tok_type_(tline, TOK_ID)) {
1892 error(ERR_NONFATAL,
1893 "`%s' expects a macro name", pp_directives[ct]);
1894 goto fail;
1896 searching.name = nasm_strdup(tline->text);
1897 searching.casesense = true;
1898 searching.plus = false;
1899 searching.nolist = false;
1900 //searching.in_progress = 0;
1901 searching.max_depth = 0;
1902 //searching.rep_nest = NULL;
1903 searching.nparam_min = 0;
1904 searching.nparam_max = INT_MAX;
1905 tline = expand_smacro(tline->next);
1906 skip_white_(tline);
1907 if (!tline) {
1908 } else if (!tok_type_(tline, TOK_NUMBER)) {
1909 error(ERR_NONFATAL,
1910 "`%s' expects a parameter count or nothing",
1911 pp_directives[ct]);
1912 } else {
1913 searching.nparam_min = searching.nparam_max =
1914 readnum(tline->text, &j);
1915 if (j)
1916 error(ERR_NONFATAL,
1917 "unable to parse parameter count `%s'",
1918 tline->text);
1920 if (tline && tok_is_(tline->next, "-")) {
1921 tline = tline->next->next;
1922 if (tok_is_(tline, "*"))
1923 searching.nparam_max = INT_MAX;
1924 else if (!tok_type_(tline, TOK_NUMBER))
1925 error(ERR_NONFATAL,
1926 "`%s' expects a parameter count after `-'",
1927 pp_directives[ct]);
1928 else {
1929 searching.nparam_max = readnum(tline->text, &j);
1930 if (j)
1931 error(ERR_NONFATAL,
1932 "unable to parse parameter count `%s'",
1933 tline->text);
1934 if (searching.nparam_min > searching.nparam_max)
1935 error(ERR_NONFATAL,
1936 "minimum parameter count exceeds maximum");
1939 if (tline && tok_is_(tline->next, "+")) {
1940 tline = tline->next;
1941 searching.plus = true;
1943 ed = (ExpDef *) hash_findix(&expdefs, searching.name);
1944 while (ed != NULL) {
1945 if (!strcmp(ed->name, searching.name) &&
1946 (ed->nparam_min <= searching.nparam_max
1947 || searching.plus)
1948 && (searching.nparam_min <= ed->nparam_max
1949 || ed->plus)) {
1950 found = true;
1951 break;
1953 ed = ed->next;
1955 if (tline && tline->next)
1956 error(ERR_WARNING|ERR_PASS1,
1957 "trailing garbage after %%ifmacro ignored");
1958 nasm_free(searching.name);
1959 j = found;
1960 break;
1963 case PPC_IFID:
1964 needtype = TOK_ID;
1965 goto iftype;
1966 case PPC_IFNUM:
1967 needtype = TOK_NUMBER;
1968 goto iftype;
1969 case PPC_IFSTR:
1970 needtype = TOK_STRING;
1971 goto iftype;
1973 iftype:
1974 t = tline = expand_smacro(tline);
1976 while (tok_type_(t, TOK_WHITESPACE) ||
1977 (needtype == TOK_NUMBER &&
1978 tok_type_(t, TOK_OTHER) &&
1979 (t->text[0] == '-' || t->text[0] == '+') &&
1980 !t->text[1]))
1981 t = t->next;
1983 j = tok_type_(t, needtype);
1984 break;
1986 case PPC_IFTOKEN:
1987 t = tline = expand_smacro(tline);
1988 while (tok_type_(t, TOK_WHITESPACE))
1989 t = t->next;
1991 j = false;
1992 if (t) {
1993 t = t->next; /* Skip the actual token */
1994 while (tok_type_(t, TOK_WHITESPACE))
1995 t = t->next;
1996 j = !t; /* Should be nothing left */
1998 break;
2000 case PPC_IFEMPTY:
2001 t = tline = expand_smacro(tline);
2002 while (tok_type_(t, TOK_WHITESPACE))
2003 t = t->next;
2005 j = !t; /* Should be empty */
2006 break;
2008 case PPC_IF:
2009 t = tline = expand_smacro(tline);
2010 tptr = &t;
2011 tokval.t_type = TOKEN_INVALID;
2012 evalresult = evaluate(ppscan, tptr, &tokval,
2013 NULL, pass | CRITICAL, error, NULL);
2014 if (!evalresult)
2015 return -1;
2016 if (tokval.t_type)
2017 error(ERR_WARNING|ERR_PASS1,
2018 "trailing garbage after expression ignored");
2019 if (!is_simple(evalresult)) {
2020 error(ERR_NONFATAL,
2021 "non-constant value given to `%s'", pp_directives[ct]);
2022 goto fail;
2024 j = reloc_value(evalresult) != 0;
2025 break;
2027 default:
2028 error(ERR_FATAL,
2029 "preprocessor directive `%s' not yet implemented",
2030 pp_directives[ct]);
2031 goto fail;
2034 free_tlist(origline);
2035 return j ^ PP_NEGATIVE(ct);
2037 fail:
2038 free_tlist(origline);
2039 return -1;
2043 * Common code for defining an smacro
2045 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
2046 int nparam, Token *expansion)
2048 SMacro *smac, **smhead;
2049 struct hash_table *smtbl;
2051 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
2052 if (!smac) {
2053 error(ERR_WARNING|ERR_PASS1,
2054 "single-line macro `%s' defined both with and"
2055 " without parameters", mname);
2057 * Some instances of the old code considered this a failure,
2058 * some others didn't. What is the right thing to do here?
2060 free_tlist(expansion);
2061 return false; /* Failure */
2062 } else {
2064 * We're redefining, so we have to take over an
2065 * existing SMacro structure. This means freeing
2066 * what was already in it.
2068 nasm_free(smac->name);
2069 free_tlist(smac->expansion);
2071 } else {
2072 smtbl = ctx ? &ctx->localmac : &smacros;
2073 smhead = (SMacro **) hash_findi_add(smtbl, mname);
2074 smac = nasm_malloc(sizeof(SMacro));
2075 smac->next = *smhead;
2076 *smhead = smac;
2078 smac->name = nasm_strdup(mname);
2079 smac->casesense = casesense;
2080 smac->nparam = nparam;
2081 smac->expansion = expansion;
2082 smac->in_progress = false;
2083 return true; /* Success */
2087 * Undefine an smacro
2089 static void undef_smacro(Context *ctx, const char *mname)
2091 SMacro **smhead, *s, **sp;
2092 struct hash_table *smtbl;
2094 smtbl = ctx ? &ctx->localmac : &smacros;
2095 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
2097 if (smhead) {
2099 * We now have a macro name... go hunt for it.
2101 sp = smhead;
2102 while ((s = *sp) != NULL) {
2103 if (!mstrcmp(s->name, mname, s->casesense)) {
2104 *sp = s->next;
2105 nasm_free(s->name);
2106 free_tlist(s->expansion);
2107 nasm_free(s);
2108 } else {
2109 sp = &s->next;
2116 * Parse a mmacro specification.
2118 static bool parse_mmacro_spec(Token *tline, ExpDef *def, const char *directive)
2120 bool err;
2122 tline = tline->next;
2123 skip_white_(tline);
2124 tline = expand_id(tline);
2125 if (!tok_type_(tline, TOK_ID)) {
2126 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
2127 return false;
2130 def->name = nasm_strdup(tline->text);
2131 def->plus = false;
2132 def->nolist = false;
2133 // def->in_progress = 0;
2134 // def->rep_nest = NULL;
2135 def->nparam_min = 0;
2136 def->nparam_max = 0;
2138 tline = expand_smacro(tline->next);
2139 skip_white_(tline);
2140 if (!tok_type_(tline, TOK_NUMBER)) {
2141 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
2142 } else {
2143 def->nparam_min = def->nparam_max =
2144 readnum(tline->text, &err);
2145 if (err)
2146 error(ERR_NONFATAL,
2147 "unable to parse parameter count `%s'", tline->text);
2149 if (tline && tok_is_(tline->next, "-")) {
2150 tline = tline->next->next;
2151 if (tok_is_(tline, "*")) {
2152 def->nparam_max = INT_MAX;
2153 } else if (!tok_type_(tline, TOK_NUMBER)) {
2154 error(ERR_NONFATAL,
2155 "`%s' expects a parameter count after `-'", directive);
2156 } else {
2157 def->nparam_max = readnum(tline->text, &err);
2158 if (err) {
2159 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
2160 tline->text);
2162 if (def->nparam_min > def->nparam_max) {
2163 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
2167 if (tline && tok_is_(tline->next, "+")) {
2168 tline = tline->next;
2169 def->plus = true;
2171 if (tline && tok_type_(tline->next, TOK_ID) &&
2172 !nasm_stricmp(tline->next->text, ".nolist")) {
2173 tline = tline->next;
2174 def->nolist = true;
2178 * Handle default parameters.
2180 if (tline && tline->next) {
2181 def->dlist = tline->next;
2182 tline->next = NULL;
2183 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
2184 } else {
2185 def->dlist = NULL;
2186 def->defaults = NULL;
2188 def->line = NULL;
2190 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2191 !def->plus)
2192 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2193 "too many default macro parameters");
2195 return true;
2200 * Decode a size directive
2202 static int parse_size(const char *str) {
2203 static const char *size_names[] =
2204 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2205 static const int sizes[] =
2206 { 0, 1, 4, 16, 8, 10, 2, 32 };
2208 return sizes[bsii(str, size_names, ARRAY_SIZE(size_names))+1];
2212 * find and process preprocessor directive in passed line
2213 * Find out if a line contains a preprocessor directive, and deal
2214 * with it if so.
2216 * If a directive _is_ found, it is the responsibility of this routine
2217 * (and not the caller) to free_tlist() the line.
2219 * @param tline a pointer to the current tokeninzed line linked list
2220 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2223 static int do_directive(Token * tline)
2225 enum preproc_token i;
2226 int j;
2227 bool err;
2228 int nparam;
2229 bool nolist;
2230 bool casesense;
2231 int k, m;
2232 int offset;
2233 char *p, *pp;
2234 const char *mname;
2235 Include *inc;
2236 Context *ctx;
2237 Line *l;
2238 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2239 struct tokenval tokval;
2240 expr *evalresult;
2241 ExpDef *ed, *eed, **edhead;
2242 ExpInv *ei, *eei;
2243 int64_t count;
2244 size_t len;
2245 int severity;
2247 origline = tline;
2249 skip_white_(tline);
2250 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2251 (tline->text[1] == '%' || tline->text[1] == '$'
2252 || tline->text[1] == '!'))
2253 return NO_DIRECTIVE_FOUND;
2255 i = pp_token_hash(tline->text);
2257 switch (i) {
2258 case PP_INVALID:
2259 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2260 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2261 tline->text);
2262 return NO_DIRECTIVE_FOUND; /* didn't get it */
2264 case PP_STACKSIZE:
2265 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2266 /* Directive to tell NASM what the default stack size is. The
2267 * default is for a 16-bit stack, and this can be overriden with
2268 * %stacksize large.
2270 tline = tline->next;
2271 if (tline && tline->type == TOK_WHITESPACE)
2272 tline = tline->next;
2273 if (!tline || tline->type != TOK_ID) {
2274 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2275 free_tlist(origline);
2276 return DIRECTIVE_FOUND;
2278 if (nasm_stricmp(tline->text, "flat") == 0) {
2279 /* All subsequent ARG directives are for a 32-bit stack */
2280 StackSize = 4;
2281 StackPointer = "ebp";
2282 ArgOffset = 8;
2283 LocalOffset = 0;
2284 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2285 /* All subsequent ARG directives are for a 64-bit stack */
2286 StackSize = 8;
2287 StackPointer = "rbp";
2288 ArgOffset = 16;
2289 LocalOffset = 0;
2290 } else if (nasm_stricmp(tline->text, "large") == 0) {
2291 /* All subsequent ARG directives are for a 16-bit stack,
2292 * far function call.
2294 StackSize = 2;
2295 StackPointer = "bp";
2296 ArgOffset = 4;
2297 LocalOffset = 0;
2298 } else if (nasm_stricmp(tline->text, "small") == 0) {
2299 /* All subsequent ARG directives are for a 16-bit stack,
2300 * far function call. We don't support near functions.
2302 StackSize = 2;
2303 StackPointer = "bp";
2304 ArgOffset = 6;
2305 LocalOffset = 0;
2306 } else {
2307 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2308 free_tlist(origline);
2309 return DIRECTIVE_FOUND;
2311 free_tlist(origline);
2312 return DIRECTIVE_FOUND;
2314 case PP_ARG:
2315 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2316 /* TASM like ARG directive to define arguments to functions, in
2317 * the following form:
2319 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2321 offset = ArgOffset;
2322 do {
2323 char *arg, directive[256];
2324 int size = StackSize;
2326 /* Find the argument name */
2327 tline = tline->next;
2328 if (tline && tline->type == TOK_WHITESPACE)
2329 tline = tline->next;
2330 if (!tline || tline->type != TOK_ID) {
2331 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2332 free_tlist(origline);
2333 return DIRECTIVE_FOUND;
2335 arg = tline->text;
2337 /* Find the argument size type */
2338 tline = tline->next;
2339 if (!tline || tline->type != TOK_OTHER
2340 || tline->text[0] != ':') {
2341 error(ERR_NONFATAL,
2342 "Syntax error processing `%%arg' directive");
2343 free_tlist(origline);
2344 return DIRECTIVE_FOUND;
2346 tline = tline->next;
2347 if (!tline || tline->type != TOK_ID) {
2348 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2349 free_tlist(origline);
2350 return DIRECTIVE_FOUND;
2353 /* Allow macro expansion of type parameter */
2354 tt = tokenize(tline->text);
2355 tt = expand_smacro(tt);
2356 size = parse_size(tt->text);
2357 if (!size) {
2358 error(ERR_NONFATAL,
2359 "Invalid size type for `%%arg' missing directive");
2360 free_tlist(tt);
2361 free_tlist(origline);
2362 return DIRECTIVE_FOUND;
2364 free_tlist(tt);
2366 /* Round up to even stack slots */
2367 size = ALIGN(size, StackSize);
2369 /* Now define the macro for the argument */
2370 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2371 arg, StackPointer, offset);
2372 do_directive(tokenize(directive));
2373 offset += size;
2375 /* Move to the next argument in the list */
2376 tline = tline->next;
2377 if (tline && tline->type == TOK_WHITESPACE)
2378 tline = tline->next;
2379 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2380 ArgOffset = offset;
2381 free_tlist(origline);
2382 return DIRECTIVE_FOUND;
2384 case PP_LOCAL:
2385 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2386 /* TASM like LOCAL directive to define local variables for a
2387 * function, in the following form:
2389 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2391 * The '= LocalSize' at the end is ignored by NASM, but is
2392 * required by TASM to define the local parameter size (and used
2393 * by the TASM macro package).
2395 offset = LocalOffset;
2396 do {
2397 char *local, directive[256];
2398 int size = StackSize;
2400 /* Find the argument name */
2401 tline = tline->next;
2402 if (tline && tline->type == TOK_WHITESPACE)
2403 tline = tline->next;
2404 if (!tline || tline->type != TOK_ID) {
2405 error(ERR_NONFATAL,
2406 "`%%local' missing argument parameter");
2407 free_tlist(origline);
2408 return DIRECTIVE_FOUND;
2410 local = tline->text;
2412 /* Find the argument size type */
2413 tline = tline->next;
2414 if (!tline || tline->type != TOK_OTHER
2415 || tline->text[0] != ':') {
2416 error(ERR_NONFATAL,
2417 "Syntax error processing `%%local' directive");
2418 free_tlist(origline);
2419 return DIRECTIVE_FOUND;
2421 tline = tline->next;
2422 if (!tline || tline->type != TOK_ID) {
2423 error(ERR_NONFATAL,
2424 "`%%local' missing size type parameter");
2425 free_tlist(origline);
2426 return DIRECTIVE_FOUND;
2429 /* Allow macro expansion of type parameter */
2430 tt = tokenize(tline->text);
2431 tt = expand_smacro(tt);
2432 size = parse_size(tt->text);
2433 if (!size) {
2434 error(ERR_NONFATAL,
2435 "Invalid size type for `%%local' missing directive");
2436 free_tlist(tt);
2437 free_tlist(origline);
2438 return DIRECTIVE_FOUND;
2440 free_tlist(tt);
2442 /* Round up to even stack slots */
2443 size = ALIGN(size, StackSize);
2445 offset += size; /* Negative offset, increment before */
2447 /* Now define the macro for the argument */
2448 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2449 local, StackPointer, offset);
2450 do_directive(tokenize(directive));
2452 /* Now define the assign to setup the enter_c macro correctly */
2453 snprintf(directive, sizeof(directive),
2454 "%%assign %%$localsize %%$localsize+%d", size);
2455 do_directive(tokenize(directive));
2457 /* Move to the next argument in the list */
2458 tline = tline->next;
2459 if (tline && tline->type == TOK_WHITESPACE)
2460 tline = tline->next;
2461 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2462 LocalOffset = offset;
2463 free_tlist(origline);
2464 return DIRECTIVE_FOUND;
2466 case PP_CLEAR:
2467 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2468 if (tline->next)
2469 error(ERR_WARNING|ERR_PASS1,
2470 "trailing garbage after `%%clear' ignored");
2471 free_macros();
2472 init_macros();
2473 free_tlist(origline);
2474 return DIRECTIVE_FOUND;
2476 case PP_DEPEND:
2477 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2478 t = tline->next = expand_smacro(tline->next);
2479 skip_white_(t);
2480 if (!t || (t->type != TOK_STRING &&
2481 t->type != TOK_INTERNAL_STRING)) {
2482 error(ERR_NONFATAL, "`%%depend' expects a file name");
2483 free_tlist(origline);
2484 return DIRECTIVE_FOUND; /* but we did _something_ */
2486 if (t->next)
2487 error(ERR_WARNING|ERR_PASS1,
2488 "trailing garbage after `%%depend' ignored");
2489 p = t->text;
2490 if (t->type != TOK_INTERNAL_STRING)
2491 nasm_unquote_cstr(p, i);
2492 if (dephead && !in_list(*dephead, p)) {
2493 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2494 sl->next = NULL;
2495 strcpy(sl->str, p);
2496 *deptail = sl;
2497 deptail = &sl->next;
2499 free_tlist(origline);
2500 return DIRECTIVE_FOUND;
2502 case PP_INCLUDE:
2503 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2504 t = tline->next = expand_smacro(tline->next);
2505 skip_white_(t);
2507 if (!t || (t->type != TOK_STRING &&
2508 t->type != TOK_INTERNAL_STRING)) {
2509 error(ERR_NONFATAL, "`%%include' expects a file name");
2510 free_tlist(origline);
2511 return DIRECTIVE_FOUND; /* but we did _something_ */
2513 if (t->next)
2514 error(ERR_WARNING|ERR_PASS1,
2515 "trailing garbage after `%%include' ignored");
2516 p = t->text;
2517 if (t->type != TOK_INTERNAL_STRING)
2518 nasm_unquote_cstr(p, i);
2519 inc = nasm_malloc(sizeof(Include));
2520 inc->next = istk;
2521 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2522 if (!inc->fp) {
2523 /* -MG given but file not found */
2524 nasm_free(inc);
2525 } else {
2526 inc->fname = src_set_fname(nasm_strdup(p));
2527 inc->lineno = src_set_linnum(0);
2528 inc->lineinc = 1;
2529 inc->expansion = NULL;
2530 istk = inc;
2531 list->uplevel(LIST_INCLUDE);
2533 free_tlist(origline);
2534 return DIRECTIVE_FOUND;
2536 case PP_USE:
2537 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2539 static macros_t *use_pkg;
2540 const char *pkg_macro = NULL;
2542 tline = tline->next;
2543 skip_white_(tline);
2544 tline = expand_id(tline);
2546 if (!tline || (tline->type != TOK_STRING &&
2547 tline->type != TOK_INTERNAL_STRING &&
2548 tline->type != TOK_ID)) {
2549 error(ERR_NONFATAL, "`%%use' expects a package name");
2550 free_tlist(origline);
2551 return DIRECTIVE_FOUND; /* but we did _something_ */
2553 if (tline->next)
2554 error(ERR_WARNING|ERR_PASS1,
2555 "trailing garbage after `%%use' ignored");
2556 if (tline->type == TOK_STRING)
2557 nasm_unquote_cstr(tline->text, i);
2558 use_pkg = nasm_stdmac_find_package(tline->text);
2559 if (!use_pkg)
2560 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2561 else
2562 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2563 if (use_pkg && ! smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2564 /* Not already included, go ahead and include it */
2565 stdmacpos = use_pkg;
2567 free_tlist(origline);
2568 return DIRECTIVE_FOUND;
2570 case PP_PUSH:
2571 case PP_REPL:
2572 case PP_POP:
2573 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2574 tline = tline->next;
2575 skip_white_(tline);
2576 tline = expand_id(tline);
2577 if (tline) {
2578 if (!tok_type_(tline, TOK_ID)) {
2579 error(ERR_NONFATAL, "`%s' expects a context identifier",
2580 pp_directives[i]);
2581 free_tlist(origline);
2582 return DIRECTIVE_FOUND; /* but we did _something_ */
2584 if (tline->next)
2585 error(ERR_WARNING|ERR_PASS1,
2586 "trailing garbage after `%s' ignored",
2587 pp_directives[i]);
2588 p = nasm_strdup(tline->text);
2589 } else {
2590 p = NULL; /* Anonymous */
2593 if (i == PP_PUSH) {
2594 ctx = nasm_malloc(sizeof(Context));
2595 ctx->next = cstk;
2596 hash_init(&ctx->localmac, HASH_SMALL);
2597 ctx->name = p;
2598 ctx->number = unique++;
2599 cstk = ctx;
2600 } else {
2601 /* %pop or %repl */
2602 if (!cstk) {
2603 error(ERR_NONFATAL, "`%s': context stack is empty",
2604 pp_directives[i]);
2605 } else if (i == PP_POP) {
2606 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2607 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2608 "expected %s",
2609 cstk->name ? cstk->name : "anonymous", p);
2610 else
2611 ctx_pop();
2612 } else {
2613 /* i == PP_REPL */
2614 nasm_free(cstk->name);
2615 cstk->name = p;
2616 p = NULL;
2618 nasm_free(p);
2620 free_tlist(origline);
2621 return DIRECTIVE_FOUND;
2622 case PP_FATAL:
2623 severity = ERR_FATAL;
2624 goto issue_error;
2625 case PP_ERROR:
2626 severity = ERR_NONFATAL;
2627 goto issue_error;
2628 case PP_WARNING:
2629 severity = ERR_WARNING|ERR_WARN_USER;
2630 goto issue_error;
2632 issue_error:
2633 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2635 /* Only error out if this is the final pass */
2636 if (pass != 2 && i != PP_FATAL)
2637 return DIRECTIVE_FOUND;
2639 tline->next = expand_smacro(tline->next);
2640 tline = tline->next;
2641 skip_white_(tline);
2642 t = tline ? tline->next : NULL;
2643 skip_white_(t);
2644 if (tok_type_(tline, TOK_STRING) && !t) {
2645 /* The line contains only a quoted string */
2646 p = tline->text;
2647 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2648 error(severity, "%s", p);
2649 } else {
2650 /* Not a quoted string, or more than a quoted string */
2651 p = detoken(tline, false);
2652 error(severity, "%s", p);
2653 nasm_free(p);
2655 free_tlist(origline);
2656 return DIRECTIVE_FOUND;
2659 CASE_PP_IF:
2660 if (defining != NULL) {
2661 if (defining->type == EXP_IF) {
2662 defining->def_depth ++;
2664 return NO_DIRECTIVE_FOUND;
2666 if ((istk->expansion != NULL) &&
2667 (istk->expansion->emitting == false)) {
2668 j = COND_NEVER;
2669 } else {
2670 j = if_condition(tline->next, i);
2671 tline->next = NULL; /* it got freed */
2672 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
2674 ed = new_ExpDef();
2675 ed->type = EXP_IF;
2676 ed->state = j;
2677 ed->nolist = NULL;
2678 ed->def_depth = 0;
2679 ed->cur_depth = 0;
2680 ed->max_depth = 0;
2681 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
2682 ed->prev = defining;
2683 defining = ed;
2684 free_tlist(origline);
2685 return DIRECTIVE_FOUND;
2687 CASE_PP_ELIF:
2688 if (defining != NULL) {
2689 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2690 return NO_DIRECTIVE_FOUND;
2693 if ((defining == NULL) || (defining->type != EXP_IF)) {
2694 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2696 switch (defining->state) {
2697 case COND_IF_TRUE:
2698 defining->state = COND_DONE;
2699 defining->ignoring = true;
2700 break;
2702 case COND_DONE:
2703 case COND_NEVER:
2704 defining->ignoring = true;
2705 break;
2707 case COND_ELSE_TRUE:
2708 case COND_ELSE_FALSE:
2709 error_precond(ERR_WARNING|ERR_PASS1,
2710 "`%%elif' after `%%else' ignored");
2711 defining->state = COND_NEVER;
2712 defining->ignoring = true;
2713 break;
2715 case COND_IF_FALSE:
2717 * IMPORTANT: In the case of %if, we will already have
2718 * called expand_mmac_params(); however, if we're
2719 * processing an %elif we must have been in a
2720 * non-emitting mode, which would have inhibited
2721 * the normal invocation of expand_mmac_params().
2722 * Therefore, we have to do it explicitly here.
2724 j = if_condition(expand_mmac_params(tline->next), i);
2725 tline->next = NULL; /* it got freed */
2726 defining->state =
2727 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2728 defining->ignoring = ((defining->state == COND_IF_TRUE) ? false : true);
2729 break;
2731 free_tlist(origline);
2732 return DIRECTIVE_FOUND;
2734 case PP_ELSE:
2735 if (defining != NULL) {
2736 if ((defining->type != EXP_IF) || (defining->def_depth > 0)) {
2737 return NO_DIRECTIVE_FOUND;
2740 if (tline->next)
2741 error_precond(ERR_WARNING|ERR_PASS1,
2742 "trailing garbage after `%%else' ignored");
2743 if ((defining == NULL) || (defining->type != EXP_IF)) {
2744 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2746 switch (defining->state) {
2747 case COND_IF_TRUE:
2748 case COND_DONE:
2749 defining->state = COND_ELSE_FALSE;
2750 defining->ignoring = true;
2751 break;
2753 case COND_NEVER:
2754 defining->ignoring = true;
2755 break;
2757 case COND_IF_FALSE:
2758 defining->state = COND_ELSE_TRUE;
2759 defining->ignoring = false;
2760 break;
2762 case COND_ELSE_TRUE:
2763 case COND_ELSE_FALSE:
2764 error_precond(ERR_WARNING|ERR_PASS1,
2765 "`%%else' after `%%else' ignored.");
2766 defining->state = COND_NEVER;
2767 defining->ignoring = true;
2768 break;
2770 free_tlist(origline);
2771 return DIRECTIVE_FOUND;
2773 case PP_ENDIF:
2774 if (defining != NULL) {
2775 if (defining->type == EXP_IF) {
2776 if (defining->def_depth > 0) {
2777 defining->def_depth --;
2778 return NO_DIRECTIVE_FOUND;
2780 } else {
2781 return NO_DIRECTIVE_FOUND;
2784 if (tline->next)
2785 error_precond(ERR_WARNING|ERR_PASS1,
2786 "trailing garbage after `%%endif' ignored");
2787 if ((defining == NULL) || (defining->type != EXP_IF)) {
2788 error(ERR_NONFATAL, "`%%endif': no matching `%%if'");
2790 ed = defining;
2791 defining = ed->prev;
2792 ed->prev = expansions;
2793 expansions = ed;
2794 ei = new_ExpInv();
2795 ei->type = EXP_IF;
2796 ei->def = ed;
2797 ei->current = ed->line;
2798 ei->emitting = true;
2799 ei->prev = istk->expansion;
2800 istk->expansion = ei;
2801 free_tlist(origline);
2802 return DIRECTIVE_FOUND;
2804 case PP_RMACRO:
2805 case PP_IRMACRO:
2806 case PP_MACRO:
2807 case PP_IMACRO:
2808 if (defining != NULL) {
2809 if (defining->type == EXP_MMACRO) {
2810 defining->def_depth ++;
2812 return NO_DIRECTIVE_FOUND;
2814 ed = new_ExpDef();
2815 ed->max_depth =
2816 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2817 ed->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2818 if (!parse_mmacro_spec(tline, ed, pp_directives[i])) {
2819 nasm_free(ed);
2820 ed = NULL;
2821 return DIRECTIVE_FOUND;
2823 ed->type = EXP_MMACRO;
2824 ed->def_depth = 0;
2825 ed->cur_depth = 0;
2826 ed->max_depth = (ed->max_depth + 1);
2827 ed->ignoring = false;
2828 ed->prev = defining;
2829 defining = ed;
2831 eed = (ExpDef *) hash_findix(&expdefs, ed->name);
2832 while (eed) {
2833 if (!strcmp(eed->name, ed->name) &&
2834 (eed->nparam_min <= ed->nparam_max
2835 || ed->plus)
2836 && (ed->nparam_min <= eed->nparam_max
2837 || eed->plus)) {
2838 error(ERR_WARNING|ERR_PASS1,
2839 "redefining multi-line macro `%s'", ed->name);
2840 return DIRECTIVE_FOUND;
2842 eed = eed->next;
2844 free_tlist(origline);
2845 return DIRECTIVE_FOUND;
2847 case PP_ENDM:
2848 case PP_ENDMACRO:
2849 if (defining != NULL) {
2850 if (defining->type == EXP_MMACRO) {
2851 if (defining->def_depth > 0) {
2852 defining->def_depth --;
2853 return NO_DIRECTIVE_FOUND;
2855 } else {
2856 return NO_DIRECTIVE_FOUND;
2859 if (!(defining) || (defining->type != EXP_MMACRO)) {
2860 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2861 return DIRECTIVE_FOUND;
2863 edhead = (ExpDef **) hash_findi_add(&expdefs, defining->name);
2864 defining->next = *edhead;
2865 *edhead = defining;
2866 ed = defining;
2867 defining = ed->prev;
2868 ed->prev = expansions;
2869 expansions = ed;
2870 ed = NULL;
2871 free_tlist(origline);
2872 return DIRECTIVE_FOUND;
2874 case PP_EXITMACRO:
2875 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2877 * We must search along istk->expansion until we hit a
2878 * macro invocation. Then we disable the emitting state(s)
2879 * between exitmacro and endmacro.
2881 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
2882 if(ei->type == EXP_MMACRO) {
2883 break;
2887 if (ei != NULL) {
2889 * Set all invocations leading back to the macro
2890 * invocation to a non-emitting state.
2892 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
2893 eei->emitting = false;
2895 eei->emitting = false;
2896 } else {
2897 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2899 free_tlist(origline);
2900 return DIRECTIVE_FOUND;
2902 case PP_UNMACRO:
2903 case PP_UNIMACRO:
2904 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2906 ExpDef **ed_p;
2907 ExpDef spec;
2909 spec.casesense = (i == PP_UNMACRO);
2910 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2911 return DIRECTIVE_FOUND;
2913 ed_p = (ExpDef **) hash_findi(&expdefs, spec.name, NULL);
2914 while (ed_p && *ed_p) {
2915 ed = *ed_p;
2916 if (ed->casesense == spec.casesense &&
2917 !mstrcmp(ed->name, spec.name, spec.casesense) &&
2918 ed->nparam_min == spec.nparam_min &&
2919 ed->nparam_max == spec.nparam_max &&
2920 ed->plus == spec.plus) {
2921 *ed_p = ed->next;
2922 free_expdef(ed);
2923 } else {
2924 ed_p = &ed->next;
2927 free_tlist(origline);
2928 free_tlist(spec.dlist);
2929 return DIRECTIVE_FOUND;
2932 case PP_ROTATE:
2933 if (defining != NULL) return NO_DIRECTIVE_FOUND;
2934 if (tline->next && tline->next->type == TOK_WHITESPACE)
2935 tline = tline->next;
2936 if (!tline->next) {
2937 free_tlist(origline);
2938 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2939 return DIRECTIVE_FOUND;
2941 t = expand_smacro(tline->next);
2942 tline->next = NULL;
2943 free_tlist(origline);
2944 tline = t;
2945 tptr = &t;
2946 tokval.t_type = TOKEN_INVALID;
2947 evalresult =
2948 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2949 free_tlist(tline);
2950 if (!evalresult)
2951 return DIRECTIVE_FOUND;
2952 if (tokval.t_type)
2953 error(ERR_WARNING|ERR_PASS1,
2954 "trailing garbage after expression ignored");
2955 if (!is_simple(evalresult)) {
2956 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2957 return DIRECTIVE_FOUND;
2959 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
2960 if (ei->type == EXP_MMACRO) {
2961 break;
2964 if (ei == NULL) {
2965 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2966 } else if (ei->nparam == 0) {
2967 error(ERR_NONFATAL,
2968 "`%%rotate' invoked within macro without parameters");
2969 } else {
2970 int rotate = ei->rotate + reloc_value(evalresult);
2972 rotate %= (int)ei->nparam;
2973 if (rotate < 0)
2974 rotate += ei->nparam;
2975 ei->rotate = rotate;
2977 return DIRECTIVE_FOUND;
2979 case PP_REP:
2980 if (defining != NULL) {
2981 if (defining->type == EXP_REP) {
2982 defining->def_depth ++;
2984 return NO_DIRECTIVE_FOUND;
2986 nolist = false;
2987 do {
2988 tline = tline->next;
2989 } while (tok_type_(tline, TOK_WHITESPACE));
2991 if (tok_type_(tline, TOK_ID) &&
2992 nasm_stricmp(tline->text, ".nolist") == 0) {
2993 nolist = true;
2994 do {
2995 tline = tline->next;
2996 } while (tok_type_(tline, TOK_WHITESPACE));
2999 if (tline) {
3000 t = expand_smacro(tline);
3001 tptr = &t;
3002 tokval.t_type = TOKEN_INVALID;
3003 evalresult =
3004 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3005 if (!evalresult) {
3006 free_tlist(origline);
3007 return DIRECTIVE_FOUND;
3009 if (tokval.t_type)
3010 error(ERR_WARNING|ERR_PASS1,
3011 "trailing garbage after expression ignored");
3012 if (!is_simple(evalresult)) {
3013 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
3014 return DIRECTIVE_FOUND;
3016 count = reloc_value(evalresult) + 1;
3017 } else {
3018 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
3019 count = 0;
3021 free_tlist(origline);
3022 ed = new_ExpDef();
3023 ed->type = EXP_REP;
3024 ed->nolist = nolist;
3025 ed->def_depth = 0;
3026 ed->cur_depth = 1;
3027 ed->max_depth = (count - 1);
3028 ed->ignoring = false;
3029 ed->prev = defining;
3030 defining = ed;
3031 return DIRECTIVE_FOUND;
3033 case PP_ENDREP:
3034 if (defining != NULL) {
3035 if (defining->type == EXP_REP) {
3036 if (defining->def_depth > 0) {
3037 defining->def_depth --;
3038 return NO_DIRECTIVE_FOUND;
3040 } else {
3041 return NO_DIRECTIVE_FOUND;
3044 if ((defining == NULL) || (defining->type != EXP_REP)) {
3045 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
3046 return DIRECTIVE_FOUND;
3050 * Now we have a "macro" defined - although it has no name
3051 * and we won't be entering it in the hash tables - we must
3052 * push a macro-end marker for it on to istk->expansion.
3053 * After that, it will take care of propagating itself (a
3054 * macro-end marker line for a macro which is really a %rep
3055 * block will cause the macro to be re-expanded, complete
3056 * with another macro-end marker to ensure the process
3057 * continues) until the whole expansion is forcibly removed
3058 * from istk->expansion by a %exitrep.
3060 ed = defining;
3061 defining = ed->prev;
3062 ed->prev = expansions;
3063 expansions = ed;
3064 ei = new_ExpInv();
3065 ei->type = EXP_REP;
3066 ei->def = ed;
3067 ei->current = ed->line;
3068 ei->emitting = ((ed->max_depth > 0) ? true : false);
3069 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
3070 ei->prev = istk->expansion;
3071 istk->expansion = ei;
3072 free_tlist(origline);
3073 return DIRECTIVE_FOUND;
3075 case PP_EXITREP:
3076 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3078 * We must search along istk->expansion until we hit a
3079 * rep invocation. Then we disable the emitting state(s)
3080 * between exitrep and endrep.
3082 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3083 if (ei->type == EXP_REP) {
3084 break;
3088 if (ei != NULL) {
3090 * Set all invocations leading back to the rep
3091 * invocation to a non-emitting state.
3093 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3094 eei->emitting = false;
3096 eei->emitting = false;
3097 eei->current = NULL;
3098 eei->def->cur_depth = eei->def->max_depth;
3099 } else {
3100 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
3102 free_tlist(origline);
3103 return DIRECTIVE_FOUND;
3105 case PP_XDEFINE:
3106 case PP_IXDEFINE:
3107 case PP_DEFINE:
3108 case PP_IDEFINE:
3109 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3110 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
3112 tline = tline->next;
3113 skip_white_(tline);
3114 tline = expand_id(tline);
3115 if (!tline || (tline->type != TOK_ID &&
3116 (tline->type != TOK_PREPROC_ID ||
3117 tline->text[1] != '$'))) {
3118 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3119 pp_directives[i]);
3120 free_tlist(origline);
3121 return DIRECTIVE_FOUND;
3124 ctx = get_ctx(tline->text, &mname, false);
3125 last = tline;
3126 param_start = tline = tline->next;
3127 nparam = 0;
3129 /* Expand the macro definition now for %xdefine and %ixdefine */
3130 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
3131 tline = expand_smacro(tline);
3133 if (tok_is_(tline, "(")) {
3135 * This macro has parameters.
3138 tline = tline->next;
3139 while (1) {
3140 skip_white_(tline);
3141 if (!tline) {
3142 error(ERR_NONFATAL, "parameter identifier expected");
3143 free_tlist(origline);
3144 return DIRECTIVE_FOUND;
3146 if (tline->type != TOK_ID) {
3147 error(ERR_NONFATAL,
3148 "`%s': parameter identifier expected",
3149 tline->text);
3150 free_tlist(origline);
3151 return DIRECTIVE_FOUND;
3153 tline->type = TOK_SMAC_PARAM + nparam++;
3154 tline = tline->next;
3155 skip_white_(tline);
3156 if (tok_is_(tline, ",")) {
3157 tline = tline->next;
3158 } else {
3159 if (!tok_is_(tline, ")")) {
3160 error(ERR_NONFATAL,
3161 "`)' expected to terminate macro template");
3162 free_tlist(origline);
3163 return DIRECTIVE_FOUND;
3165 break;
3168 last = tline;
3169 tline = tline->next;
3171 if (tok_type_(tline, TOK_WHITESPACE))
3172 last = tline, tline = tline->next;
3173 macro_start = NULL;
3174 last->next = NULL;
3175 t = tline;
3176 while (t) {
3177 if (t->type == TOK_ID) {
3178 list_for_each(tt, param_start)
3179 if (tt->type >= TOK_SMAC_PARAM &&
3180 !strcmp(tt->text, t->text))
3181 t->type = tt->type;
3183 tt = t->next;
3184 t->next = macro_start;
3185 macro_start = t;
3186 t = tt;
3189 * Good. We now have a macro name, a parameter count, and a
3190 * token list (in reverse order) for an expansion. We ought
3191 * to be OK just to create an SMacro, store it, and let
3192 * free_tlist have the rest of the line (which we have
3193 * carefully re-terminated after chopping off the expansion
3194 * from the end).
3196 define_smacro(ctx, mname, casesense, nparam, macro_start);
3197 free_tlist(origline);
3198 return DIRECTIVE_FOUND;
3200 case PP_UNDEF:
3201 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3202 tline = tline->next;
3203 skip_white_(tline);
3204 tline = expand_id(tline);
3205 if (!tline || (tline->type != TOK_ID &&
3206 (tline->type != TOK_PREPROC_ID ||
3207 tline->text[1] != '$'))) {
3208 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
3209 free_tlist(origline);
3210 return DIRECTIVE_FOUND;
3212 if (tline->next) {
3213 error(ERR_WARNING|ERR_PASS1,
3214 "trailing garbage after macro name ignored");
3217 /* Find the context that symbol belongs to */
3218 ctx = get_ctx(tline->text, &mname, false);
3219 undef_smacro(ctx, mname);
3220 free_tlist(origline);
3221 return DIRECTIVE_FOUND;
3223 case PP_DEFSTR:
3224 case PP_IDEFSTR:
3225 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3226 casesense = (i == PP_DEFSTR);
3228 tline = tline->next;
3229 skip_white_(tline);
3230 tline = expand_id(tline);
3231 if (!tline || (tline->type != TOK_ID &&
3232 (tline->type != TOK_PREPROC_ID ||
3233 tline->text[1] != '$'))) {
3234 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3235 pp_directives[i]);
3236 free_tlist(origline);
3237 return DIRECTIVE_FOUND;
3240 ctx = get_ctx(tline->text, &mname, false);
3241 last = tline;
3242 tline = expand_smacro(tline->next);
3243 last->next = NULL;
3245 while (tok_type_(tline, TOK_WHITESPACE))
3246 tline = delete_Token(tline);
3248 p = detoken(tline, false);
3249 macro_start = nasm_malloc(sizeof(*macro_start));
3250 macro_start->next = NULL;
3251 macro_start->text = nasm_quote(p, strlen(p));
3252 macro_start->type = TOK_STRING;
3253 macro_start->a.mac = NULL;
3254 nasm_free(p);
3257 * We now have a macro name, an implicit parameter count of
3258 * zero, and a string token to use as an expansion. Create
3259 * and store an SMacro.
3261 define_smacro(ctx, mname, casesense, 0, macro_start);
3262 free_tlist(origline);
3263 return DIRECTIVE_FOUND;
3265 case PP_DEFTOK:
3266 case PP_IDEFTOK:
3267 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3268 casesense = (i == PP_DEFTOK);
3270 tline = tline->next;
3271 skip_white_(tline);
3272 tline = expand_id(tline);
3273 if (!tline || (tline->type != TOK_ID &&
3274 (tline->type != TOK_PREPROC_ID ||
3275 tline->text[1] != '$'))) {
3276 error(ERR_NONFATAL,
3277 "`%s' expects a macro identifier as first parameter",
3278 pp_directives[i]);
3279 free_tlist(origline);
3280 return DIRECTIVE_FOUND;
3282 ctx = get_ctx(tline->text, &mname, false);
3283 last = tline;
3284 tline = expand_smacro(tline->next);
3285 last->next = NULL;
3287 t = tline;
3288 while (tok_type_(t, TOK_WHITESPACE))
3289 t = t->next;
3290 /* t should now point to the string */
3291 if (t->type != TOK_STRING) {
3292 error(ERR_NONFATAL,
3293 "`%s` requires string as second parameter",
3294 pp_directives[i]);
3295 free_tlist(tline);
3296 free_tlist(origline);
3297 return DIRECTIVE_FOUND;
3300 nasm_unquote_cstr(t->text, i);
3301 macro_start = tokenize(t->text);
3304 * We now have a macro name, an implicit parameter count of
3305 * zero, and a numeric token to use as an expansion. Create
3306 * and store an SMacro.
3308 define_smacro(ctx, mname, casesense, 0, macro_start);
3309 free_tlist(tline);
3310 free_tlist(origline);
3311 return DIRECTIVE_FOUND;
3313 case PP_PATHSEARCH:
3314 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3316 FILE *fp;
3317 StrList *xsl = NULL;
3318 StrList **xst = &xsl;
3320 casesense = true;
3322 tline = tline->next;
3323 skip_white_(tline);
3324 tline = expand_id(tline);
3325 if (!tline || (tline->type != TOK_ID &&
3326 (tline->type != TOK_PREPROC_ID ||
3327 tline->text[1] != '$'))) {
3328 error(ERR_NONFATAL,
3329 "`%%pathsearch' expects a macro identifier as first parameter");
3330 free_tlist(origline);
3331 return DIRECTIVE_FOUND;
3333 ctx = get_ctx(tline->text, &mname, false);
3334 last = tline;
3335 tline = expand_smacro(tline->next);
3336 last->next = NULL;
3338 t = tline;
3339 while (tok_type_(t, TOK_WHITESPACE))
3340 t = t->next;
3342 if (!t || (t->type != TOK_STRING &&
3343 t->type != TOK_INTERNAL_STRING)) {
3344 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3345 free_tlist(tline);
3346 free_tlist(origline);
3347 return DIRECTIVE_FOUND; /* but we did _something_ */
3349 if (t->next)
3350 error(ERR_WARNING|ERR_PASS1,
3351 "trailing garbage after `%%pathsearch' ignored");
3352 p = t->text;
3353 if (t->type != TOK_INTERNAL_STRING)
3354 nasm_unquote(p, NULL);
3356 fp = inc_fopen(p, &xsl, &xst, true);
3357 if (fp) {
3358 p = xsl->str;
3359 fclose(fp); /* Don't actually care about the file */
3361 macro_start = nasm_malloc(sizeof(*macro_start));
3362 macro_start->next = NULL;
3363 macro_start->text = nasm_quote(p, strlen(p));
3364 macro_start->type = TOK_STRING;
3365 macro_start->a.mac = NULL;
3366 if (xsl)
3367 nasm_free(xsl);
3370 * We now have a macro name, an implicit parameter count of
3371 * zero, and a string token to use as an expansion. Create
3372 * and store an SMacro.
3374 define_smacro(ctx, mname, casesense, 0, macro_start);
3375 free_tlist(tline);
3376 free_tlist(origline);
3377 return DIRECTIVE_FOUND;
3380 case PP_STRLEN:
3381 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3382 casesense = true;
3384 tline = tline->next;
3385 skip_white_(tline);
3386 tline = expand_id(tline);
3387 if (!tline || (tline->type != TOK_ID &&
3388 (tline->type != TOK_PREPROC_ID ||
3389 tline->text[1] != '$'))) {
3390 error(ERR_NONFATAL,
3391 "`%%strlen' expects a macro identifier as first parameter");
3392 free_tlist(origline);
3393 return DIRECTIVE_FOUND;
3395 ctx = get_ctx(tline->text, &mname, false);
3396 last = tline;
3397 tline = expand_smacro(tline->next);
3398 last->next = NULL;
3400 t = tline;
3401 while (tok_type_(t, TOK_WHITESPACE))
3402 t = t->next;
3403 /* t should now point to the string */
3404 if (!tok_type_(t, TOK_STRING)) {
3405 error(ERR_NONFATAL,
3406 "`%%strlen` requires string as second parameter");
3407 free_tlist(tline);
3408 free_tlist(origline);
3409 return DIRECTIVE_FOUND;
3412 macro_start = nasm_malloc(sizeof(*macro_start));
3413 macro_start->next = NULL;
3414 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3415 macro_start->a.mac = NULL;
3418 * We now have a macro name, an implicit parameter count of
3419 * zero, and a numeric token to use as an expansion. Create
3420 * and store an SMacro.
3422 define_smacro(ctx, mname, casesense, 0, macro_start);
3423 free_tlist(tline);
3424 free_tlist(origline);
3425 return DIRECTIVE_FOUND;
3427 case PP_STRCAT:
3428 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3429 casesense = true;
3431 tline = tline->next;
3432 skip_white_(tline);
3433 tline = expand_id(tline);
3434 if (!tline || (tline->type != TOK_ID &&
3435 (tline->type != TOK_PREPROC_ID ||
3436 tline->text[1] != '$'))) {
3437 error(ERR_NONFATAL,
3438 "`%%strcat' expects a macro identifier as first parameter");
3439 free_tlist(origline);
3440 return DIRECTIVE_FOUND;
3442 ctx = get_ctx(tline->text, &mname, false);
3443 last = tline;
3444 tline = expand_smacro(tline->next);
3445 last->next = NULL;
3447 len = 0;
3448 list_for_each(t, tline) {
3449 switch (t->type) {
3450 case TOK_WHITESPACE:
3451 break;
3452 case TOK_STRING:
3453 len += t->a.len = nasm_unquote(t->text, NULL);
3454 break;
3455 case TOK_OTHER:
3456 if (!strcmp(t->text, ",")) /* permit comma separators */
3457 break;
3458 /* else fall through */
3459 default:
3460 error(ERR_NONFATAL,
3461 "non-string passed to `%%strcat' (%d)", t->type);
3462 free_tlist(tline);
3463 free_tlist(origline);
3464 return DIRECTIVE_FOUND;
3468 p = pp = nasm_malloc(len);
3469 list_for_each(t, tline) {
3470 if (t->type == TOK_STRING) {
3471 memcpy(p, t->text, t->a.len);
3472 p += t->a.len;
3477 * We now have a macro name, an implicit parameter count of
3478 * zero, and a numeric token to use as an expansion. Create
3479 * and store an SMacro.
3481 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3482 macro_start->text = nasm_quote(pp, len);
3483 nasm_free(pp);
3484 define_smacro(ctx, mname, casesense, 0, macro_start);
3485 free_tlist(tline);
3486 free_tlist(origline);
3487 return DIRECTIVE_FOUND;
3489 case PP_SUBSTR:
3490 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3492 int64_t a1, a2;
3493 size_t len;
3495 casesense = true;
3497 tline = tline->next;
3498 skip_white_(tline);
3499 tline = expand_id(tline);
3500 if (!tline || (tline->type != TOK_ID &&
3501 (tline->type != TOK_PREPROC_ID ||
3502 tline->text[1] != '$'))) {
3503 error(ERR_NONFATAL,
3504 "`%%substr' expects a macro identifier as first parameter");
3505 free_tlist(origline);
3506 return DIRECTIVE_FOUND;
3508 ctx = get_ctx(tline->text, &mname, false);
3509 last = tline;
3510 tline = expand_smacro(tline->next);
3511 last->next = NULL;
3513 t = tline->next;
3514 while (tok_type_(t, TOK_WHITESPACE))
3515 t = t->next;
3517 /* t should now point to the string */
3518 if (t->type != TOK_STRING) {
3519 error(ERR_NONFATAL,
3520 "`%%substr` requires string as second parameter");
3521 free_tlist(tline);
3522 free_tlist(origline);
3523 return DIRECTIVE_FOUND;
3526 tt = t->next;
3527 tptr = &tt;
3528 tokval.t_type = TOKEN_INVALID;
3529 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3530 pass, error, NULL);
3531 if (!evalresult) {
3532 free_tlist(tline);
3533 free_tlist(origline);
3534 return DIRECTIVE_FOUND;
3535 } else if (!is_simple(evalresult)) {
3536 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3537 free_tlist(tline);
3538 free_tlist(origline);
3539 return DIRECTIVE_FOUND;
3541 a1 = evalresult->value-1;
3543 while (tok_type_(tt, TOK_WHITESPACE))
3544 tt = tt->next;
3545 if (!tt) {
3546 a2 = 1; /* Backwards compatibility: one character */
3547 } else {
3548 tokval.t_type = TOKEN_INVALID;
3549 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3550 pass, error, NULL);
3551 if (!evalresult) {
3552 free_tlist(tline);
3553 free_tlist(origline);
3554 return DIRECTIVE_FOUND;
3555 } else if (!is_simple(evalresult)) {
3556 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3557 free_tlist(tline);
3558 free_tlist(origline);
3559 return DIRECTIVE_FOUND;
3561 a2 = evalresult->value;
3564 len = nasm_unquote(t->text, NULL);
3565 if (a2 < 0)
3566 a2 = a2+1+len-a1;
3567 if (a1+a2 > (int64_t)len)
3568 a2 = len-a1;
3570 macro_start = nasm_malloc(sizeof(*macro_start));
3571 macro_start->next = NULL;
3572 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3573 macro_start->type = TOK_STRING;
3574 macro_start->a.mac = NULL;
3577 * We now have a macro name, an implicit parameter count of
3578 * zero, and a numeric token to use as an expansion. Create
3579 * and store an SMacro.
3581 define_smacro(ctx, mname, casesense, 0, macro_start);
3582 free_tlist(tline);
3583 free_tlist(origline);
3584 return DIRECTIVE_FOUND;
3587 case PP_ASSIGN:
3588 case PP_IASSIGN:
3589 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3590 casesense = (i == PP_ASSIGN);
3592 tline = tline->next;
3593 skip_white_(tline);
3594 tline = expand_id(tline);
3595 if (!tline || (tline->type != TOK_ID &&
3596 (tline->type != TOK_PREPROC_ID ||
3597 tline->text[1] != '$'))) {
3598 error(ERR_NONFATAL,
3599 "`%%%sassign' expects a macro identifier",
3600 (i == PP_IASSIGN ? "i" : ""));
3601 free_tlist(origline);
3602 return DIRECTIVE_FOUND;
3604 ctx = get_ctx(tline->text, &mname, false);
3605 last = tline;
3606 tline = expand_smacro(tline->next);
3607 last->next = NULL;
3609 t = tline;
3610 tptr = &t;
3611 tokval.t_type = TOKEN_INVALID;
3612 evalresult =
3613 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3614 free_tlist(tline);
3615 if (!evalresult) {
3616 free_tlist(origline);
3617 return DIRECTIVE_FOUND;
3620 if (tokval.t_type)
3621 error(ERR_WARNING|ERR_PASS1,
3622 "trailing garbage after expression ignored");
3624 if (!is_simple(evalresult)) {
3625 error(ERR_NONFATAL,
3626 "non-constant value given to `%%%sassign'",
3627 (i == PP_IASSIGN ? "i" : ""));
3628 free_tlist(origline);
3629 return DIRECTIVE_FOUND;
3632 macro_start = nasm_malloc(sizeof(*macro_start));
3633 macro_start->next = NULL;
3634 make_tok_num(macro_start, reloc_value(evalresult));
3635 macro_start->a.mac = NULL;
3638 * We now have a macro name, an implicit parameter count of
3639 * zero, and a numeric token to use as an expansion. Create
3640 * and store an SMacro.
3642 define_smacro(ctx, mname, casesense, 0, macro_start);
3643 free_tlist(origline);
3644 return DIRECTIVE_FOUND;
3646 case PP_LINE:
3647 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3649 * Syntax is `%line nnn[+mmm] [filename]'
3651 tline = tline->next;
3652 skip_white_(tline);
3653 if (!tok_type_(tline, TOK_NUMBER)) {
3654 error(ERR_NONFATAL, "`%%line' expects line number");
3655 free_tlist(origline);
3656 return DIRECTIVE_FOUND;
3658 k = readnum(tline->text, &err);
3659 m = 1;
3660 tline = tline->next;
3661 if (tok_is_(tline, "+")) {
3662 tline = tline->next;
3663 if (!tok_type_(tline, TOK_NUMBER)) {
3664 error(ERR_NONFATAL, "`%%line' expects line increment");
3665 free_tlist(origline);
3666 return DIRECTIVE_FOUND;
3668 m = readnum(tline->text, &err);
3669 tline = tline->next;
3671 skip_white_(tline);
3672 src_set_linnum(k);
3673 istk->lineinc = m;
3674 if (tline) {
3675 nasm_free(src_set_fname(detoken(tline, false)));
3677 free_tlist(origline);
3678 return DIRECTIVE_FOUND;
3680 case PP_WHILE:
3681 if (defining != NULL) {
3682 if (defining->type == EXP_WHILE) {
3683 defining->def_depth ++;
3685 return NO_DIRECTIVE_FOUND;
3687 l = NULL;
3688 if ((istk->expansion != NULL) &&
3689 (istk->expansion->emitting == false)) {
3690 j = COND_NEVER;
3691 } else {
3692 l = new_Line();
3693 l->first = copy_Token(tline->next);
3694 j = if_condition(tline->next, i);
3695 tline->next = NULL; /* it got freed */
3696 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
3698 ed = new_ExpDef();
3699 ed->type = EXP_WHILE;
3700 ed->state = j;
3701 ed->cur_depth = 1;
3702 ed->max_depth = DEADMAN_LIMIT;
3703 ed->ignoring = ((ed->state == COND_IF_TRUE) ? false : true);
3704 if (ed->ignoring == false) {
3705 ed->line = l;
3706 ed->last = l;
3707 } else if (l != NULL) {
3708 delete_Token(l->first);
3709 nasm_free(l);
3710 l = NULL;
3712 ed->prev = defining;
3713 defining = ed;
3714 free_tlist(origline);
3715 return DIRECTIVE_FOUND;
3717 case PP_ENDWHILE:
3718 if (defining != NULL) {
3719 if (defining->type == EXP_WHILE) {
3720 if (defining->def_depth > 0) {
3721 defining->def_depth --;
3722 return NO_DIRECTIVE_FOUND;
3724 } else {
3725 return NO_DIRECTIVE_FOUND;
3728 if (tline->next != NULL) {
3729 error_precond(ERR_WARNING|ERR_PASS1,
3730 "trailing garbage after `%%endwhile' ignored");
3732 if ((defining == NULL) || (defining->type != EXP_WHILE)) {
3733 error(ERR_NONFATAL, "`%%endwhile': no matching `%%while'");
3734 return DIRECTIVE_FOUND;
3736 ed = defining;
3737 defining = ed->prev;
3738 if (ed->ignoring == false) {
3739 ed->prev = expansions;
3740 expansions = ed;
3741 ei = new_ExpInv();
3742 ei->type = EXP_WHILE;
3743 ei->def = ed;
3744 ei->current = ed->line->next;
3745 ei->emitting = true;
3746 ei->prev = istk->expansion;
3747 istk->expansion = ei;
3748 } else {
3749 nasm_free(ed);
3751 free_tlist(origline);
3752 return DIRECTIVE_FOUND;
3754 case PP_EXITWHILE:
3755 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3757 * We must search along istk->expansion until we hit a
3758 * while invocation. Then we disable the emitting state(s)
3759 * between exitwhile and endwhile.
3761 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
3762 if (ei->type == EXP_WHILE) {
3763 break;
3767 if (ei != NULL) {
3769 * Set all invocations leading back to the while
3770 * invocation to a non-emitting state.
3772 for (eei = istk->expansion; eei != ei; eei = eei->prev) {
3773 eei->emitting = false;
3775 eei->emitting = false;
3776 eei->current = NULL;
3777 eei->def->cur_depth = eei->def->max_depth;
3778 } else {
3779 error(ERR_NONFATAL, "`%%exitwhile' not within `%%while' block");
3781 free_tlist(origline);
3782 return DIRECTIVE_FOUND;
3784 case PP_COMMENT:
3785 if (defining != NULL) {
3786 if (defining->type == EXP_COMMENT) {
3787 defining->def_depth ++;
3789 return NO_DIRECTIVE_FOUND;
3791 ed = new_ExpDef();
3792 ed->type = EXP_COMMENT;
3793 ed->ignoring = true;
3794 ed->prev = defining;
3795 defining = ed;
3796 free_tlist(origline);
3797 return DIRECTIVE_FOUND;
3799 case PP_ENDCOMMENT:
3800 if (defining != NULL) {
3801 if (defining->type == EXP_COMMENT) {
3802 if (defining->def_depth > 0) {
3803 defining->def_depth --;
3804 return NO_DIRECTIVE_FOUND;
3806 } else {
3807 return NO_DIRECTIVE_FOUND;
3810 if ((defining == NULL) || (defining->type != EXP_COMMENT)) {
3811 error(ERR_NONFATAL, "`%%endcomment': no matching `%%comment'");
3812 return DIRECTIVE_FOUND;
3814 ed = defining;
3815 defining = ed->prev;
3816 nasm_free(ed);
3817 free_tlist(origline);
3818 return DIRECTIVE_FOUND;
3820 case PP_FINAL:
3821 if (defining != NULL) return NO_DIRECTIVE_FOUND;
3822 if (in_final != false) {
3823 error(ERR_FATAL, "`%%final' cannot be used recursively");
3825 tline = tline->next;
3826 skip_white_(tline);
3827 if (tline == NULL) {
3828 error(ERR_NONFATAL, "`%%final' expects at least one parameter");
3829 } else {
3830 l = new_Line();
3831 l->first = copy_Token(tline);
3832 l->next = finals;
3833 finals = l;
3835 free_tlist(origline);
3836 return DIRECTIVE_FOUND;
3838 default:
3839 error(ERR_FATAL,
3840 "preprocessor directive `%s' not yet implemented",
3841 pp_directives[i]);
3842 return DIRECTIVE_FOUND;
3847 * Ensure that a macro parameter contains a condition code and
3848 * nothing else. Return the condition code index if so, or -1
3849 * otherwise.
3851 static int find_cc(Token * t)
3853 Token *tt;
3854 int i, j, k, m;
3856 if (!t)
3857 return -1; /* Probably a %+ without a space */
3859 skip_white_(t);
3860 if (t->type != TOK_ID)
3861 return -1;
3862 tt = t->next;
3863 skip_white_(tt);
3864 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3865 return -1;
3867 i = -1;
3868 j = ARRAY_SIZE(conditions);
3869 while (j - i > 1) {
3870 k = (j + i) / 2;
3871 m = nasm_stricmp(t->text, conditions[k]);
3872 if (m == 0) {
3873 i = k;
3874 j = -2;
3875 break;
3876 } else if (m < 0) {
3877 j = k;
3878 } else
3879 i = k;
3881 if (j != -2)
3882 return -1;
3883 return i;
3886 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3888 Token **tail, *t, *tt;
3889 Token **paste_head;
3890 bool did_paste = false;
3891 char *tmp;
3893 /* Now handle token pasting... */
3894 paste_head = NULL;
3895 tail = head;
3896 while ((t = *tail) && (tt = t->next)) {
3897 switch (t->type) {
3898 case TOK_WHITESPACE:
3899 if (tt->type == TOK_WHITESPACE) {
3900 /* Zap adjacent whitespace tokens */
3901 t->next = delete_Token(tt);
3902 } else {
3903 /* Do not advance paste_head here */
3904 tail = &t->next;
3906 break;
3907 case TOK_ID:
3908 case TOK_NUMBER:
3909 case TOK_FLOAT:
3911 size_t len = 0;
3912 char *tmp, *p;
3914 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3915 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3916 tt->type == TOK_OTHER)) {
3917 len += strlen(tt->text);
3918 tt = tt->next;
3922 * Now tt points to the first token after
3923 * the potential paste area...
3925 if (tt != t->next) {
3926 /* We have at least two tokens... */
3927 len += strlen(t->text);
3928 p = tmp = nasm_malloc(len+1);
3930 while (t != tt) {
3931 strcpy(p, t->text);
3932 p = strchr(p, '\0');
3933 t = delete_Token(t);
3936 t = *tail = tokenize(tmp);
3937 nasm_free(tmp);
3939 while (t->next) {
3940 tail = &t->next;
3941 t = t->next;
3943 t->next = tt; /* Attach the remaining token chain */
3945 did_paste = true;
3947 paste_head = tail;
3948 tail = &t->next;
3949 break;
3951 case TOK_PASTE: /* %+ */
3952 if (handle_paste_tokens) {
3953 /* Zap %+ and whitespace tokens to the right */
3954 while (t && (t->type == TOK_WHITESPACE ||
3955 t->type == TOK_PASTE))
3956 t = *tail = delete_Token(t);
3957 if (!paste_head || !t)
3958 break; /* Nothing to paste with */
3959 tail = paste_head;
3960 t = *tail;
3961 tt = t->next;
3962 while (tok_type_(tt, TOK_WHITESPACE))
3963 tt = t->next = delete_Token(tt);
3965 if (tt) {
3966 tmp = nasm_strcat(t->text, tt->text);
3967 delete_Token(t);
3968 tt = delete_Token(tt);
3969 t = *tail = tokenize(tmp);
3970 nasm_free(tmp);
3971 while (t->next) {
3972 tail = &t->next;
3973 t = t->next;
3975 t->next = tt; /* Attach the remaining token chain */
3976 did_paste = true;
3978 paste_head = tail;
3979 tail = &t->next;
3980 break;
3982 /* else fall through */
3983 default:
3984 tail = &t->next;
3985 if (!tok_type_(t->next, TOK_WHITESPACE))
3986 paste_head = tail;
3987 break;
3990 return did_paste;
3994 * expands to a list of tokens from %{x:y}
3996 static Token *expand_mmac_params_range(ExpInv *ei, Token *tline, Token ***last)
3998 Token *t = tline, **tt, *tm, *head;
3999 char *pos;
4000 int fst, lst, j, i;
4002 pos = strchr(tline->text, ':');
4003 nasm_assert(pos);
4005 lst = atoi(pos + 1);
4006 fst = atoi(tline->text + 1);
4009 * only macros params are accounted so
4010 * if someone passes %0 -- we reject such
4011 * value(s)
4013 if (lst == 0 || fst == 0)
4014 goto err;
4016 /* the values should be sane */
4017 if ((fst > (int)ei->nparam || fst < (-(int)ei->nparam)) ||
4018 (lst > (int)ei->nparam || lst < (-(int)ei->nparam)))
4019 goto err;
4021 fst = fst < 0 ? fst + (int)ei->nparam + 1: fst;
4022 lst = lst < 0 ? lst + (int)ei->nparam + 1: lst;
4024 /* counted from zero */
4025 fst--, lst--;
4028 * it will be at least one token
4030 tm = ei->params[(fst + ei->rotate) % ei->nparam];
4031 t = new_Token(NULL, tm->type, tm->text, 0);
4032 head = t, tt = &t->next;
4033 if (fst < lst) {
4034 for (i = fst + 1; i <= lst; i++) {
4035 t = new_Token(NULL, TOK_OTHER, ",", 0);
4036 *tt = t, tt = &t->next;
4037 j = (i + ei->rotate) % ei->nparam;
4038 tm = ei->params[j];
4039 t = new_Token(NULL, tm->type, tm->text, 0);
4040 *tt = t, tt = &t->next;
4042 } else {
4043 for (i = fst - 1; i >= lst; i--) {
4044 t = new_Token(NULL, TOK_OTHER, ",", 0);
4045 *tt = t, tt = &t->next;
4046 j = (i + ei->rotate) % ei->nparam;
4047 tm = ei->params[j];
4048 t = new_Token(NULL, tm->type, tm->text, 0);
4049 *tt = t, tt = &t->next;
4053 *last = tt;
4054 return head;
4056 err:
4057 error(ERR_NONFATAL, "`%%{%s}': macro parameters out of range",
4058 &tline->text[1]);
4059 return tline;
4063 * Expand MMacro-local things: parameter references (%0, %n, %+n,
4064 * %-n) and MMacro-local identifiers (%%foo) as well as
4065 * macro indirection (%[...]) and range (%{..:..}).
4067 static Token *expand_mmac_params(Token * tline)
4069 Token *t, *tt, **tail, *thead;
4070 bool changed = false;
4071 char *pos;
4073 tail = &thead;
4074 thead = NULL;
4076 while (tline) {
4077 if (tline->type == TOK_PREPROC_ID &&
4078 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text[2]) ||
4079 (tline->text[1] >= '0' && tline->text[1] <= '9') ||
4080 tline->text[1] == '%')) {
4081 char *text = NULL;
4082 int type = 0, cc; /* type = 0 to placate optimisers */
4083 char tmpbuf[30];
4084 unsigned int n;
4085 int i;
4086 ExpInv *ei;
4088 t = tline;
4089 tline = tline->next;
4091 for (ei = istk->expansion; ei != NULL; ei = ei->prev) {
4092 if (ei->type == EXP_MMACRO) {
4093 break;
4096 if (ei == NULL) {
4097 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
4098 } else {
4099 pos = strchr(t->text, ':');
4100 if (!pos) {
4101 switch (t->text[1]) {
4103 * We have to make a substitution of one of the
4104 * forms %1, %-1, %+1, %%foo, %0.
4106 case '0':
4107 if ((strlen(t->text) > 2) && (t->text[2] == '0')) {
4108 type = TOK_ID;
4109 text = nasm_strdup(ei->label_text);
4110 } else {
4111 type = TOK_NUMBER;
4112 snprintf(tmpbuf, sizeof(tmpbuf), "%d", ei->nparam);
4113 text = nasm_strdup(tmpbuf);
4115 break;
4116 case '%':
4117 type = TOK_ID;
4118 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
4119 ei->unique);
4120 text = nasm_strcat(tmpbuf, t->text + 2);
4121 break;
4122 case '-':
4123 n = atoi(t->text + 2) - 1;
4124 if (n >= ei->nparam)
4125 tt = NULL;
4126 else {
4127 if (ei->nparam > 1)
4128 n = (n + ei->rotate) % ei->nparam;
4129 tt = ei->params[n];
4131 cc = find_cc(tt);
4132 if (cc == -1) {
4133 error(ERR_NONFATAL,
4134 "macro parameter %d is not a condition code",
4135 n + 1);
4136 text = NULL;
4137 } else {
4138 type = TOK_ID;
4139 if (inverse_ccs[cc] == -1) {
4140 error(ERR_NONFATAL,
4141 "condition code `%s' is not invertible",
4142 conditions[cc]);
4143 text = NULL;
4144 } else
4145 text = nasm_strdup(conditions[inverse_ccs[cc]]);
4147 break;
4148 case '+':
4149 n = atoi(t->text + 2) - 1;
4150 if (n >= ei->nparam)
4151 tt = NULL;
4152 else {
4153 if (ei->nparam > 1)
4154 n = (n + ei->rotate) % ei->nparam;
4155 tt = ei->params[n];
4157 cc = find_cc(tt);
4158 if (cc == -1) {
4159 error(ERR_NONFATAL,
4160 "macro parameter %d is not a condition code",
4161 n + 1);
4162 text = NULL;
4163 } else {
4164 type = TOK_ID;
4165 text = nasm_strdup(conditions[cc]);
4167 break;
4168 default:
4169 n = atoi(t->text + 1) - 1;
4170 if (n >= ei->nparam)
4171 tt = NULL;
4172 else {
4173 if (ei->nparam > 1)
4174 n = (n + ei->rotate) % ei->nparam;
4175 tt = ei->params[n];
4177 if (tt) {
4178 for (i = 0; i < ei->paramlen[n]; i++) {
4179 *tail = new_Token(NULL, tt->type, tt->text, 0);
4180 tail = &(*tail)->next;
4181 tt = tt->next;
4184 text = NULL; /* we've done it here */
4185 break;
4187 } else {
4189 * seems we have a parameters range here
4191 Token *head, **last;
4192 head = expand_mmac_params_range(ei, t, &last);
4193 if (head != t) {
4194 *tail = head;
4195 *last = tline;
4196 tline = head;
4197 text = NULL;
4201 if (!text) {
4202 delete_Token(t);
4203 } else {
4204 *tail = t;
4205 tail = &t->next;
4206 t->type = type;
4207 nasm_free(t->text);
4208 t->text = text;
4209 t->a.mac = NULL;
4211 changed = true;
4212 continue;
4213 } else if (tline->type == TOK_INDIRECT) {
4214 t = tline;
4215 tline = tline->next;
4216 tt = tokenize(t->text);
4217 tt = expand_mmac_params(tt);
4218 tt = expand_smacro(tt);
4219 *tail = tt;
4220 while (tt) {
4221 tt->a.mac = NULL; /* Necessary? */
4222 tail = &tt->next;
4223 tt = tt->next;
4225 delete_Token(t);
4226 changed = true;
4227 } else {
4228 t = *tail = tline;
4229 tline = tline->next;
4230 t->a.mac = NULL;
4231 tail = &t->next;
4234 *tail = NULL;
4236 if (changed)
4237 paste_tokens(&thead, false);
4239 return thead;
4243 * Expand all single-line macro calls made in the given line.
4244 * Return the expanded version of the line. The original is deemed
4245 * to be destroyed in the process. (In reality we'll just move
4246 * Tokens from input to output a lot of the time, rather than
4247 * actually bothering to destroy and replicate.)
4250 static Token *expand_smacro(Token * tline)
4252 Token *t, *tt, *mstart, **tail, *thead;
4253 SMacro *head = NULL, *m;
4254 Token **params;
4255 int *paramsize;
4256 unsigned int nparam, sparam;
4257 int brackets;
4258 Token *org_tline = tline;
4259 Context *ctx;
4260 const char *mname;
4261 int deadman = DEADMAN_LIMIT;
4262 bool expanded;
4265 * Trick: we should avoid changing the start token pointer since it can
4266 * be contained in "next" field of other token. Because of this
4267 * we allocate a copy of first token and work with it; at the end of
4268 * routine we copy it back
4270 if (org_tline) {
4271 tline = new_Token(org_tline->next, org_tline->type,
4272 org_tline->text, 0);
4273 tline->a.mac = org_tline->a.mac;
4274 nasm_free(org_tline->text);
4275 org_tline->text = NULL;
4278 expanded = true; /* Always expand %+ at least once */
4280 again:
4281 thead = NULL;
4282 tail = &thead;
4284 while (tline) { /* main token loop */
4285 if (!--deadman) {
4286 error(ERR_NONFATAL, "interminable macro recursion");
4287 goto err;
4290 if ((mname = tline->text)) {
4291 /* if this token is a local macro, look in local context */
4292 if (tline->type == TOK_ID) {
4293 head = (SMacro *)hash_findix(&smacros, mname);
4294 } else if (tline->type == TOK_PREPROC_ID) {
4295 ctx = get_ctx(mname, &mname, true);
4296 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
4297 } else
4298 head = NULL;
4301 * We've hit an identifier. As in is_mmacro below, we first
4302 * check whether the identifier is a single-line macro at
4303 * all, then think about checking for parameters if
4304 * necessary.
4306 list_for_each(m, head)
4307 if (!mstrcmp(m->name, mname, m->casesense))
4308 break;
4309 if (m) {
4310 mstart = tline;
4311 params = NULL;
4312 paramsize = NULL;
4313 if (m->nparam == 0) {
4315 * Simple case: the macro is parameterless. Discard the
4316 * one token that the macro call took, and push the
4317 * expansion back on the to-do stack.
4319 if (!m->expansion) {
4320 if (!strcmp("__FILE__", m->name)) {
4321 int32_t num = 0;
4322 char *file = NULL;
4323 src_get(&num, &file);
4324 tline->text = nasm_quote(file, strlen(file));
4325 tline->type = TOK_STRING;
4326 nasm_free(file);
4327 continue;
4329 if (!strcmp("__LINE__", m->name)) {
4330 nasm_free(tline->text);
4331 make_tok_num(tline, src_get_linnum());
4332 continue;
4334 if (!strcmp("__BITS__", m->name)) {
4335 nasm_free(tline->text);
4336 make_tok_num(tline, globalbits);
4337 continue;
4339 tline = delete_Token(tline);
4340 continue;
4342 } else {
4344 * Complicated case: at least one macro with this name
4345 * exists and takes parameters. We must find the
4346 * parameters in the call, count them, find the SMacro
4347 * that corresponds to that form of the macro call, and
4348 * substitute for the parameters when we expand. What a
4349 * pain.
4351 /*tline = tline->next;
4352 skip_white_(tline); */
4353 do {
4354 t = tline->next;
4355 while (tok_type_(t, TOK_SMAC_END)) {
4356 t->a.mac->in_progress = false;
4357 t->text = NULL;
4358 t = tline->next = delete_Token(t);
4360 tline = t;
4361 } while (tok_type_(tline, TOK_WHITESPACE));
4362 if (!tok_is_(tline, "(")) {
4364 * This macro wasn't called with parameters: ignore
4365 * the call. (Behaviour borrowed from gnu cpp.)
4367 tline = mstart;
4368 m = NULL;
4369 } else {
4370 int paren = 0;
4371 int white = 0;
4372 brackets = 0;
4373 nparam = 0;
4374 sparam = PARAM_DELTA;
4375 params = nasm_malloc(sparam * sizeof(Token *));
4376 params[0] = tline->next;
4377 paramsize = nasm_malloc(sparam * sizeof(int));
4378 paramsize[0] = 0;
4379 while (true) { /* parameter loop */
4381 * For some unusual expansions
4382 * which concatenates function call
4384 t = tline->next;
4385 while (tok_type_(t, TOK_SMAC_END)) {
4386 t->a.mac->in_progress = false;
4387 t->text = NULL;
4388 t = tline->next = delete_Token(t);
4390 tline = t;
4392 if (!tline) {
4393 error(ERR_NONFATAL,
4394 "macro call expects terminating `)'");
4395 break;
4397 if (tline->type == TOK_WHITESPACE
4398 && brackets <= 0) {
4399 if (paramsize[nparam])
4400 white++;
4401 else
4402 params[nparam] = tline->next;
4403 continue; /* parameter loop */
4405 if (tline->type == TOK_OTHER
4406 && tline->text[1] == 0) {
4407 char ch = tline->text[0];
4408 if (ch == ',' && !paren && brackets <= 0) {
4409 if (++nparam >= sparam) {
4410 sparam += PARAM_DELTA;
4411 params = nasm_realloc(params,
4412 sparam * sizeof(Token *));
4413 paramsize = nasm_realloc(paramsize,
4414 sparam * sizeof(int));
4416 params[nparam] = tline->next;
4417 paramsize[nparam] = 0;
4418 white = 0;
4419 continue; /* parameter loop */
4421 if (ch == '{' &&
4422 (brackets > 0 || (brackets == 0 &&
4423 !paramsize[nparam])))
4425 if (!(brackets++)) {
4426 params[nparam] = tline->next;
4427 continue; /* parameter loop */
4430 if (ch == '}' && brackets > 0)
4431 if (--brackets == 0) {
4432 brackets = -1;
4433 continue; /* parameter loop */
4435 if (ch == '(' && !brackets)
4436 paren++;
4437 if (ch == ')' && brackets <= 0)
4438 if (--paren < 0)
4439 break;
4441 if (brackets < 0) {
4442 brackets = 0;
4443 error(ERR_NONFATAL, "braces do not "
4444 "enclose all of macro parameter");
4446 paramsize[nparam] += white + 1;
4447 white = 0;
4448 } /* parameter loop */
4449 nparam++;
4450 while (m && (m->nparam != nparam ||
4451 mstrcmp(m->name, mname,
4452 m->casesense)))
4453 m = m->next;
4454 if (!m)
4455 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4456 "macro `%s' exists, "
4457 "but not taking %d parameters",
4458 mstart->text, nparam);
4461 if (m && m->in_progress)
4462 m = NULL;
4463 if (!m) { /* in progess or didn't find '(' or wrong nparam */
4465 * Design question: should we handle !tline, which
4466 * indicates missing ')' here, or expand those
4467 * macros anyway, which requires the (t) test a few
4468 * lines down?
4470 nasm_free(params);
4471 nasm_free(paramsize);
4472 tline = mstart;
4473 } else {
4475 * Expand the macro: we are placed on the last token of the
4476 * call, so that we can easily split the call from the
4477 * following tokens. We also start by pushing an SMAC_END
4478 * token for the cycle removal.
4480 t = tline;
4481 if (t) {
4482 tline = t->next;
4483 t->next = NULL;
4485 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
4486 tt->a.mac = m;
4487 m->in_progress = true;
4488 tline = tt;
4489 list_for_each(t, m->expansion) {
4490 if (t->type >= TOK_SMAC_PARAM) {
4491 Token *pcopy = tline, **ptail = &pcopy;
4492 Token *ttt, *pt;
4493 int i;
4495 ttt = params[t->type - TOK_SMAC_PARAM];
4496 i = paramsize[t->type - TOK_SMAC_PARAM];
4497 while (--i >= 0) {
4498 pt = *ptail = new_Token(tline, ttt->type,
4499 ttt->text, 0);
4500 ptail = &pt->next;
4501 ttt = ttt->next;
4503 tline = pcopy;
4504 } else if (t->type == TOK_PREPROC_Q) {
4505 tt = new_Token(tline, TOK_ID, mname, 0);
4506 tline = tt;
4507 } else if (t->type == TOK_PREPROC_QQ) {
4508 tt = new_Token(tline, TOK_ID, m->name, 0);
4509 tline = tt;
4510 } else {
4511 tt = new_Token(tline, t->type, t->text, 0);
4512 tline = tt;
4517 * Having done that, get rid of the macro call, and clean
4518 * up the parameters.
4520 nasm_free(params);
4521 nasm_free(paramsize);
4522 free_tlist(mstart);
4523 expanded = true;
4524 continue; /* main token loop */
4529 if (tline->type == TOK_SMAC_END) {
4530 tline->a.mac->in_progress = false;
4531 tline = delete_Token(tline);
4532 } else {
4533 t = *tail = tline;
4534 tline = tline->next;
4535 t->a.mac = NULL;
4536 t->next = NULL;
4537 tail = &t->next;
4542 * Now scan the entire line and look for successive TOK_IDs that resulted
4543 * after expansion (they can't be produced by tokenize()). The successive
4544 * TOK_IDs should be concatenated.
4545 * Also we look for %+ tokens and concatenate the tokens before and after
4546 * them (without white spaces in between).
4548 if (expanded && paste_tokens(&thead, true)) {
4550 * If we concatenated something, *and* we had previously expanded
4551 * an actual macro, scan the lines again for macros...
4553 tline = thead;
4554 expanded = false;
4555 goto again;
4558 err:
4559 if (org_tline) {
4560 if (thead) {
4561 *org_tline = *thead;
4562 /* since we just gave text to org_line, don't free it */
4563 thead->text = NULL;
4564 delete_Token(thead);
4565 } else {
4566 /* the expression expanded to empty line;
4567 we can't return NULL for some reasons
4568 we just set the line to a single WHITESPACE token. */
4569 memset(org_tline, 0, sizeof(*org_tline));
4570 org_tline->text = NULL;
4571 org_tline->type = TOK_WHITESPACE;
4573 thead = org_tline;
4576 return thead;
4580 * Similar to expand_smacro but used exclusively with macro identifiers
4581 * right before they are fetched in. The reason is that there can be
4582 * identifiers consisting of several subparts. We consider that if there
4583 * are more than one element forming the name, user wants a expansion,
4584 * otherwise it will be left as-is. Example:
4586 * %define %$abc cde
4588 * the identifier %$abc will be left as-is so that the handler for %define
4589 * will suck it and define the corresponding value. Other case:
4591 * %define _%$abc cde
4593 * In this case user wants name to be expanded *before* %define starts
4594 * working, so we'll expand %$abc into something (if it has a value;
4595 * otherwise it will be left as-is) then concatenate all successive
4596 * PP_IDs into one.
4598 static Token *expand_id(Token * tline)
4600 Token *cur, *oldnext = NULL;
4602 if (!tline || !tline->next)
4603 return tline;
4605 cur = tline;
4606 while (cur->next &&
4607 (cur->next->type == TOK_ID ||
4608 cur->next->type == TOK_PREPROC_ID
4609 || cur->next->type == TOK_NUMBER))
4610 cur = cur->next;
4612 /* If identifier consists of just one token, don't expand */
4613 if (cur == tline)
4614 return tline;
4616 if (cur) {
4617 oldnext = cur->next; /* Detach the tail past identifier */
4618 cur->next = NULL; /* so that expand_smacro stops here */
4621 tline = expand_smacro(tline);
4623 if (cur) {
4624 /* expand_smacro possibly changhed tline; re-scan for EOL */
4625 cur = tline;
4626 while (cur && cur->next)
4627 cur = cur->next;
4628 if (cur)
4629 cur->next = oldnext;
4632 return tline;
4636 * Determine whether the given line constitutes a multi-line macro
4637 * call, and return the ExpDef structure called if so. Doesn't have
4638 * to check for an initial label - that's taken care of in
4639 * expand_mmacro - but must check numbers of parameters. Guaranteed
4640 * to be called with tline->type == TOK_ID, so the putative macro
4641 * name is easy to find.
4643 static ExpDef *is_mmacro(Token * tline, Token *** params_array)
4645 ExpDef *head, *ed;
4646 Token **params;
4647 int nparam;
4649 head = (ExpDef *) hash_findix(&expdefs, tline->text);
4652 * Efficiency: first we see if any macro exists with the given
4653 * name. If not, we can return NULL immediately. _Then_ we
4654 * count the parameters, and then we look further along the
4655 * list if necessary to find the proper ExpDef.
4657 list_for_each(ed, head)
4658 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4659 break;
4660 if (!ed)
4661 return NULL;
4664 * OK, we have a potential macro. Count and demarcate the
4665 * parameters.
4667 count_mmac_params(tline->next, &nparam, &params);
4670 * So we know how many parameters we've got. Find the ExpDef
4671 * structure that handles this number.
4673 while (ed) {
4674 if (ed->nparam_min <= nparam
4675 && (ed->plus || nparam <= ed->nparam_max)) {
4677 * It's right, and we can use it. Add its default
4678 * parameters to the end of our list if necessary.
4680 if (ed->defaults && nparam < ed->nparam_min + ed->ndefs) {
4681 params =
4682 nasm_realloc(params,
4683 ((ed->nparam_min + ed->ndefs +
4684 1) * sizeof(*params)));
4685 while (nparam < ed->nparam_min + ed->ndefs) {
4686 params[nparam] = ed->defaults[nparam - ed->nparam_min];
4687 nparam++;
4691 * If we've gone over the maximum parameter count (and
4692 * we're in Plus mode), ignore parameters beyond
4693 * nparam_max.
4695 if (ed->plus && nparam > ed->nparam_max)
4696 nparam = ed->nparam_max;
4698 * Then terminate the parameter list, and leave.
4700 if (!params) { /* need this special case */
4701 params = nasm_malloc(sizeof(*params));
4702 nparam = 0;
4704 params[nparam] = NULL;
4705 *params_array = params;
4706 return ed;
4709 * This one wasn't right: look for the next one with the
4710 * same name.
4712 list_for_each(ed, ed->next)
4713 if (!mstrcmp(ed->name, tline->text, ed->casesense))
4714 break;
4718 * After all that, we didn't find one with the right number of
4719 * parameters. Issue a warning, and fail to expand the macro.
4721 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4722 "macro `%s' exists, but not taking %d parameters",
4723 tline->text, nparam);
4724 nasm_free(params);
4725 return NULL;
4729 * Expand the multi-line macro call made by the given line, if
4730 * there is one to be expanded. If there is, push the expansion on
4731 * istk->expansion and return 1. Otherwise return 0.
4733 static int expand_mmacro(Token * tline)
4735 Token *startline = tline;
4736 Token *label = NULL;
4737 int dont_prepend = 0;
4738 Token **params, *t, *mtok, *tt;
4739 Line *l;
4740 ExpDef *ed;
4741 ExpInv *ei;
4742 int i, nparam, *paramlen;
4743 const char *mname;
4745 t = tline;
4746 skip_white_(t);
4747 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4748 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4749 return 0;
4750 mtok = t;
4751 ed = is_mmacro(t, &params);
4752 if (ed != NULL) {
4753 mname = t->text;
4754 } else {
4755 Token *last;
4757 * We have an id which isn't a macro call. We'll assume
4758 * it might be a label; we'll also check to see if a
4759 * colon follows it. Then, if there's another id after
4760 * that lot, we'll check it again for macro-hood.
4762 label = last = t;
4763 t = t->next;
4764 if (tok_type_(t, TOK_WHITESPACE))
4765 last = t, t = t->next;
4766 if (tok_is_(t, ":")) {
4767 dont_prepend = 1;
4768 last = t, t = t->next;
4769 if (tok_type_(t, TOK_WHITESPACE))
4770 last = t, t = t->next;
4772 if (!tok_type_(t, TOK_ID) || !(ed = is_mmacro(t, &params)))
4773 return 0;
4774 last->next = NULL;
4775 mname = t->text;
4776 tline = t;
4780 * Fix up the parameters: this involves stripping leading and
4781 * trailing whitespace, then stripping braces if they are
4782 * present.
4784 for (nparam = 0; params[nparam]; nparam++) ;
4785 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4787 for (i = 0; params[i]; i++) {
4788 int brace = false;
4789 int comma = (!ed->plus || i < nparam - 1);
4791 t = params[i];
4792 skip_white_(t);
4793 if (tok_is_(t, "{"))
4794 t = t->next, brace = true, comma = false;
4795 params[i] = t;
4796 paramlen[i] = 0;
4797 while (t) {
4798 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4799 break; /* ... because we have hit a comma */
4800 if (comma && t->type == TOK_WHITESPACE
4801 && tok_is_(t->next, ","))
4802 break; /* ... or a space then a comma */
4803 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4804 break; /* ... or a brace */
4805 t = t->next;
4806 paramlen[i]++;
4810 if (ed->cur_depth >= ed->max_depth) {
4811 if (ed->max_depth > 1) {
4812 error(ERR_WARNING,
4813 "reached maximum macro recursion depth of %i for %s",
4814 ed->max_depth,ed->name);
4816 return 0;
4817 } else {
4818 ed->cur_depth ++;
4822 * OK, we have found a ExpDef structure representing a
4823 * previously defined mmacro. Create an expansion invocation
4824 * and point it back to the expansion definition. Substitution of
4825 * parameter tokens and macro-local tokens doesn't get done
4826 * until the single-line macro substitution process; this is
4827 * because delaying them allows us to change the semantics
4828 * later through %rotate.
4830 ei = new_ExpInv();
4831 ei->type = EXP_MMACRO;
4832 ei->def = ed;
4833 // ei->label = label;
4834 ei->label_text = detoken(label, false);
4835 ei->current = ed->line;
4836 ei->emitting = true;
4837 // ei->iline = tline;
4838 ei->params = params;
4839 ei->nparam = nparam;
4840 ei->rotate = 0;
4841 ei->paramlen = paramlen;
4842 ei->lineno = 0;
4844 ei->prev = istk->expansion;
4845 istk->expansion = ei;
4847 /***** todo: relocate %? (Q) and %?? (QQ); %00 already relocated *****/
4849 list_for_each(l, m->expansion) {
4850 Token **tail;
4852 l = new_Line();
4853 l->next = istk->expansion;
4854 istk->expansion = l;
4855 tail = &l->first;
4857 list_for_each(t, ei->current->first) {
4858 Token *x = t;
4859 switch (t->type) {
4860 case TOK_PREPROC_Q:
4861 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4862 break;
4863 case TOK_PREPROC_QQ:
4864 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4865 break;
4866 case TOK_PREPROC_ID:
4867 if (t->text[1] == '0' && t->text[2] == '0') {
4868 dont_prepend = -1;
4869 x = label;
4870 if (!x)
4871 continue;
4873 // fall through
4874 default:
4875 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4876 break;
4878 tail = &tt->next;
4880 *tail = NULL;
4884 * If we had a label, push it on as the first line of
4885 * the macro expansion.
4887 if (label) {
4888 if (dont_prepend < 0)
4889 free_tlist(startline);
4890 else {
4891 l = new_Line();
4892 ei->label = l;
4893 l->first = startline;
4894 if (!dont_prepend) {
4895 while (label->next)
4896 label = label->next;
4897 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4902 list->uplevel(ed->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4904 return 1;
4907 /* The function that actually does the error reporting */
4908 static void verror(int severity, const char *fmt, va_list arg)
4910 char buff[1024];
4912 vsnprintf(buff, sizeof(buff), fmt, arg);
4914 if ((istk != NULL) &&
4915 (istk->expansion != NULL) &&
4916 (istk->expansion->type == EXP_MMACRO)) {
4917 ExpDef *ed = istk->expansion->def;
4918 nasm_error(severity, "(%s:%d) %s", ed->name,
4919 istk->expansion->lineno, buff);
4920 } else {
4921 nasm_error(severity, "%s", buff);
4926 * Since preprocessor always operate only on the line that didn't
4927 * arrived yet, we should always use ERR_OFFBY1.
4929 static void error(int severity, const char *fmt, ...)
4931 va_list arg;
4932 va_start(arg, fmt);
4933 verror(severity, fmt, arg);
4934 va_end(arg);
4938 * Because %else etc are evaluated in the state context
4939 * of the previous branch, errors might get lost with error():
4940 * %if 0 ... %else trailing garbage ... %endif
4941 * So %else etc should report errors with this function.
4943 static void error_precond(int severity, const char *fmt, ...)
4945 va_list arg;
4947 /* Only ignore the error if it's really in a dead branch */
4948 if ((istk != NULL) &&
4949 (istk->expansion != NULL) &&
4950 (istk->expansion->type == EXP_IF) &&
4951 (istk->expansion->def->state == COND_NEVER))
4952 return;
4954 va_start(arg, fmt);
4955 verror(severity, fmt, arg);
4956 va_end(arg);
4959 static void
4960 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
4962 Token *t;
4964 cstk = NULL;
4965 istk = nasm_malloc(sizeof(Include));
4966 istk->next = NULL;
4967 istk->expansion = NULL;
4968 istk->fp = fopen(file, "r");
4969 istk->fname = NULL;
4970 src_set_fname(nasm_strdup(file));
4971 src_set_linnum(0);
4972 istk->lineinc = 1;
4973 if (!istk->fp)
4974 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4975 file);
4976 defining = NULL;
4977 finals = NULL;
4978 in_final = false;
4979 nested_mac_count = 0;
4980 nested_rep_count = 0;
4981 init_macros();
4982 unique = 0;
4983 if (tasm_compatible_mode) {
4984 stdmacpos = nasm_stdmac;
4985 } else {
4986 stdmacpos = nasm_stdmac_after_tasm;
4988 any_extrastdmac = extrastdmac && *extrastdmac;
4989 do_predef = true;
4990 list = listgen;
4993 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4994 * The caller, however, will also pass in 3 for preprocess-only so
4995 * we can set __PASS__ accordingly.
4997 pass = apass > 2 ? 2 : apass;
4999 dephead = deptail = deplist;
5000 if (deplist) {
5001 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
5002 sl->next = NULL;
5003 strcpy(sl->str, file);
5004 *deptail = sl;
5005 deptail = &sl->next;
5009 * Define the __PASS__ macro. This is defined here unlike
5010 * all the other builtins, because it is special -- it varies between
5011 * passes.
5013 t = nasm_malloc(sizeof(*t));
5014 t->next = NULL;
5015 make_tok_num(t, apass);
5016 t->a.mac = NULL;
5017 define_smacro(NULL, "__PASS__", true, 0, t);
5020 static char *pp_getline(void)
5022 char *line;
5023 Token *tline;
5025 while (1) {
5027 * Fetch a tokenized line, either from the expansion
5028 * buffer or from the input file.
5030 tline = NULL;
5032 while (1) { /* until we get a line we can use */
5034 * Fetch a tokenized line from the expansion buffer
5036 if (istk->expansion != NULL) {
5038 ExpInv *e = istk->expansion;
5039 if (e->current != NULL) {
5040 if (e->emitting == false) {
5041 e->current = NULL;
5042 continue;
5044 Line *l = NULL;
5045 l = e->current;
5046 e->current = l->next;
5047 e->lineno++;
5048 tline = copy_Token(l->first);
5049 if (((e->type == EXP_REP) ||
5050 (e->type == EXP_MMACRO) ||
5051 (e->type == EXP_WHILE))
5052 && (e->def->nolist == false)) {
5053 char *p = detoken(tline, false);
5054 list->line(LIST_MACRO, p);
5055 nasm_free(p);
5057 break;
5058 } else if ((e->type == EXP_REP) &&
5059 (e->def->cur_depth < e->def->max_depth)) {
5060 e->def->cur_depth ++;
5061 e->current = e->def->line;
5062 e->lineno = 0;
5063 continue;
5064 } else if ((e->type == EXP_WHILE) &&
5065 (e->def->cur_depth < e->def->max_depth)) {
5066 e->current = e->def->line;
5067 e->lineno = 0;
5068 tline = copy_Token(e->current->first);
5069 int j = if_condition(tline, PP_WHILE);
5070 tline = NULL;
5071 j = (((j < 0) ? COND_NEVER : j) ? COND_IF_TRUE : COND_IF_FALSE);
5072 if (j == COND_IF_TRUE) {
5073 e->current = e->current->next;
5074 e->def->cur_depth ++;
5075 } else {
5076 e->emitting = false;
5077 e->current = NULL;
5078 e->def->cur_depth = e->def->max_depth;
5080 continue;
5081 } else {
5082 istk->expansion = e->prev;
5083 ExpDef *ed = e->def;
5084 if (ed != NULL) {
5085 if ((e->emitting == true) &&
5086 (ed->max_depth == DEADMAN_LIMIT) &&
5087 (ed->cur_depth == DEADMAN_LIMIT)
5089 error(ERR_FATAL, "runaway expansion detected, aborting");
5091 if (ed->cur_depth > 0) {
5092 ed->cur_depth --;
5093 } else if ((ed->type != EXP_MMACRO) && (ed->type != EXP_IF)) {
5094 /***** should this really be right here??? *****/
5096 Line *l = NULL, *ll = NULL;
5097 for (l = ed->line; l != NULL;) {
5098 if (l->first != NULL) {
5099 free_tlist(l->first);
5100 l->first = NULL;
5102 ll = l;
5103 l = l->next;
5104 nasm_free(ll);
5106 expansions = ed->prev;
5107 nasm_free(ed);
5110 if ((e->type == EXP_REP) ||
5111 (e->type == EXP_MMACRO) ||
5112 (e->type == EXP_WHILE)) {
5113 list->downlevel(LIST_MACRO);
5116 nasm_free(e);
5117 continue;
5122 * Read in line from input and tokenize
5124 line = read_line();
5125 if (line) { /* from the current input file */
5126 line = prepreproc(line);
5127 tline = tokenize(line);
5128 nasm_free(line);
5129 break;
5133 * The current file has ended; work down the istk
5136 Include *i = istk;
5137 fclose(i->fp);
5138 if (i->expansion != NULL) {
5139 error(ERR_FATAL,
5140 "end of file while still in an expansion");
5142 /* only set line and file name if there's a next node */
5143 if (i->next) {
5144 src_set_linnum(i->lineno);
5145 nasm_free(src_set_fname(i->fname));
5147 if ((i->next == NULL) && (finals != NULL)) {
5148 in_final = true;
5149 ExpInv *ei = new_ExpInv();
5150 ei->type = EXP_FINAL;
5151 ei->emitting = true;
5152 ei->current = finals;
5153 istk->expansion = ei;
5154 finals = NULL;
5155 continue;
5157 istk = i->next;
5158 list->downlevel(LIST_INCLUDE);
5159 nasm_free(i);
5160 if (istk == NULL) {
5161 if (finals != NULL) {
5162 in_final = true;
5163 } else {
5164 return NULL;
5167 continue;
5171 if (defining == NULL) {
5172 tline = expand_mmac_params(tline);
5176 * Check the line to see if it's a preprocessor directive.
5178 if (do_directive(tline) == DIRECTIVE_FOUND) {
5179 continue;
5180 } else if (defining != NULL) {
5182 * We're defining an expansion. We emit nothing at all,
5183 * and just shove the tokenized line on to the definition.
5185 if (defining->ignoring == false) {
5186 Line *l = new_Line();
5187 l->first = tline;
5188 if (defining->line == NULL) {
5189 defining->line = l;
5190 defining->last = l;
5191 } else {
5192 defining->last->next = l;
5193 defining->last = l;
5195 } else {
5196 //free_tlist(tline); /***** sanity check: is this supposed to be here? *****/
5198 continue;
5199 } else if ((istk->expansion != NULL) &&
5200 (istk->expansion->emitting != true)) {
5202 * We're in a non-emitting branch of an expansion.
5203 * Emit nothing at all, not even a blank line: when we
5204 * emerge from the expansion we'll give a line-number
5205 * directive so we keep our place correctly.
5207 free_tlist(tline);
5208 continue;
5209 } else {
5210 tline = expand_smacro(tline);
5211 if (!expand_mmacro(tline)) {
5213 * De-tokenize the line again, and emit it.
5215 line = detoken(tline, true);
5216 free_tlist(tline);
5217 break;
5218 } else {
5219 continue; /* expand_mmacro calls free_tlist */
5223 return line;
5226 static void pp_cleanup(int pass)
5228 if (defining != NULL) {
5229 error(ERR_NONFATAL, "end of file while still defining an expansion");
5230 nasm_free(defining); /***** todo: free everything to avoid mem leaks *****/
5231 defining = NULL;
5233 while (cstk != NULL)
5234 ctx_pop();
5235 free_macros();
5236 while (istk != NULL) {
5237 Include *i = istk;
5238 istk = istk->next;
5239 fclose(i->fp);
5240 nasm_free(i->fname);
5241 nasm_free(i);
5243 while (cstk)
5244 ctx_pop();
5245 nasm_free(src_set_fname(NULL));
5246 if (pass == 0) {
5247 IncPath *i;
5248 free_llist(predef);
5249 delete_Blocks();
5250 while ((i = ipath)) {
5251 ipath = i->next;
5252 if (i->path)
5253 nasm_free(i->path);
5254 nasm_free(i);
5259 void pp_include_path(char *path)
5261 IncPath *i;
5263 i = nasm_malloc(sizeof(IncPath));
5264 i->path = path ? nasm_strdup(path) : NULL;
5265 i->next = NULL;
5267 if (ipath) {
5268 IncPath *j = ipath;
5269 while (j->next)
5270 j = j->next;
5271 j->next = i;
5272 } else {
5273 ipath = i;
5277 void pp_pre_include(char *fname)
5279 Token *inc, *space, *name;
5280 Line *l;
5282 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
5283 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
5284 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
5286 l = new_Line();
5287 l->next = predef;
5288 l->first = inc;
5289 predef = l;
5292 void pp_pre_define(char *definition)
5294 Token *def, *space;
5295 Line *l;
5296 char *equals;
5298 equals = strchr(definition, '=');
5299 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5300 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
5301 if (equals)
5302 *equals = ' ';
5303 space->next = tokenize(definition);
5304 if (equals)
5305 *equals = '=';
5307 l = new_Line();
5308 l->next = predef;
5309 l->first = def;
5310 predef = l;
5313 void pp_pre_undefine(char *definition)
5315 Token *def, *space;
5316 Line *l;
5318 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
5319 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
5320 space->next = tokenize(definition);
5322 l = new_Line();
5323 l->next = predef;
5324 l->first = def;
5325 predef = l;
5329 * This function is used to assist with "runtime" preprocessor
5330 * directives, e.g. pp_runtime("%define __BITS__ 64");
5332 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5333 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5336 void pp_runtime(char *definition)
5338 Token *def;
5340 def = tokenize(definition);
5341 if (do_directive(def) == NO_DIRECTIVE_FOUND)
5342 free_tlist(def);
5346 void pp_extra_stdmac(macros_t *macros)
5348 extrastdmac = macros;
5351 static void make_tok_num(Token * tok, int64_t val)
5353 char numbuf[20];
5354 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
5355 tok->text = nasm_strdup(numbuf);
5356 tok->type = TOK_NUMBER;
5359 Preproc nasmpp = {
5360 pp_reset,
5361 pp_getline,
5362 pp_cleanup