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
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
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
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
84 typedef struct SMacro SMacro;
85 typedef struct MMacro MMacro;
86 typedef struct MMacroInvocation MMacroInvocation;
87 typedef struct Context Context;
88 typedef struct Token Token;
89 typedef struct Blocks Blocks;
90 typedef struct Line Line;
91 typedef struct Include Include;
92 typedef struct Cond Cond;
93 typedef struct IncPath IncPath;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
117 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
135 MMacroInvocation *prev; /* previous invocation */
137 int nparam_min, nparam_max;
139 bool plus; /* is the last parameter greedy? */
140 bool nolist; /* is this macro listing-inhibited? */
141 int64_t in_progress; /* is this macro currently being expanded? */
142 int32_t max_depth; /* maximum number of recursive expansions allowed */
143 Token *dlist; /* All defaults as one list */
144 Token **defaults; /* Parameter default pointers */
145 int ndefs; /* number of default parameters */
149 MMacro *rep_nest; /* used for nesting %rep */
150 Token **params; /* actual parameters */
151 Token *iline; /* invocation line */
152 unsigned int nparam, rotate;
155 int lineno; /* Current line number on expansion */
156 uint64_t condcnt; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation {
164 MMacroInvocation *prev; /* previous invocation */
165 Token **params; /* actual parameters */
166 Token *iline; /* invocation line */
167 unsigned int nparam, rotate;
175 * The context stack is composed of a linked list of these.
180 struct hash_table localmac;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
204 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
205 TOK_PREPROC_ID, TOK_STRING,
206 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
208 TOK_PREPROC_Q, TOK_PREPROC_QQ,
210 TOK_INDIRECT, /* %[...] */
211 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
219 SMacro *mac; /* associated macro for TOK_SMAC_END */
220 size_t len; /* scratch length field */
221 } a; /* Auxiliary data */
222 enum pp_token_type type;
226 * Multi-line macro definitions are stored as a linked list of
227 * these, which is essentially a container to allow several linked
230 * Note that in this module, linked lists are treated as stacks
231 * wherever possible. For this reason, Lines are _pushed_ on to the
232 * `expansion' field in MMacro structures, so that the linked list,
233 * if walked, would give the macro lines in reverse order; this
234 * means that we can walk the list when expanding a macro, and thus
235 * push the lines on to the `expansion' field in _istk_ in reverse
236 * order (so that when popped back off they are in the right
237 * order). It may seem cockeyed, and it relies on my design having
238 * an even number of steps in, but it works...
240 * Some of these structures, rather than being actual lines, are
241 * markers delimiting the end of the expansion of a given macro.
242 * This is for use in the cycle-tracking and %rep-handling code.
243 * Such structures have `finishes' non-NULL, and `first' NULL. All
244 * others have `finishes' NULL, but `first' may still be NULL if
254 * To handle an arbitrary level of file inclusion, we maintain a
255 * stack (ie linked list) of these things.
264 MMacro *mstk; /* stack of active macros/reps */
268 * Include search path. This is simply a list of strings which get
269 * prepended, in turn, to the name of an include file, in an
270 * attempt to find the file if it's not in the current directory.
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.)
290 * These states are for use just after %if or %elif: IF_TRUE
291 * means the condition has evaluated to truth so we are
292 * currently emitting, whereas IF_FALSE means we are not
293 * currently emitting but will start doing so if a %else comes
294 * up. In these states, all directives are admissible: %elif,
295 * %else and %endif. (And of course %if.)
297 COND_IF_TRUE, COND_IF_FALSE,
299 * These states come up after a %else: ELSE_TRUE means we're
300 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
301 * any %elif or %else will cause an error.
303 COND_ELSE_TRUE, COND_ELSE_FALSE,
305 * These states mean that we're not emitting now, and also that
306 * nothing until %endif will be emitted at all. COND_DONE is
307 * used when we've had our moment of emission
308 * and have now started seeing %elifs. COND_NEVER is used when
309 * the condition construct in question is contained within a
310 * non-emitting branch of a larger condition construct,
311 * or if there is an error.
313 COND_DONE, COND_NEVER
315 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
318 * These defines are used as the possible return values for do_directive
320 #define NO_DIRECTIVE_FOUND 0
321 #define DIRECTIVE_FOUND 1
324 * This define sets the upper limit for smacro and recursive mmacro
327 #define DEADMAN_LIMIT (1 << 20)
330 * Condition codes. Note that we use c_ prefix not C_ because C_ is
331 * used in nasm.h for the "real" condition codes. At _this_ level,
332 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
333 * ones, so we need a different enum...
335 static const char * const conditions[] = {
336 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
337 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
338 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
341 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
342 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
343 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
346 static const enum pp_conds inverse_ccs[] = {
347 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
348 c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
349 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
355 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
356 static int is_condition(enum preproc_token arg)
358 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
361 /* For TASM compatibility we need to be able to recognise TASM compatible
362 * conditional compilation directives. Using the NASM pre-processor does
363 * not work, so we look for them specifically from the following list and
364 * then jam in the equivalent NASM directive into the input stream.
368 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
369 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
372 static const char * const tasm_directives[] = {
373 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
374 "ifndef", "include", "local"
377 static int StackSize = 4;
378 static char *StackPointer = "ebp";
379 static int ArgOffset = 8;
380 static int LocalOffset = 0;
382 static Context *cstk;
383 static Include *istk;
384 static IncPath *ipath = NULL;
386 static int pass; /* HACK: pass 0 = generate dependencies only */
387 static StrList **dephead, **deptail; /* Dependency list */
389 static uint64_t unique; /* unique identifier numbers */
391 static Line *predef = NULL;
392 static bool do_predef;
394 static ListGen *list;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro *defining;
412 static uint64_t nested_mac_count;
413 static uint64_t nested_rep_count;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t *stdmacpos;
427 * The extra standard macros that come from the object format, if
430 static macros_t *extrastdmac = NULL;
431 static bool any_extrastdmac;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token *freeTokens = NULL;
443 static Blocks blocks = { NULL, NULL };
446 * Forward declarations.
448 static Token *expand_mmac_params(Token * tline);
449 static Token *expand_smacro(Token * tline);
450 static Token *expand_id(Token * tline);
451 static Context *get_ctx(const char *name, const char **namep,
453 static void make_tok_num(Token * tok, int64_t val);
454 static void error(int severity, const char *fmt, ...);
455 static void error_precond(int severity, const char *fmt, ...);
456 static void *new_Block(size_t size);
457 static void delete_Blocks(void);
458 static Token *new_Token(Token * next, enum pp_token_type type,
459 const char *text, int txtlen);
460 static Token *delete_Token(Token * t);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * Handle TASM specific directives, which do not contain a % in
472 * front of them. We do it here because I could not find any other
473 * place to do it for the moment, and it is a hack (ideally it would
474 * be nice to be able to use the NASM pre-processor to do it).
476 static char *check_tasm_directive(char *line)
478 int32_t i, j, k, m, len;
479 char *p, *q, *oldline, oldchar;
481 p = nasm_skip_spaces(line);
483 /* Binary search for the directive name */
485 j = elements(tasm_directives);
486 q = nasm_skip_word(p);
493 m = nasm_stricmp(p, tasm_directives[k]);
495 /* We have found a directive, so jam a % in front of it
496 * so that NASM will then recognise it as one if it's own.
501 line = nasm_malloc(len + 2);
503 if (k == TM_IFDIFI) {
505 * NASM does not recognise IFDIFI, so we convert
506 * it to %if 0. This is not used in NASM
507 * compatible code, but does need to parse for the
508 * TASM macro package.
510 strcpy(line + 1, "if 0");
512 memcpy(line + 1, p, len + 1);
527 * The pre-preprocessing stage... This function translates line
528 * number indications as they emerge from GNU cpp (`# lineno "file"
529 * flags') into NASM preprocessor line number indications (`%line
532 static char *prepreproc(char *line)
535 char *fname, *oldline;
537 if (line[0] == '#' && line[1] == ' ') {
540 lineno = atoi(fname);
541 fname += strspn(fname, "0123456789 ");
544 fnlen = strcspn(fname, "\"");
545 line = nasm_malloc(20 + fnlen);
546 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
549 if (tasm_compatible_mode)
550 return check_tasm_directive(line);
555 * Free a linked list of tokens.
557 static void free_tlist(Token * list)
560 list = delete_Token(list);
565 * Free a linked list of lines.
567 static void free_llist(Line * list)
573 free_tlist(l->first);
581 static void free_mmacro(MMacro * m)
584 free_tlist(m->dlist);
585 nasm_free(m->defaults);
586 free_llist(m->expansion);
591 * Free all currently defined macros, and free the hash tables
593 static void free_smacro_table(struct hash_table *smt)
597 struct hash_tbl_node *it = NULL;
599 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
600 nasm_free((void *)key);
602 SMacro *ns = s->next;
604 free_tlist(s->expansion);
612 static void free_mmacro_table(struct hash_table *mmt)
616 struct hash_tbl_node *it = NULL;
619 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
620 nasm_free((void *)key);
622 MMacro *nm = m->next;
630 static void free_macros(void)
632 free_smacro_table(&smacros);
633 free_mmacro_table(&mmacros);
637 * Initialize the hash tables
639 static void init_macros(void)
641 hash_init(&smacros, HASH_LARGE);
642 hash_init(&mmacros, HASH_LARGE);
646 * Pop the context stack.
648 static void ctx_pop(void)
653 free_smacro_table(&c->localmac);
659 * Search for a key in the hash index; adding it if necessary
660 * (in which case we initialize the data pointer to NULL.)
663 hash_findi_add(struct hash_table *hash, const char *str)
665 struct hash_insert hi;
669 r = hash_findi(hash, str, &hi);
673 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
674 return hash_add(&hi, strx, NULL);
678 * Like hash_findi, but returns the data element rather than a pointer
679 * to it. Used only when not adding a new element, hence no third
683 hash_findix(struct hash_table *hash, const char *str)
687 p = hash_findi(hash, str, NULL);
688 return p ? *p : NULL;
691 #define BUF_DELTA 512
693 * Read a line from the top file in istk, handling multiple CR/LFs
694 * at the end of the line read, and handling spurious ^Zs. Will
695 * return lines from the standard macro set if this has not already
698 static char *read_line(void)
700 char *buffer, *p, *q;
701 int bufsize, continued_count;
705 const unsigned char *p = stdmacpos;
710 len += pp_directives_len[c-0x80]+1;
714 ret = nasm_malloc(len+1);
716 while ((c = *stdmacpos++)) {
718 memcpy(q, pp_directives[c-0x80], pp_directives_len[c-0x80]);
719 q += pp_directives_len[c-0x80];
729 /* This was the last of the standard macro chain... */
731 if (any_extrastdmac) {
732 stdmacpos = extrastdmac;
733 any_extrastdmac = false;
734 } else if (do_predef) {
736 Token *head, **tail, *t;
739 * Nasty hack: here we push the contents of
740 * `predef' on to the top-level expansion stack,
741 * since this is the most convenient way to
742 * implement the pre-include and pre-define
745 for (pd = predef; pd; pd = pd->next) {
748 for (t = pd->first; t; t = t->next) {
749 *tail = new_Token(NULL, t->type, t->text, 0);
750 tail = &(*tail)->next;
752 l = nasm_malloc(sizeof(Line));
753 l->next = istk->expansion;
765 buffer = nasm_malloc(BUF_DELTA);
769 q = fgets(p, bufsize - (p - buffer), istk->fp);
773 if (p > buffer && p[-1] == '\n') {
775 * Convert backslash-CRLF line continuation sequences into
776 * nothing at all (for DOS and Windows)
778 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
784 * Also convert backslash-LF line continuation sequences into
785 * nothing at all (for Unix)
787 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
795 if (p - buffer > bufsize - 10) {
796 int32_t offset = p - buffer;
797 bufsize += BUF_DELTA;
798 buffer = nasm_realloc(buffer, bufsize);
799 p = buffer + offset; /* prevent stale-pointer problems */
803 if (!q && p == buffer) {
808 src_set_linnum(src_get_linnum() + istk->lineinc +
809 (continued_count * istk->lineinc));
812 * Play safe: remove CRs as well as LFs, if any of either are
813 * present at the end of the line.
815 while (--p >= buffer && (*p == '\n' || *p == '\r'))
819 * Handle spurious ^Z, which may be inserted into source files
820 * by some file transfer utilities.
822 buffer[strcspn(buffer, "\032")] = '\0';
824 list->line(LIST_READ, buffer);
830 * Tokenize a line of text. This is a very simple process since we
831 * don't need to parse the value out of e.g. numeric tokens: we
832 * simply split one string into many.
834 static Token *tokenize(char *line)
837 enum pp_token_type type;
839 Token *t, **tail = &list;
845 if (*p == '+' && !nasm_isdigit(p[1])) {
848 } else if (nasm_isdigit(*p) ||
849 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
853 while (nasm_isdigit(*p));
854 type = TOK_PREPROC_ID;
855 } else if (*p == '{') {
857 while (*p && *p != '}') {
864 type = TOK_PREPROC_ID;
865 } else if (*p == '[') {
867 line += 2; /* Skip the leading %[ */
869 while (lvl && (c = *p++)) {
881 p = nasm_skip_string(p)+1;
891 error(ERR_NONFATAL, "unterminated %[ construct");
893 } else if (*p == '?') {
894 type = TOK_PREPROC_Q; /* %? */
897 type = TOK_PREPROC_QQ; /* %?? */
900 } else if (isidchar(*p) ||
901 ((*p == '!' || *p == '%' || *p == '$') &&
906 while (isidchar(*p));
907 type = TOK_PREPROC_ID;
913 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
916 while (*p && isidchar(*p))
918 } else if (*p == '\'' || *p == '"' || *p == '`') {
923 p = nasm_skip_string(p);
928 error(ERR_WARNING|ERR_PASS1, "unterminated string");
929 /* Handling unterminated strings by UNV */
932 } else if (p[0] == '$' && p[1] == '$') {
933 type = TOK_OTHER; /* TOKEN_BASE */
935 } else if (isnumstart(*p)) {
937 bool is_float = false;
953 if (!is_hex && (c == 'e' || c == 'E')) {
955 if (*p == '+' || *p == '-') {
957 * e can only be followed by +/- if it is either a
958 * prefixed hex number or a floating-point number
963 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
965 } else if (c == 'P' || c == 'p') {
967 if (*p == '+' || *p == '-')
969 } else if (isnumchar(c) || c == '_')
973 * we need to deal with consequences of the legacy
974 * parser, like "1.nolist" being two tokens
975 * (TOK_NUMBER, TOK_ID) here; at least give it
976 * a shot for now. In the future, we probably need
977 * a flex-based scanner with proper pattern matching
978 * to do it as well as it can be done. Nothing in
979 * the world is going to help the person who wants
980 * 0x123.p16 interpreted as two tokens, though.
986 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
987 (!is_hex && (*r == 'e' || *r == 'E')) ||
988 (*r == 'p' || *r == 'P')) {
992 break; /* Terminate the token */
996 p--; /* Point to first character beyond number */
998 if (p == line+1 && *line == '$') {
999 type = TOK_OTHER; /* TOKEN_HERE */
1001 if (has_e && !is_hex) {
1002 /* 1e13 is floating-point, but 1e13h is not */
1006 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1008 } else if (nasm_isspace(*p)) {
1009 type = TOK_WHITESPACE;
1010 p = nasm_skip_spaces(p);
1012 * Whitespace just before end-of-line is discarded by
1013 * pretending it's a comment; whitespace just before a
1014 * comment gets lumped into the comment.
1016 if (!*p || *p == ';') {
1021 } else if (*p == ';') {
1027 * Anything else is an operator of some kind. We check
1028 * for all the double-character operators (>>, <<, //,
1029 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1030 * else is a single-character operator.
1033 if ((p[0] == '>' && p[1] == '>') ||
1034 (p[0] == '<' && p[1] == '<') ||
1035 (p[0] == '/' && p[1] == '/') ||
1036 (p[0] == '<' && p[1] == '=') ||
1037 (p[0] == '>' && p[1] == '=') ||
1038 (p[0] == '=' && p[1] == '=') ||
1039 (p[0] == '!' && p[1] == '=') ||
1040 (p[0] == '<' && p[1] == '>') ||
1041 (p[0] == '&' && p[1] == '&') ||
1042 (p[0] == '|' && p[1] == '|') ||
1043 (p[0] == '^' && p[1] == '^')) {
1049 /* Handling unterminated string by UNV */
1052 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1053 t->text[p-line] = *line;
1057 if (type != TOK_COMMENT) {
1058 *tail = t = new_Token(NULL, type, line, p - line);
1067 * this function allocates a new managed block of memory and
1068 * returns a pointer to the block. The managed blocks are
1069 * deleted only all at once by the delete_Blocks function.
1071 static void *new_Block(size_t size)
1073 Blocks *b = &blocks;
1075 /* first, get to the end of the linked list */
1078 /* now allocate the requested chunk */
1079 b->chunk = nasm_malloc(size);
1081 /* now allocate a new block for the next request */
1082 b->next = nasm_malloc(sizeof(Blocks));
1083 /* and initialize the contents of the new block */
1084 b->next->next = NULL;
1085 b->next->chunk = NULL;
1090 * this function deletes all managed blocks of memory
1092 static void delete_Blocks(void)
1094 Blocks *a, *b = &blocks;
1097 * keep in mind that the first block, pointed to by blocks
1098 * is a static and not dynamically allocated, so we don't
1103 nasm_free(b->chunk);
1112 * this function creates a new Token and passes a pointer to it
1113 * back to the caller. It sets the type and text elements, and
1114 * also the a.mac and next elements to NULL.
1116 static Token *new_Token(Token * next, enum pp_token_type type,
1117 const char *text, int txtlen)
1123 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1124 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1125 freeTokens[i].next = &freeTokens[i + 1];
1126 freeTokens[i].next = NULL;
1129 freeTokens = t->next;
1133 if (type == TOK_WHITESPACE || !text) {
1137 txtlen = strlen(text);
1138 t->text = nasm_malloc(txtlen+1);
1139 memcpy(t->text, text, txtlen);
1140 t->text[txtlen] = '\0';
1145 static Token *delete_Token(Token * t)
1147 Token *next = t->next;
1149 t->next = freeTokens;
1155 * Convert a line of tokens back into text.
1156 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1157 * will be transformed into ..@ctxnum.xxx
1159 static char *detoken(Token * tlist, bool expand_locals)
1167 for (t = tlist; t; t = t->next) {
1168 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1169 char *p = getenv(t->text + 2);
1172 t->text = nasm_strdup(p);
1176 /* Expand local macros here and not during preprocessing */
1177 if (expand_locals &&
1178 t->type == TOK_PREPROC_ID && t->text &&
1179 t->text[0] == '%' && t->text[1] == '$') {
1182 Context *ctx = get_ctx(t->text, &q, false);
1185 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1186 p = nasm_strcat(buffer, q);
1191 if (t->type == TOK_WHITESPACE) {
1193 } else if (t->text) {
1194 len += strlen(t->text);
1197 p = line = nasm_malloc(len + 1);
1198 for (t = tlist; t; t = t->next) {
1199 if (t->type == TOK_WHITESPACE) {
1201 } else if (t->text) {
1212 * A scanner, suitable for use by the expression evaluator, which
1213 * operates on a line of Tokens. Expects a pointer to a pointer to
1214 * the first token in the line to be passed in as its private_data
1217 * FIX: This really needs to be unified with stdscan.
1219 static int ppscan(void *private_data, struct tokenval *tokval)
1221 Token **tlineptr = private_data;
1223 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1227 *tlineptr = tline ? tline->next : NULL;
1229 while (tline && (tline->type == TOK_WHITESPACE ||
1230 tline->type == TOK_COMMENT));
1233 return tokval->t_type = TOKEN_EOS;
1235 tokval->t_charptr = tline->text;
1237 if (tline->text[0] == '$' && !tline->text[1])
1238 return tokval->t_type = TOKEN_HERE;
1239 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1240 return tokval->t_type = TOKEN_BASE;
1242 if (tline->type == TOK_ID) {
1243 p = tokval->t_charptr = tline->text;
1245 tokval->t_charptr++;
1246 return tokval->t_type = TOKEN_ID;
1249 for (r = p, s = ourcopy; *r; r++) {
1250 if (r >= p+MAX_KEYWORD)
1251 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1252 *s++ = nasm_tolower(*r);
1255 /* right, so we have an identifier sitting in temp storage. now,
1256 * is it actually a register or instruction name, or what? */
1257 return nasm_token_hash(ourcopy, tokval);
1260 if (tline->type == TOK_NUMBER) {
1262 tokval->t_integer = readnum(tline->text, &rn_error);
1263 tokval->t_charptr = tline->text;
1265 return tokval->t_type = TOKEN_ERRNUM;
1267 return tokval->t_type = TOKEN_NUM;
1270 if (tline->type == TOK_FLOAT) {
1271 return tokval->t_type = TOKEN_FLOAT;
1274 if (tline->type == TOK_STRING) {
1277 bq = tline->text[0];
1278 tokval->t_charptr = tline->text;
1279 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1281 if (ep[0] != bq || ep[1] != '\0')
1282 return tokval->t_type = TOKEN_ERRSTR;
1284 return tokval->t_type = TOKEN_STR;
1287 if (tline->type == TOK_OTHER) {
1288 if (!strcmp(tline->text, "<<"))
1289 return tokval->t_type = TOKEN_SHL;
1290 if (!strcmp(tline->text, ">>"))
1291 return tokval->t_type = TOKEN_SHR;
1292 if (!strcmp(tline->text, "//"))
1293 return tokval->t_type = TOKEN_SDIV;
1294 if (!strcmp(tline->text, "%%"))
1295 return tokval->t_type = TOKEN_SMOD;
1296 if (!strcmp(tline->text, "=="))
1297 return tokval->t_type = TOKEN_EQ;
1298 if (!strcmp(tline->text, "<>"))
1299 return tokval->t_type = TOKEN_NE;
1300 if (!strcmp(tline->text, "!="))
1301 return tokval->t_type = TOKEN_NE;
1302 if (!strcmp(tline->text, "<="))
1303 return tokval->t_type = TOKEN_LE;
1304 if (!strcmp(tline->text, ">="))
1305 return tokval->t_type = TOKEN_GE;
1306 if (!strcmp(tline->text, "&&"))
1307 return tokval->t_type = TOKEN_DBL_AND;
1308 if (!strcmp(tline->text, "^^"))
1309 return tokval->t_type = TOKEN_DBL_XOR;
1310 if (!strcmp(tline->text, "||"))
1311 return tokval->t_type = TOKEN_DBL_OR;
1315 * We have no other options: just return the first character of
1318 return tokval->t_type = tline->text[0];
1322 * Compare a string to the name of an existing macro; this is a
1323 * simple wrapper which calls either strcmp or nasm_stricmp
1324 * depending on the value of the `casesense' parameter.
1326 static int mstrcmp(const char *p, const char *q, bool casesense)
1328 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1332 * Compare a string to the name of an existing macro; this is a
1333 * simple wrapper which calls either strcmp or nasm_stricmp
1334 * depending on the value of the `casesense' parameter.
1336 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1338 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1342 * Return the Context structure associated with a %$ token. Return
1343 * NULL, having _already_ reported an error condition, if the
1344 * context stack isn't deep enough for the supplied number of $
1346 * If all_contexts == true, contexts that enclose current are
1347 * also scanned for such smacro, until it is found; if not -
1348 * only the context that directly results from the number of $'s
1349 * in variable's name.
1351 * If "namep" is non-NULL, set it to the pointer to the macro name
1352 * tail, i.e. the part beyond %$...
1354 static Context *get_ctx(const char *name, const char **namep,
1364 if (!name || name[0] != '%' || name[1] != '$')
1368 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1375 while (ctx && *name == '$') {
1381 error(ERR_NONFATAL, "`%s': context stack is only"
1382 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1393 /* Search for this smacro in found context */
1394 m = hash_findix(&ctx->localmac, name);
1396 if (!mstrcmp(m->name, name, m->casesense))
1407 * Check to see if a file is already in a string list
1409 static bool in_list(const StrList *list, const char *str)
1412 if (!strcmp(list->str, str))
1420 * Open an include file. This routine must always return a valid
1421 * file pointer if it returns - it's responsible for throwing an
1422 * ERR_FATAL and bombing out completely if not. It should also try
1423 * the include path one by one until it finds the file or reaches
1424 * the end of the path.
1426 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1431 IncPath *ip = ipath;
1432 int len = strlen(file);
1433 size_t prefix_len = 0;
1437 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1438 memcpy(sl->str, prefix, prefix_len);
1439 memcpy(sl->str+prefix_len, file, len+1);
1440 fp = fopen(sl->str, "r");
1441 if (fp && dhead && !in_list(*dhead, sl->str)) {
1459 prefix_len = strlen(prefix);
1461 /* -MG given and file not found */
1462 if (dhead && !in_list(*dhead, file)) {
1463 sl = nasm_malloc(len+1+sizeof sl->next);
1465 strcpy(sl->str, file);
1473 error(ERR_FATAL, "unable to open include file `%s'", file);
1478 * Determine if we should warn on defining a single-line macro of
1479 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1480 * return true if _any_ single-line macro of that name is defined.
1481 * Otherwise, will return true if a single-line macro with either
1482 * `nparam' or no parameters is defined.
1484 * If a macro with precisely the right number of parameters is
1485 * defined, or nparam is -1, the address of the definition structure
1486 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1487 * is NULL, no action will be taken regarding its contents, and no
1490 * Note that this is also called with nparam zero to resolve
1493 * If you already know which context macro belongs to, you can pass
1494 * the context pointer as first parameter; if you won't but name begins
1495 * with %$ the context will be automatically computed. If all_contexts
1496 * is true, macro will be searched in outer contexts as well.
1499 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1502 struct hash_table *smtbl;
1506 smtbl = &ctx->localmac;
1507 } else if (name[0] == '%' && name[1] == '$') {
1509 ctx = get_ctx(name, &name, false);
1511 return false; /* got to return _something_ */
1512 smtbl = &ctx->localmac;
1516 m = (SMacro *) hash_findix(smtbl, name);
1519 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1520 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1522 if (nparam == (int) m->nparam || nparam == -1)
1536 * Count and mark off the parameters in a multi-line macro call.
1537 * This is called both from within the multi-line macro expansion
1538 * code, and also to mark off the default parameters when provided
1539 * in a %macro definition line.
1541 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1543 int paramsize, brace;
1545 *nparam = paramsize = 0;
1548 /* +1: we need space for the final NULL */
1549 if (*nparam+1 >= paramsize) {
1550 paramsize += PARAM_DELTA;
1551 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1555 if (tok_is_(t, "{"))
1557 (*params)[(*nparam)++] = t;
1558 while (tok_isnt_(t, brace ? "}" : ","))
1560 if (t) { /* got a comma/brace */
1564 * Now we've found the closing brace, look further
1568 if (tok_isnt_(t, ",")) {
1570 "braces do not enclose all of macro parameter");
1571 while (tok_isnt_(t, ","))
1575 t = t->next; /* eat the comma */
1582 * Determine whether one of the various `if' conditions is true or
1585 * We must free the tline we get passed.
1587 static bool if_condition(Token * tline, enum preproc_token ct)
1589 enum pp_conditional i = PP_COND(ct);
1591 Token *t, *tt, **tptr, *origline;
1592 struct tokenval tokval;
1594 enum pp_token_type needtype;
1600 j = false; /* have we matched yet? */
1605 if (tline->type != TOK_ID) {
1607 "`%s' expects context identifiers", pp_directives[ct]);
1608 free_tlist(origline);
1611 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1613 tline = tline->next;
1618 j = false; /* have we matched yet? */
1621 if (!tline || (tline->type != TOK_ID &&
1622 (tline->type != TOK_PREPROC_ID ||
1623 tline->text[1] != '$'))) {
1625 "`%s' expects macro identifiers", pp_directives[ct]);
1628 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1630 tline = tline->next;
1636 tline = expand_smacro(tline);
1638 while (tok_isnt_(tt, ","))
1642 "`%s' expects two comma-separated arguments",
1647 j = true; /* assume equality unless proved not */
1648 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1649 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1650 error(ERR_NONFATAL, "`%s': more than one comma on line",
1654 if (t->type == TOK_WHITESPACE) {
1658 if (tt->type == TOK_WHITESPACE) {
1662 if (tt->type != t->type) {
1663 j = false; /* found mismatching tokens */
1666 /* When comparing strings, need to unquote them first */
1667 if (t->type == TOK_STRING) {
1668 size_t l1 = nasm_unquote(t->text, NULL);
1669 size_t l2 = nasm_unquote(tt->text, NULL);
1675 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1679 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1680 j = false; /* found mismatching tokens */
1687 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1688 j = false; /* trailing gunk on one end or other */
1694 MMacro searching, *mmac;
1697 tline = expand_id(tline);
1698 if (!tok_type_(tline, TOK_ID)) {
1700 "`%s' expects a macro name", pp_directives[ct]);
1703 searching.name = nasm_strdup(tline->text);
1704 searching.casesense = true;
1705 searching.plus = false;
1706 searching.nolist = false;
1707 searching.in_progress = 0;
1708 searching.max_depth = 0;
1709 searching.rep_nest = NULL;
1710 searching.nparam_min = 0;
1711 searching.nparam_max = INT_MAX;
1712 tline = expand_smacro(tline->next);
1715 } else if (!tok_type_(tline, TOK_NUMBER)) {
1717 "`%s' expects a parameter count or nothing",
1720 searching.nparam_min = searching.nparam_max =
1721 readnum(tline->text, &j);
1724 "unable to parse parameter count `%s'",
1727 if (tline && tok_is_(tline->next, "-")) {
1728 tline = tline->next->next;
1729 if (tok_is_(tline, "*"))
1730 searching.nparam_max = INT_MAX;
1731 else if (!tok_type_(tline, TOK_NUMBER))
1733 "`%s' expects a parameter count after `-'",
1736 searching.nparam_max = readnum(tline->text, &j);
1739 "unable to parse parameter count `%s'",
1741 if (searching.nparam_min > searching.nparam_max)
1743 "minimum parameter count exceeds maximum");
1746 if (tline && tok_is_(tline->next, "+")) {
1747 tline = tline->next;
1748 searching.plus = true;
1750 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1752 if (!strcmp(mmac->name, searching.name) &&
1753 (mmac->nparam_min <= searching.nparam_max
1755 && (searching.nparam_min <= mmac->nparam_max
1762 if (tline && tline->next)
1763 error(ERR_WARNING|ERR_PASS1,
1764 "trailing garbage after %%ifmacro ignored");
1765 nasm_free(searching.name);
1774 needtype = TOK_NUMBER;
1777 needtype = TOK_STRING;
1781 t = tline = expand_smacro(tline);
1783 while (tok_type_(t, TOK_WHITESPACE) ||
1784 (needtype == TOK_NUMBER &&
1785 tok_type_(t, TOK_OTHER) &&
1786 (t->text[0] == '-' || t->text[0] == '+') &&
1790 j = tok_type_(t, needtype);
1794 t = tline = expand_smacro(tline);
1795 while (tok_type_(t, TOK_WHITESPACE))
1800 t = t->next; /* Skip the actual token */
1801 while (tok_type_(t, TOK_WHITESPACE))
1803 j = !t; /* Should be nothing left */
1808 t = tline = expand_smacro(tline);
1809 while (tok_type_(t, TOK_WHITESPACE))
1812 j = !t; /* Should be empty */
1816 t = tline = expand_smacro(tline);
1818 tokval.t_type = TOKEN_INVALID;
1819 evalresult = evaluate(ppscan, tptr, &tokval,
1820 NULL, pass | CRITICAL, error, NULL);
1824 error(ERR_WARNING|ERR_PASS1,
1825 "trailing garbage after expression ignored");
1826 if (!is_simple(evalresult)) {
1828 "non-constant value given to `%s'", pp_directives[ct]);
1831 j = reloc_value(evalresult) != 0;
1836 "preprocessor directive `%s' not yet implemented",
1841 free_tlist(origline);
1842 return j ^ PP_NEGATIVE(ct);
1845 free_tlist(origline);
1850 * Common code for defining an smacro
1852 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1853 int nparam, Token *expansion)
1855 SMacro *smac, **smhead;
1856 struct hash_table *smtbl;
1858 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1860 error(ERR_WARNING|ERR_PASS1,
1861 "single-line macro `%s' defined both with and"
1862 " without parameters", mname);
1864 * Some instances of the old code considered this a failure,
1865 * some others didn't. What is the right thing to do here?
1867 free_tlist(expansion);
1868 return false; /* Failure */
1871 * We're redefining, so we have to take over an
1872 * existing SMacro structure. This means freeing
1873 * what was already in it.
1875 nasm_free(smac->name);
1876 free_tlist(smac->expansion);
1879 smtbl = ctx ? &ctx->localmac : &smacros;
1880 smhead = (SMacro **) hash_findi_add(smtbl, mname);
1881 smac = nasm_malloc(sizeof(SMacro));
1882 smac->next = *smhead;
1885 smac->name = nasm_strdup(mname);
1886 smac->casesense = casesense;
1887 smac->nparam = nparam;
1888 smac->expansion = expansion;
1889 smac->in_progress = false;
1890 return true; /* Success */
1894 * Undefine an smacro
1896 static void undef_smacro(Context *ctx, const char *mname)
1898 SMacro **smhead, *s, **sp;
1899 struct hash_table *smtbl;
1901 smtbl = ctx ? &ctx->localmac : &smacros;
1902 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
1906 * We now have a macro name... go hunt for it.
1909 while ((s = *sp) != NULL) {
1910 if (!mstrcmp(s->name, mname, s->casesense)) {
1913 free_tlist(s->expansion);
1923 * Parse a mmacro specification.
1925 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
1929 tline = tline->next;
1931 tline = expand_id(tline);
1932 if (!tok_type_(tline, TOK_ID)) {
1933 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
1938 def->name = nasm_strdup(tline->text);
1940 def->nolist = false;
1941 def->in_progress = 0;
1942 def->rep_nest = NULL;
1943 def->nparam_min = 0;
1944 def->nparam_max = 0;
1946 tline = expand_smacro(tline->next);
1948 if (!tok_type_(tline, TOK_NUMBER)) {
1949 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
1951 def->nparam_min = def->nparam_max =
1952 readnum(tline->text, &err);
1955 "unable to parse parameter count `%s'", tline->text);
1957 if (tline && tok_is_(tline->next, "-")) {
1958 tline = tline->next->next;
1959 if (tok_is_(tline, "*")) {
1960 def->nparam_max = INT_MAX;
1961 } else if (!tok_type_(tline, TOK_NUMBER)) {
1963 "`%s' expects a parameter count after `-'", directive);
1965 def->nparam_max = readnum(tline->text, &err);
1967 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
1970 if (def->nparam_min > def->nparam_max) {
1971 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
1975 if (tline && tok_is_(tline->next, "+")) {
1976 tline = tline->next;
1979 if (tline && tok_type_(tline->next, TOK_ID) &&
1980 !nasm_stricmp(tline->next->text, ".nolist")) {
1981 tline = tline->next;
1986 * Handle default parameters.
1988 if (tline && tline->next) {
1989 def->dlist = tline->next;
1991 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
1994 def->defaults = NULL;
1996 def->expansion = NULL;
1998 if (def->defaults && def->ndefs > def->nparam_max - def->nparam_min &&
2000 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
2001 "too many default macro parameters");
2008 * Decode a size directive
2010 static int parse_size(const char *str) {
2011 static const char *size_names[] =
2012 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2013 static const int sizes[] =
2014 { 0, 1, 4, 16, 8, 10, 2, 32 };
2016 return sizes[bsii(str, size_names, elements(size_names))+1];
2020 * nasm_unquote with error if the string contains NUL characters.
2021 * If the string contains NUL characters, issue an error and return
2022 * the C len, i.e. truncate at the NUL.
2024 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
2026 size_t len = nasm_unquote(qstr, NULL);
2027 size_t clen = strlen(qstr);
2030 error(ERR_NONFATAL, "NUL character in `%s' directive",
2031 pp_directives[directive]);
2037 * find and process preprocessor directive in passed line
2038 * Find out if a line contains a preprocessor directive, and deal
2041 * If a directive _is_ found, it is the responsibility of this routine
2042 * (and not the caller) to free_tlist() the line.
2044 * @param tline a pointer to the current tokeninzed line linked list
2045 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2048 static int do_directive(Token * tline)
2050 enum preproc_token i;
2063 MMacro *mmac, **mmhead;
2064 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2066 struct tokenval tokval;
2068 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2076 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2077 (tline->text[1] == '%' || tline->text[1] == '$'
2078 || tline->text[1] == '!'))
2079 return NO_DIRECTIVE_FOUND;
2081 i = pp_token_hash(tline->text);
2084 * If we're in a non-emitting branch of a condition construct,
2085 * or walking to the end of an already terminated %rep block,
2086 * we should ignore all directives except for condition
2089 if (((istk->conds && !emitting(istk->conds->state)) ||
2090 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2091 return NO_DIRECTIVE_FOUND;
2095 * If we're defining a macro or reading a %rep block, we should
2096 * ignore all directives except for %macro/%imacro (which nest),
2097 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2098 * If we're in a %rep block, another %rep nests, so should be let through.
2100 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2101 i != PP_RMACRO && i != PP_IRMACRO &&
2102 i != PP_ENDMACRO && i != PP_ENDM &&
2103 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2104 return NO_DIRECTIVE_FOUND;
2108 if (i == PP_MACRO || i == PP_IMACRO ||
2109 i == PP_RMACRO || i == PP_IRMACRO) {
2111 return NO_DIRECTIVE_FOUND;
2112 } else if (nested_mac_count > 0) {
2113 if (i == PP_ENDMACRO) {
2115 return NO_DIRECTIVE_FOUND;
2118 if (!defining->name) {
2121 return NO_DIRECTIVE_FOUND;
2122 } else if (nested_rep_count > 0) {
2123 if (i == PP_ENDREP) {
2125 return NO_DIRECTIVE_FOUND;
2133 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2135 return NO_DIRECTIVE_FOUND; /* didn't get it */
2138 /* Directive to tell NASM what the default stack size is. The
2139 * default is for a 16-bit stack, and this can be overriden with
2142 tline = tline->next;
2143 if (tline && tline->type == TOK_WHITESPACE)
2144 tline = tline->next;
2145 if (!tline || tline->type != TOK_ID) {
2146 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2147 free_tlist(origline);
2148 return DIRECTIVE_FOUND;
2150 if (nasm_stricmp(tline->text, "flat") == 0) {
2151 /* All subsequent ARG directives are for a 32-bit stack */
2153 StackPointer = "ebp";
2156 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2157 /* All subsequent ARG directives are for a 64-bit stack */
2159 StackPointer = "rbp";
2162 } else if (nasm_stricmp(tline->text, "large") == 0) {
2163 /* All subsequent ARG directives are for a 16-bit stack,
2164 * far function call.
2167 StackPointer = "bp";
2170 } else if (nasm_stricmp(tline->text, "small") == 0) {
2171 /* All subsequent ARG directives are for a 16-bit stack,
2172 * far function call. We don't support near functions.
2175 StackPointer = "bp";
2179 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2180 free_tlist(origline);
2181 return DIRECTIVE_FOUND;
2183 free_tlist(origline);
2184 return DIRECTIVE_FOUND;
2187 /* TASM like ARG directive to define arguments to functions, in
2188 * the following form:
2190 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2194 char *arg, directive[256];
2195 int size = StackSize;
2197 /* Find the argument name */
2198 tline = tline->next;
2199 if (tline && tline->type == TOK_WHITESPACE)
2200 tline = tline->next;
2201 if (!tline || tline->type != TOK_ID) {
2202 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2203 free_tlist(origline);
2204 return DIRECTIVE_FOUND;
2208 /* Find the argument size type */
2209 tline = tline->next;
2210 if (!tline || tline->type != TOK_OTHER
2211 || tline->text[0] != ':') {
2213 "Syntax error processing `%%arg' directive");
2214 free_tlist(origline);
2215 return DIRECTIVE_FOUND;
2217 tline = tline->next;
2218 if (!tline || tline->type != TOK_ID) {
2219 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2220 free_tlist(origline);
2221 return DIRECTIVE_FOUND;
2224 /* Allow macro expansion of type parameter */
2225 tt = tokenize(tline->text);
2226 tt = expand_smacro(tt);
2227 size = parse_size(tt->text);
2230 "Invalid size type for `%%arg' missing directive");
2232 free_tlist(origline);
2233 return DIRECTIVE_FOUND;
2237 /* Round up to even stack slots */
2238 size = ALIGN(size, StackSize);
2240 /* Now define the macro for the argument */
2241 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2242 arg, StackPointer, offset);
2243 do_directive(tokenize(directive));
2246 /* Move to the next argument in the list */
2247 tline = tline->next;
2248 if (tline && tline->type == TOK_WHITESPACE)
2249 tline = tline->next;
2250 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2252 free_tlist(origline);
2253 return DIRECTIVE_FOUND;
2256 /* TASM like LOCAL directive to define local variables for a
2257 * function, in the following form:
2259 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2261 * The '= LocalSize' at the end is ignored by NASM, but is
2262 * required by TASM to define the local parameter size (and used
2263 * by the TASM macro package).
2265 offset = LocalOffset;
2267 char *local, directive[256];
2268 int size = StackSize;
2270 /* Find the argument name */
2271 tline = tline->next;
2272 if (tline && tline->type == TOK_WHITESPACE)
2273 tline = tline->next;
2274 if (!tline || tline->type != TOK_ID) {
2276 "`%%local' missing argument parameter");
2277 free_tlist(origline);
2278 return DIRECTIVE_FOUND;
2280 local = tline->text;
2282 /* Find the argument size type */
2283 tline = tline->next;
2284 if (!tline || tline->type != TOK_OTHER
2285 || tline->text[0] != ':') {
2287 "Syntax error processing `%%local' directive");
2288 free_tlist(origline);
2289 return DIRECTIVE_FOUND;
2291 tline = tline->next;
2292 if (!tline || tline->type != TOK_ID) {
2294 "`%%local' missing size type parameter");
2295 free_tlist(origline);
2296 return DIRECTIVE_FOUND;
2299 /* Allow macro expansion of type parameter */
2300 tt = tokenize(tline->text);
2301 tt = expand_smacro(tt);
2302 size = parse_size(tt->text);
2305 "Invalid size type for `%%local' missing directive");
2307 free_tlist(origline);
2308 return DIRECTIVE_FOUND;
2312 /* Round up to even stack slots */
2313 size = ALIGN(size, StackSize);
2315 offset += size; /* Negative offset, increment before */
2317 /* Now define the macro for the argument */
2318 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2319 local, StackPointer, offset);
2320 do_directive(tokenize(directive));
2322 /* Now define the assign to setup the enter_c macro correctly */
2323 snprintf(directive, sizeof(directive),
2324 "%%assign %%$localsize %%$localsize+%d", size);
2325 do_directive(tokenize(directive));
2327 /* Move to the next argument in the list */
2328 tline = tline->next;
2329 if (tline && tline->type == TOK_WHITESPACE)
2330 tline = tline->next;
2331 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2332 LocalOffset = offset;
2333 free_tlist(origline);
2334 return DIRECTIVE_FOUND;
2338 error(ERR_WARNING|ERR_PASS1,
2339 "trailing garbage after `%%clear' ignored");
2342 free_tlist(origline);
2343 return DIRECTIVE_FOUND;
2346 t = tline->next = expand_smacro(tline->next);
2348 if (!t || (t->type != TOK_STRING &&
2349 t->type != TOK_INTERNAL_STRING)) {
2350 error(ERR_NONFATAL, "`%%depend' expects a file name");
2351 free_tlist(origline);
2352 return DIRECTIVE_FOUND; /* but we did _something_ */
2355 error(ERR_WARNING|ERR_PASS1,
2356 "trailing garbage after `%%depend' ignored");
2358 if (t->type != TOK_INTERNAL_STRING)
2359 nasm_unquote_cstr(p, i);
2360 if (dephead && !in_list(*dephead, p)) {
2361 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2365 deptail = &sl->next;
2367 free_tlist(origline);
2368 return DIRECTIVE_FOUND;
2371 t = tline->next = expand_smacro(tline->next);
2374 if (!t || (t->type != TOK_STRING &&
2375 t->type != TOK_INTERNAL_STRING)) {
2376 error(ERR_NONFATAL, "`%%include' expects a file name");
2377 free_tlist(origline);
2378 return DIRECTIVE_FOUND; /* but we did _something_ */
2381 error(ERR_WARNING|ERR_PASS1,
2382 "trailing garbage after `%%include' ignored");
2384 if (t->type != TOK_INTERNAL_STRING)
2385 nasm_unquote_cstr(p, i);
2386 inc = nasm_malloc(sizeof(Include));
2389 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2391 /* -MG given but file not found */
2394 inc->fname = src_set_fname(nasm_strdup(p));
2395 inc->lineno = src_set_linnum(0);
2397 inc->expansion = NULL;
2400 list->uplevel(LIST_INCLUDE);
2402 free_tlist(origline);
2403 return DIRECTIVE_FOUND;
2407 static macros_t *use_pkg;
2408 const char *pkg_macro = NULL;
2410 tline = tline->next;
2412 tline = expand_id(tline);
2414 if (!tline || (tline->type != TOK_STRING &&
2415 tline->type != TOK_INTERNAL_STRING &&
2416 tline->type != TOK_ID)) {
2417 error(ERR_NONFATAL, "`%%use' expects a package name");
2418 free_tlist(origline);
2419 return DIRECTIVE_FOUND; /* but we did _something_ */
2422 error(ERR_WARNING|ERR_PASS1,
2423 "trailing garbage after `%%use' ignored");
2424 if (tline->type == TOK_STRING)
2425 nasm_unquote_cstr(tline->text, i);
2426 use_pkg = nasm_stdmac_find_package(tline->text);
2428 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2430 pkg_macro = (char *)use_pkg + 1; /* The first string will be <%define>__USE_*__ */
2431 if (use_pkg && smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2432 /* Not already included, go ahead and include it */
2433 stdmacpos = use_pkg;
2435 free_tlist(origline);
2436 return DIRECTIVE_FOUND;
2441 tline = tline->next;
2443 tline = expand_id(tline);
2445 if (!tok_type_(tline, TOK_ID)) {
2446 error(ERR_NONFATAL, "`%s' expects a context identifier",
2448 free_tlist(origline);
2449 return DIRECTIVE_FOUND; /* but we did _something_ */
2452 error(ERR_WARNING|ERR_PASS1,
2453 "trailing garbage after `%s' ignored",
2455 p = nasm_strdup(tline->text);
2457 p = NULL; /* Anonymous */
2461 ctx = nasm_malloc(sizeof(Context));
2463 hash_init(&ctx->localmac, HASH_SMALL);
2465 ctx->number = unique++;
2470 error(ERR_NONFATAL, "`%s': context stack is empty",
2472 } else if (i == PP_POP) {
2473 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2474 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2476 cstk->name ? cstk->name : "anonymous", p);
2481 nasm_free(cstk->name);
2487 free_tlist(origline);
2488 return DIRECTIVE_FOUND;
2490 severity = ERR_FATAL;
2493 severity = ERR_NONFATAL;
2496 severity = ERR_WARNING|ERR_WARN_USER;
2501 /* Only error out if this is the final pass */
2502 if (pass != 2 && i != PP_FATAL)
2503 return DIRECTIVE_FOUND;
2505 tline->next = expand_smacro(tline->next);
2506 tline = tline->next;
2508 t = tline ? tline->next : NULL;
2510 if (tok_type_(tline, TOK_STRING) && !t) {
2511 /* The line contains only a quoted string */
2513 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2514 error(severity, "%s", p);
2516 /* Not a quoted string, or more than a quoted string */
2517 p = detoken(tline, false);
2518 error(severity, "%s", p);
2521 free_tlist(origline);
2522 return DIRECTIVE_FOUND;
2526 if (istk->conds && !emitting(istk->conds->state))
2529 j = if_condition(tline->next, i);
2530 tline->next = NULL; /* it got freed */
2531 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2533 cond = nasm_malloc(sizeof(Cond));
2534 cond->next = istk->conds;
2538 istk->mstk->condcnt ++;
2539 free_tlist(origline);
2540 return DIRECTIVE_FOUND;
2544 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2545 switch(istk->conds->state) {
2547 istk->conds->state = COND_DONE;
2554 case COND_ELSE_TRUE:
2555 case COND_ELSE_FALSE:
2556 error_precond(ERR_WARNING|ERR_PASS1,
2557 "`%%elif' after `%%else' ignored");
2558 istk->conds->state = COND_NEVER;
2563 * IMPORTANT: In the case of %if, we will already have
2564 * called expand_mmac_params(); however, if we're
2565 * processing an %elif we must have been in a
2566 * non-emitting mode, which would have inhibited
2567 * the normal invocation of expand_mmac_params().
2568 * Therefore, we have to do it explicitly here.
2570 j = if_condition(expand_mmac_params(tline->next), i);
2571 tline->next = NULL; /* it got freed */
2572 istk->conds->state =
2573 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2576 free_tlist(origline);
2577 return DIRECTIVE_FOUND;
2581 error_precond(ERR_WARNING|ERR_PASS1,
2582 "trailing garbage after `%%else' ignored");
2584 error(ERR_FATAL, "`%%else': no matching `%%if'");
2585 switch(istk->conds->state) {
2588 istk->conds->state = COND_ELSE_FALSE;
2595 istk->conds->state = COND_ELSE_TRUE;
2598 case COND_ELSE_TRUE:
2599 case COND_ELSE_FALSE:
2600 error_precond(ERR_WARNING|ERR_PASS1,
2601 "`%%else' after `%%else' ignored.");
2602 istk->conds->state = COND_NEVER;
2605 free_tlist(origline);
2606 return DIRECTIVE_FOUND;
2610 error_precond(ERR_WARNING|ERR_PASS1,
2611 "trailing garbage after `%%endif' ignored");
2613 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2615 istk->conds = cond->next;
2618 istk->mstk->condcnt --;
2619 free_tlist(origline);
2620 return DIRECTIVE_FOUND;
2627 error(ERR_FATAL, "`%s': already defining a macro",
2629 return DIRECTIVE_FOUND;
2631 defining = nasm_malloc(sizeof(MMacro));
2632 defining->max_depth =
2633 (i == PP_RMACRO) || (i == PP_IRMACRO) ? DEADMAN_LIMIT : 0;
2634 defining->casesense = (i == PP_MACRO) || (i == PP_RMACRO);
2635 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2636 nasm_free(defining);
2638 return DIRECTIVE_FOUND;
2641 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2643 if (!strcmp(mmac->name, defining->name) &&
2644 (mmac->nparam_min <= defining->nparam_max
2646 && (defining->nparam_min <= mmac->nparam_max
2648 error(ERR_WARNING|ERR_PASS1,
2649 "redefining multi-line macro `%s'", defining->name);
2650 return DIRECTIVE_FOUND;
2654 free_tlist(origline);
2655 return DIRECTIVE_FOUND;
2659 if (! (defining && defining->name)) {
2660 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2661 return DIRECTIVE_FOUND;
2663 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2664 defining->next = *mmhead;
2667 free_tlist(origline);
2668 return DIRECTIVE_FOUND;
2672 * We must search along istk->expansion until we hit a
2673 * macro-end marker for a macro with a name. Then we
2674 * bypass all lines between exitmacro and endmacro.
2676 for (l = istk->expansion; l; l = l->next)
2677 if (l->finishes && l->finishes->name)
2682 * Remove all conditional entries relative to this
2683 * macro invocation. (safe to do in this context)
2685 for ( ; l->finishes->condcnt > 0; l->finishes->condcnt --) {
2687 istk->conds = cond->next;
2690 istk->expansion = l;
2692 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2694 free_tlist(origline);
2695 return DIRECTIVE_FOUND;
2703 spec.casesense = (i == PP_UNMACRO);
2704 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2705 return DIRECTIVE_FOUND;
2707 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2708 while (mmac_p && *mmac_p) {
2710 if (mmac->casesense == spec.casesense &&
2711 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2712 mmac->nparam_min == spec.nparam_min &&
2713 mmac->nparam_max == spec.nparam_max &&
2714 mmac->plus == spec.plus) {
2715 *mmac_p = mmac->next;
2718 mmac_p = &mmac->next;
2721 free_tlist(origline);
2722 free_tlist(spec.dlist);
2723 return DIRECTIVE_FOUND;
2727 if (tline->next && tline->next->type == TOK_WHITESPACE)
2728 tline = tline->next;
2730 free_tlist(origline);
2731 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2732 return DIRECTIVE_FOUND;
2734 t = expand_smacro(tline->next);
2736 free_tlist(origline);
2739 tokval.t_type = TOKEN_INVALID;
2741 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2744 return DIRECTIVE_FOUND;
2746 error(ERR_WARNING|ERR_PASS1,
2747 "trailing garbage after expression ignored");
2748 if (!is_simple(evalresult)) {
2749 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2750 return DIRECTIVE_FOUND;
2753 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2754 mmac = mmac->next_active;
2756 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2757 } else if (mmac->nparam == 0) {
2759 "`%%rotate' invoked within macro without parameters");
2761 int rotate = mmac->rotate + reloc_value(evalresult);
2763 rotate %= (int)mmac->nparam;
2765 rotate += mmac->nparam;
2767 mmac->rotate = rotate;
2769 return DIRECTIVE_FOUND;
2774 tline = tline->next;
2775 } while (tok_type_(tline, TOK_WHITESPACE));
2777 if (tok_type_(tline, TOK_ID) &&
2778 nasm_stricmp(tline->text, ".nolist") == 0) {
2781 tline = tline->next;
2782 } while (tok_type_(tline, TOK_WHITESPACE));
2786 t = expand_smacro(tline);
2788 tokval.t_type = TOKEN_INVALID;
2790 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2792 free_tlist(origline);
2793 return DIRECTIVE_FOUND;
2796 error(ERR_WARNING|ERR_PASS1,
2797 "trailing garbage after expression ignored");
2798 if (!is_simple(evalresult)) {
2799 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2800 return DIRECTIVE_FOUND;
2802 count = reloc_value(evalresult) + 1;
2804 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2807 free_tlist(origline);
2809 tmp_defining = defining;
2810 defining = nasm_malloc(sizeof(MMacro));
2811 defining->prev = NULL;
2812 defining->name = NULL; /* flags this macro as a %rep block */
2813 defining->casesense = false;
2814 defining->plus = false;
2815 defining->nolist = nolist;
2816 defining->in_progress = count;
2817 defining->max_depth = 0;
2818 defining->nparam_min = defining->nparam_max = 0;
2819 defining->defaults = NULL;
2820 defining->dlist = NULL;
2821 defining->expansion = NULL;
2822 defining->next_active = istk->mstk;
2823 defining->rep_nest = tmp_defining;
2824 return DIRECTIVE_FOUND;
2827 if (!defining || defining->name) {
2828 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2829 return DIRECTIVE_FOUND;
2833 * Now we have a "macro" defined - although it has no name
2834 * and we won't be entering it in the hash tables - we must
2835 * push a macro-end marker for it on to istk->expansion.
2836 * After that, it will take care of propagating itself (a
2837 * macro-end marker line for a macro which is really a %rep
2838 * block will cause the macro to be re-expanded, complete
2839 * with another macro-end marker to ensure the process
2840 * continues) until the whole expansion is forcibly removed
2841 * from istk->expansion by a %exitrep.
2843 l = nasm_malloc(sizeof(Line));
2844 l->next = istk->expansion;
2845 l->finishes = defining;
2847 istk->expansion = l;
2849 istk->mstk = defining;
2851 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2852 tmp_defining = defining;
2853 defining = defining->rep_nest;
2854 free_tlist(origline);
2855 return DIRECTIVE_FOUND;
2859 * We must search along istk->expansion until we hit a
2860 * macro-end marker for a macro with no name. Then we set
2861 * its `in_progress' flag to 0.
2863 for (l = istk->expansion; l; l = l->next)
2864 if (l->finishes && !l->finishes->name)
2868 l->finishes->in_progress = 1;
2870 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2871 free_tlist(origline);
2872 return DIRECTIVE_FOUND;
2878 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2880 tline = tline->next;
2882 tline = expand_id(tline);
2883 if (!tline || (tline->type != TOK_ID &&
2884 (tline->type != TOK_PREPROC_ID ||
2885 tline->text[1] != '$'))) {
2886 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2888 free_tlist(origline);
2889 return DIRECTIVE_FOUND;
2892 ctx = get_ctx(tline->text, &mname, false);
2894 param_start = tline = tline->next;
2897 /* Expand the macro definition now for %xdefine and %ixdefine */
2898 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2899 tline = expand_smacro(tline);
2901 if (tok_is_(tline, "(")) {
2903 * This macro has parameters.
2906 tline = tline->next;
2910 error(ERR_NONFATAL, "parameter identifier expected");
2911 free_tlist(origline);
2912 return DIRECTIVE_FOUND;
2914 if (tline->type != TOK_ID) {
2916 "`%s': parameter identifier expected",
2918 free_tlist(origline);
2919 return DIRECTIVE_FOUND;
2921 tline->type = TOK_SMAC_PARAM + nparam++;
2922 tline = tline->next;
2924 if (tok_is_(tline, ",")) {
2925 tline = tline->next;
2927 if (!tok_is_(tline, ")")) {
2929 "`)' expected to terminate macro template");
2930 free_tlist(origline);
2931 return DIRECTIVE_FOUND;
2937 tline = tline->next;
2939 if (tok_type_(tline, TOK_WHITESPACE))
2940 last = tline, tline = tline->next;
2945 if (t->type == TOK_ID) {
2946 for (tt = param_start; tt; tt = tt->next)
2947 if (tt->type >= TOK_SMAC_PARAM &&
2948 !strcmp(tt->text, t->text))
2952 t->next = macro_start;
2957 * Good. We now have a macro name, a parameter count, and a
2958 * token list (in reverse order) for an expansion. We ought
2959 * to be OK just to create an SMacro, store it, and let
2960 * free_tlist have the rest of the line (which we have
2961 * carefully re-terminated after chopping off the expansion
2964 define_smacro(ctx, mname, casesense, nparam, macro_start);
2965 free_tlist(origline);
2966 return DIRECTIVE_FOUND;
2969 tline = tline->next;
2971 tline = expand_id(tline);
2972 if (!tline || (tline->type != TOK_ID &&
2973 (tline->type != TOK_PREPROC_ID ||
2974 tline->text[1] != '$'))) {
2975 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2976 free_tlist(origline);
2977 return DIRECTIVE_FOUND;
2980 error(ERR_WARNING|ERR_PASS1,
2981 "trailing garbage after macro name ignored");
2984 /* Find the context that symbol belongs to */
2985 ctx = get_ctx(tline->text, &mname, false);
2986 undef_smacro(ctx, mname);
2987 free_tlist(origline);
2988 return DIRECTIVE_FOUND;
2992 casesense = (i == PP_DEFSTR);
2994 tline = tline->next;
2996 tline = expand_id(tline);
2997 if (!tline || (tline->type != TOK_ID &&
2998 (tline->type != TOK_PREPROC_ID ||
2999 tline->text[1] != '$'))) {
3000 error(ERR_NONFATAL, "`%s' expects a macro identifier",
3002 free_tlist(origline);
3003 return DIRECTIVE_FOUND;
3006 ctx = get_ctx(tline->text, &mname, false);
3008 tline = expand_smacro(tline->next);
3011 while (tok_type_(tline, TOK_WHITESPACE))
3012 tline = delete_Token(tline);
3014 p = detoken(tline, false);
3015 macro_start = nasm_malloc(sizeof(*macro_start));
3016 macro_start->next = NULL;
3017 macro_start->text = nasm_quote(p, strlen(p));
3018 macro_start->type = TOK_STRING;
3019 macro_start->a.mac = NULL;
3023 * We now have a macro name, an implicit parameter count of
3024 * zero, and a string token to use as an expansion. Create
3025 * and store an SMacro.
3027 define_smacro(ctx, mname, casesense, 0, macro_start);
3028 free_tlist(origline);
3029 return DIRECTIVE_FOUND;
3033 casesense = (i == PP_DEFTOK);
3035 tline = tline->next;
3037 tline = expand_id(tline);
3038 if (!tline || (tline->type != TOK_ID &&
3039 (tline->type != TOK_PREPROC_ID ||
3040 tline->text[1] != '$'))) {
3042 "`%s' expects a macro identifier as first parameter",
3044 free_tlist(origline);
3045 return DIRECTIVE_FOUND;
3047 ctx = get_ctx(tline->text, &mname, false);
3049 tline = expand_smacro(tline->next);
3053 while (tok_type_(t, TOK_WHITESPACE))
3055 /* t should now point to the string */
3056 if (t->type != TOK_STRING) {
3058 "`%s` requires string as second parameter",
3061 free_tlist(origline);
3062 return DIRECTIVE_FOUND;
3065 nasm_unquote_cstr(t->text, i);
3066 macro_start = tokenize(t->text);
3069 * We now have a macro name, an implicit parameter count of
3070 * zero, and a numeric token to use as an expansion. Create
3071 * and store an SMacro.
3073 define_smacro(ctx, mname, casesense, 0, macro_start);
3075 free_tlist(origline);
3076 return DIRECTIVE_FOUND;
3081 StrList *xsl = NULL;
3082 StrList **xst = &xsl;
3086 tline = tline->next;
3088 tline = expand_id(tline);
3089 if (!tline || (tline->type != TOK_ID &&
3090 (tline->type != TOK_PREPROC_ID ||
3091 tline->text[1] != '$'))) {
3093 "`%%pathsearch' expects a macro identifier as first parameter");
3094 free_tlist(origline);
3095 return DIRECTIVE_FOUND;
3097 ctx = get_ctx(tline->text, &mname, false);
3099 tline = expand_smacro(tline->next);
3103 while (tok_type_(t, TOK_WHITESPACE))
3106 if (!t || (t->type != TOK_STRING &&
3107 t->type != TOK_INTERNAL_STRING)) {
3108 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3110 free_tlist(origline);
3111 return DIRECTIVE_FOUND; /* but we did _something_ */
3114 error(ERR_WARNING|ERR_PASS1,
3115 "trailing garbage after `%%pathsearch' ignored");
3117 if (t->type != TOK_INTERNAL_STRING)
3118 nasm_unquote(p, NULL);
3120 fp = inc_fopen(p, &xsl, &xst, true);
3123 fclose(fp); /* Don't actually care about the file */
3125 macro_start = nasm_malloc(sizeof(*macro_start));
3126 macro_start->next = NULL;
3127 macro_start->text = nasm_quote(p, strlen(p));
3128 macro_start->type = TOK_STRING;
3129 macro_start->a.mac = NULL;
3134 * We now have a macro name, an implicit parameter count of
3135 * zero, and a string token to use as an expansion. Create
3136 * and store an SMacro.
3138 define_smacro(ctx, mname, casesense, 0, macro_start);
3140 free_tlist(origline);
3141 return DIRECTIVE_FOUND;
3147 tline = tline->next;
3149 tline = expand_id(tline);
3150 if (!tline || (tline->type != TOK_ID &&
3151 (tline->type != TOK_PREPROC_ID ||
3152 tline->text[1] != '$'))) {
3154 "`%%strlen' expects a macro identifier as first parameter");
3155 free_tlist(origline);
3156 return DIRECTIVE_FOUND;
3158 ctx = get_ctx(tline->text, &mname, false);
3160 tline = expand_smacro(tline->next);
3164 while (tok_type_(t, TOK_WHITESPACE))
3166 /* t should now point to the string */
3167 if (t->type != TOK_STRING) {
3169 "`%%strlen` requires string as second parameter");
3171 free_tlist(origline);
3172 return DIRECTIVE_FOUND;
3175 macro_start = nasm_malloc(sizeof(*macro_start));
3176 macro_start->next = NULL;
3177 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3178 macro_start->a.mac = NULL;
3181 * We now have a macro name, an implicit parameter count of
3182 * zero, and a numeric token to use as an expansion. Create
3183 * and store an SMacro.
3185 define_smacro(ctx, mname, casesense, 0, macro_start);
3187 free_tlist(origline);
3188 return DIRECTIVE_FOUND;
3193 tline = tline->next;
3195 tline = expand_id(tline);
3196 if (!tline || (tline->type != TOK_ID &&
3197 (tline->type != TOK_PREPROC_ID ||
3198 tline->text[1] != '$'))) {
3200 "`%%strcat' expects a macro identifier as first parameter");
3201 free_tlist(origline);
3202 return DIRECTIVE_FOUND;
3204 ctx = get_ctx(tline->text, &mname, false);
3206 tline = expand_smacro(tline->next);
3210 for (t = tline; t; t = t->next) {
3212 case TOK_WHITESPACE:
3215 len += t->a.len = nasm_unquote(t->text, NULL);
3218 if (!strcmp(t->text, ",")) /* permit comma separators */
3220 /* else fall through */
3223 "non-string passed to `%%strcat' (%d)", t->type);
3225 free_tlist(origline);
3226 return DIRECTIVE_FOUND;
3230 p = pp = nasm_malloc(len);
3231 for (t = tline; t; t = t->next) {
3232 if (t->type == TOK_STRING) {
3233 memcpy(p, t->text, t->a.len);
3239 * We now have a macro name, an implicit parameter count of
3240 * zero, and a numeric token to use as an expansion. Create
3241 * and store an SMacro.
3243 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3244 macro_start->text = nasm_quote(pp, len);
3246 define_smacro(ctx, mname, casesense, 0, macro_start);
3248 free_tlist(origline);
3249 return DIRECTIVE_FOUND;
3258 tline = tline->next;
3260 tline = expand_id(tline);
3261 if (!tline || (tline->type != TOK_ID &&
3262 (tline->type != TOK_PREPROC_ID ||
3263 tline->text[1] != '$'))) {
3265 "`%%substr' expects a macro identifier as first parameter");
3266 free_tlist(origline);
3267 return DIRECTIVE_FOUND;
3269 ctx = get_ctx(tline->text, &mname, false);
3271 tline = expand_smacro(tline->next);
3275 while (tok_type_(t, TOK_WHITESPACE))
3278 /* t should now point to the string */
3279 if (t->type != TOK_STRING) {
3281 "`%%substr` requires string as second parameter");
3283 free_tlist(origline);
3284 return DIRECTIVE_FOUND;
3289 tokval.t_type = TOKEN_INVALID;
3290 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3294 free_tlist(origline);
3295 return DIRECTIVE_FOUND;
3296 } else if (!is_simple(evalresult)) {
3297 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3299 free_tlist(origline);
3300 return DIRECTIVE_FOUND;
3302 a1 = evalresult->value-1;
3304 while (tok_type_(tt, TOK_WHITESPACE))
3307 a2 = 1; /* Backwards compatibility: one character */
3309 tokval.t_type = TOKEN_INVALID;
3310 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3314 free_tlist(origline);
3315 return DIRECTIVE_FOUND;
3316 } else if (!is_simple(evalresult)) {
3317 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3319 free_tlist(origline);
3320 return DIRECTIVE_FOUND;
3322 a2 = evalresult->value;
3325 len = nasm_unquote(t->text, NULL);
3328 if (a1+a2 > (int64_t)len)
3331 macro_start = nasm_malloc(sizeof(*macro_start));
3332 macro_start->next = NULL;
3333 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3334 macro_start->type = TOK_STRING;
3335 macro_start->a.mac = NULL;
3338 * We now have a macro name, an implicit parameter count of
3339 * zero, and a numeric token to use as an expansion. Create
3340 * and store an SMacro.
3342 define_smacro(ctx, mname, casesense, 0, macro_start);
3344 free_tlist(origline);
3345 return DIRECTIVE_FOUND;
3350 casesense = (i == PP_ASSIGN);
3352 tline = tline->next;
3354 tline = expand_id(tline);
3355 if (!tline || (tline->type != TOK_ID &&
3356 (tline->type != TOK_PREPROC_ID ||
3357 tline->text[1] != '$'))) {
3359 "`%%%sassign' expects a macro identifier",
3360 (i == PP_IASSIGN ? "i" : ""));
3361 free_tlist(origline);
3362 return DIRECTIVE_FOUND;
3364 ctx = get_ctx(tline->text, &mname, false);
3366 tline = expand_smacro(tline->next);
3371 tokval.t_type = TOKEN_INVALID;
3373 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3376 free_tlist(origline);
3377 return DIRECTIVE_FOUND;
3381 error(ERR_WARNING|ERR_PASS1,
3382 "trailing garbage after expression ignored");
3384 if (!is_simple(evalresult)) {
3386 "non-constant value given to `%%%sassign'",
3387 (i == PP_IASSIGN ? "i" : ""));
3388 free_tlist(origline);
3389 return DIRECTIVE_FOUND;
3392 macro_start = nasm_malloc(sizeof(*macro_start));
3393 macro_start->next = NULL;
3394 make_tok_num(macro_start, reloc_value(evalresult));
3395 macro_start->a.mac = NULL;
3398 * We now have a macro name, an implicit parameter count of
3399 * zero, and a numeric token to use as an expansion. Create
3400 * and store an SMacro.
3402 define_smacro(ctx, mname, casesense, 0, macro_start);
3403 free_tlist(origline);
3404 return DIRECTIVE_FOUND;
3408 * Syntax is `%line nnn[+mmm] [filename]'
3410 tline = tline->next;
3412 if (!tok_type_(tline, TOK_NUMBER)) {
3413 error(ERR_NONFATAL, "`%%line' expects line number");
3414 free_tlist(origline);
3415 return DIRECTIVE_FOUND;
3417 k = readnum(tline->text, &err);
3419 tline = tline->next;
3420 if (tok_is_(tline, "+")) {
3421 tline = tline->next;
3422 if (!tok_type_(tline, TOK_NUMBER)) {
3423 error(ERR_NONFATAL, "`%%line' expects line increment");
3424 free_tlist(origline);
3425 return DIRECTIVE_FOUND;
3427 m = readnum(tline->text, &err);
3428 tline = tline->next;
3434 nasm_free(src_set_fname(detoken(tline, false)));
3436 free_tlist(origline);
3437 return DIRECTIVE_FOUND;
3441 "preprocessor directive `%s' not yet implemented",
3443 return DIRECTIVE_FOUND;
3448 * Ensure that a macro parameter contains a condition code and
3449 * nothing else. Return the condition code index if so, or -1
3452 static int find_cc(Token * t)
3458 return -1; /* Probably a %+ without a space */
3461 if (t->type != TOK_ID)
3465 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3469 j = elements(conditions);
3472 m = nasm_stricmp(t->text, conditions[k]);
3487 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3489 Token **tail, *t, *tt;
3491 bool did_paste = false;
3494 /* Now handle token pasting... */
3497 while ((t = *tail) && (tt = t->next)) {
3499 case TOK_WHITESPACE:
3500 if (tt->type == TOK_WHITESPACE) {
3501 /* Zap adjacent whitespace tokens */
3502 t->next = delete_Token(tt);
3504 /* Do not advance paste_head here */
3509 case TOK_PREPROC_ID:
3516 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3517 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3518 tt->type == TOK_OTHER)) {
3519 len += strlen(tt->text);
3524 * Now tt points to the first token after
3525 * the potential paste area...
3527 if (tt != t->next) {
3528 /* We have at least two tokens... */
3529 len += strlen(t->text);
3530 p = tmp = nasm_malloc(len+1);
3534 p = strchr(p, '\0');
3535 t = delete_Token(t);
3538 t = *tail = tokenize(tmp);
3545 t->next = tt; /* Attach the remaining token chain */
3553 case TOK_PASTE: /* %+ */
3554 if (handle_paste_tokens) {
3555 /* Zap %+ and whitespace tokens to the right */
3556 while (t && (t->type == TOK_WHITESPACE ||
3557 t->type == TOK_PASTE))
3558 t = *tail = delete_Token(t);
3559 if (!paste_head || !t)
3560 break; /* Nothing to paste with */
3564 while (tok_type_(tt, TOK_WHITESPACE))
3565 tt = t->next = delete_Token(tt);
3568 tmp = nasm_strcat(t->text, tt->text);
3570 tt = delete_Token(tt);
3571 t = *tail = tokenize(tmp);
3577 t->next = tt; /* Attach the remaining token chain */
3584 /* else fall through */
3586 tail = paste_head = &t->next;
3593 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3594 * %-n) and MMacro-local identifiers (%%foo) as well as
3595 * macro indirection (%[...]).
3597 static Token *expand_mmac_params(Token * tline)
3599 Token *t, *tt, **tail, *thead;
3600 bool changed = false;
3606 if (tline->type == TOK_PREPROC_ID &&
3607 (((tline->text[1] == '+' || tline->text[1] == '-')
3608 && tline->text[2]) || tline->text[1] == '%'
3609 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
3611 int type = 0, cc; /* type = 0 to placate optimisers */
3618 tline = tline->next;
3621 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3622 mac = mac->next_active;
3624 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3626 switch (t->text[1]) {
3628 * We have to make a substitution of one of the
3629 * forms %1, %-1, %+1, %%foo, %0.
3633 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3634 text = nasm_strdup(tmpbuf);
3638 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3640 text = nasm_strcat(tmpbuf, t->text + 2);
3643 n = atoi(t->text + 2) - 1;
3644 if (n >= mac->nparam)
3647 if (mac->nparam > 1)
3648 n = (n + mac->rotate) % mac->nparam;
3649 tt = mac->params[n];
3654 "macro parameter %d is not a condition code",
3659 if (inverse_ccs[cc] == -1) {
3661 "condition code `%s' is not invertible",
3665 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3669 n = atoi(t->text + 2) - 1;
3670 if (n >= mac->nparam)
3673 if (mac->nparam > 1)
3674 n = (n + mac->rotate) % mac->nparam;
3675 tt = mac->params[n];
3680 "macro parameter %d is not a condition code",
3685 text = nasm_strdup(conditions[cc]);
3689 n = atoi(t->text + 1) - 1;
3690 if (n >= mac->nparam)
3693 if (mac->nparam > 1)
3694 n = (n + mac->rotate) % mac->nparam;
3695 tt = mac->params[n];
3698 for (i = 0; i < mac->paramlen[n]; i++) {
3699 *tail = new_Token(NULL, tt->type, tt->text, 0);
3700 tail = &(*tail)->next;
3704 text = NULL; /* we've done it here */
3719 } else if (tline->type == TOK_INDIRECT) {
3721 tline = tline->next;
3722 tt = tokenize(t->text);
3723 tt = expand_mmac_params(tt);
3724 tt = expand_smacro(tt);
3727 tt->a.mac = NULL; /* Necessary? */
3735 tline = tline->next;
3743 paste_tokens(&thead, false);
3749 * Expand all single-line macro calls made in the given line.
3750 * Return the expanded version of the line. The original is deemed
3751 * to be destroyed in the process. (In reality we'll just move
3752 * Tokens from input to output a lot of the time, rather than
3753 * actually bothering to destroy and replicate.)
3756 static Token *expand_smacro(Token * tline)
3758 Token *t, *tt, *mstart, **tail, *thead;
3759 SMacro *head = NULL, *m;
3762 unsigned int nparam, sparam;
3764 Token *org_tline = tline;
3767 int deadman = DEADMAN_LIMIT;
3771 * Trick: we should avoid changing the start token pointer since it can
3772 * be contained in "next" field of other token. Because of this
3773 * we allocate a copy of first token and work with it; at the end of
3774 * routine we copy it back
3778 new_Token(org_tline->next, org_tline->type, org_tline->text,
3780 tline->a.mac = org_tline->a.mac;
3781 nasm_free(org_tline->text);
3782 org_tline->text = NULL;
3785 expanded = true; /* Always expand %+ at least once */
3791 while (tline) { /* main token loop */
3793 error(ERR_NONFATAL, "interminable macro recursion");
3797 if ((mname = tline->text)) {
3798 /* if this token is a local macro, look in local context */
3799 if (tline->type == TOK_ID) {
3800 head = (SMacro *)hash_findix(&smacros, mname);
3801 } else if (tline->type == TOK_PREPROC_ID) {
3802 ctx = get_ctx(mname, &mname, true);
3803 head = ctx ? (SMacro *)hash_findix(&ctx->localmac, mname) : NULL;
3808 * We've hit an identifier. As in is_mmacro below, we first
3809 * check whether the identifier is a single-line macro at
3810 * all, then think about checking for parameters if
3813 for (m = head; m; m = m->next)
3814 if (!mstrcmp(m->name, mname, m->casesense))
3820 if (m->nparam == 0) {
3822 * Simple case: the macro is parameterless. Discard the
3823 * one token that the macro call took, and push the
3824 * expansion back on the to-do stack.
3826 if (!m->expansion) {
3827 if (!strcmp("__FILE__", m->name)) {
3830 src_get(&num, &file);
3831 tline->text = nasm_quote(file, strlen(file));
3832 tline->type = TOK_STRING;
3836 if (!strcmp("__LINE__", m->name)) {
3837 nasm_free(tline->text);
3838 make_tok_num(tline, src_get_linnum());
3841 if (!strcmp("__BITS__", m->name)) {
3842 nasm_free(tline->text);
3843 make_tok_num(tline, globalbits);
3846 tline = delete_Token(tline);
3851 * Complicated case: at least one macro with this name
3852 * exists and takes parameters. We must find the
3853 * parameters in the call, count them, find the SMacro
3854 * that corresponds to that form of the macro call, and
3855 * substitute for the parameters when we expand. What a
3858 /*tline = tline->next;
3859 skip_white_(tline); */
3862 while (tok_type_(t, TOK_SMAC_END)) {
3863 t->a.mac->in_progress = false;
3865 t = tline->next = delete_Token(t);
3868 } while (tok_type_(tline, TOK_WHITESPACE));
3869 if (!tok_is_(tline, "(")) {
3871 * This macro wasn't called with parameters: ignore
3872 * the call. (Behaviour borrowed from gnu cpp.)
3881 sparam = PARAM_DELTA;
3882 params = nasm_malloc(sparam * sizeof(Token *));
3883 params[0] = tline->next;
3884 paramsize = nasm_malloc(sparam * sizeof(int));
3886 while (true) { /* parameter loop */
3888 * For some unusual expansions
3889 * which concatenates function call
3892 while (tok_type_(t, TOK_SMAC_END)) {
3893 t->a.mac->in_progress = false;
3895 t = tline->next = delete_Token(t);
3901 "macro call expects terminating `)'");
3904 if (tline->type == TOK_WHITESPACE
3906 if (paramsize[nparam])
3909 params[nparam] = tline->next;
3910 continue; /* parameter loop */
3912 if (tline->type == TOK_OTHER
3913 && tline->text[1] == 0) {
3914 char ch = tline->text[0];
3915 if (ch == ',' && !paren && brackets <= 0) {
3916 if (++nparam >= sparam) {
3917 sparam += PARAM_DELTA;
3918 params = nasm_realloc(params,
3923 nasm_realloc(paramsize,
3927 params[nparam] = tline->next;
3928 paramsize[nparam] = 0;
3930 continue; /* parameter loop */
3933 (brackets > 0 || (brackets == 0 &&
3934 !paramsize[nparam])))
3936 if (!(brackets++)) {
3937 params[nparam] = tline->next;
3938 continue; /* parameter loop */
3941 if (ch == '}' && brackets > 0)
3942 if (--brackets == 0) {
3944 continue; /* parameter loop */
3946 if (ch == '(' && !brackets)
3948 if (ch == ')' && brackets <= 0)
3954 error(ERR_NONFATAL, "braces do not "
3955 "enclose all of macro parameter");
3957 paramsize[nparam] += white + 1;
3959 } /* parameter loop */
3961 while (m && (m->nparam != nparam ||
3962 mstrcmp(m->name, mname,
3966 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
3967 "macro `%s' exists, "
3968 "but not taking %d parameters",
3969 mstart->text, nparam);
3972 if (m && m->in_progress)
3974 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3976 * Design question: should we handle !tline, which
3977 * indicates missing ')' here, or expand those
3978 * macros anyway, which requires the (t) test a few
3982 nasm_free(paramsize);
3986 * Expand the macro: we are placed on the last token of the
3987 * call, so that we can easily split the call from the
3988 * following tokens. We also start by pushing an SMAC_END
3989 * token for the cycle removal.
3996 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3998 m->in_progress = true;
4000 for (t = m->expansion; t; t = t->next) {
4001 if (t->type >= TOK_SMAC_PARAM) {
4002 Token *pcopy = tline, **ptail = &pcopy;
4006 ttt = params[t->type - TOK_SMAC_PARAM];
4007 for (i = paramsize[t->type - TOK_SMAC_PARAM];
4010 new_Token(tline, ttt->type, ttt->text,
4016 } else if (t->type == TOK_PREPROC_Q) {
4017 tt = new_Token(tline, TOK_ID, mname, 0);
4019 } else if (t->type == TOK_PREPROC_QQ) {
4020 tt = new_Token(tline, TOK_ID, m->name, 0);
4023 tt = new_Token(tline, t->type, t->text, 0);
4029 * Having done that, get rid of the macro call, and clean
4030 * up the parameters.
4033 nasm_free(paramsize);
4036 continue; /* main token loop */
4041 if (tline->type == TOK_SMAC_END) {
4042 tline->a.mac->in_progress = false;
4043 tline = delete_Token(tline);
4046 tline = tline->next;
4054 * Now scan the entire line and look for successive TOK_IDs that resulted
4055 * after expansion (they can't be produced by tokenize()). The successive
4056 * TOK_IDs should be concatenated.
4057 * Also we look for %+ tokens and concatenate the tokens before and after
4058 * them (without white spaces in between).
4060 if (expanded && paste_tokens(&thead, true)) {
4062 * If we concatenated something, *and* we had previously expanded
4063 * an actual macro, scan the lines again for macros...
4073 *org_tline = *thead;
4074 /* since we just gave text to org_line, don't free it */
4076 delete_Token(thead);
4078 /* the expression expanded to empty line;
4079 we can't return NULL for some reasons
4080 we just set the line to a single WHITESPACE token. */
4081 memset(org_tline, 0, sizeof(*org_tline));
4082 org_tline->text = NULL;
4083 org_tline->type = TOK_WHITESPACE;
4092 * Similar to expand_smacro but used exclusively with macro identifiers
4093 * right before they are fetched in. The reason is that there can be
4094 * identifiers consisting of several subparts. We consider that if there
4095 * are more than one element forming the name, user wants a expansion,
4096 * otherwise it will be left as-is. Example:
4100 * the identifier %$abc will be left as-is so that the handler for %define
4101 * will suck it and define the corresponding value. Other case:
4103 * %define _%$abc cde
4105 * In this case user wants name to be expanded *before* %define starts
4106 * working, so we'll expand %$abc into something (if it has a value;
4107 * otherwise it will be left as-is) then concatenate all successive
4110 static Token *expand_id(Token * tline)
4112 Token *cur, *oldnext = NULL;
4114 if (!tline || !tline->next)
4119 (cur->next->type == TOK_ID ||
4120 cur->next->type == TOK_PREPROC_ID
4121 || cur->next->type == TOK_NUMBER))
4124 /* If identifier consists of just one token, don't expand */
4129 oldnext = cur->next; /* Detach the tail past identifier */
4130 cur->next = NULL; /* so that expand_smacro stops here */
4133 tline = expand_smacro(tline);
4136 /* expand_smacro possibly changhed tline; re-scan for EOL */
4138 while (cur && cur->next)
4141 cur->next = oldnext;
4148 * Determine whether the given line constitutes a multi-line macro
4149 * call, and return the MMacro structure called if so. Doesn't have
4150 * to check for an initial label - that's taken care of in
4151 * expand_mmacro - but must check numbers of parameters. Guaranteed
4152 * to be called with tline->type == TOK_ID, so the putative macro
4153 * name is easy to find.
4155 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4161 head = (MMacro *) hash_findix(&mmacros, tline->text);
4164 * Efficiency: first we see if any macro exists with the given
4165 * name. If not, we can return NULL immediately. _Then_ we
4166 * count the parameters, and then we look further along the
4167 * list if necessary to find the proper MMacro.
4169 for (m = head; m; m = m->next)
4170 if (!mstrcmp(m->name, tline->text, m->casesense))
4176 * OK, we have a potential macro. Count and demarcate the
4179 count_mmac_params(tline->next, &nparam, ¶ms);
4182 * So we know how many parameters we've got. Find the MMacro
4183 * structure that handles this number.
4186 if (m->nparam_min <= nparam
4187 && (m->plus || nparam <= m->nparam_max)) {
4189 * This one is right. Just check if cycle removal
4190 * prohibits us using it before we actually celebrate...
4192 if (m->in_progress > m->max_depth) {
4193 if (m->max_depth > 0) {
4195 "reached maximum recursion depth of %i",
4202 * It's right, and we can use it. Add its default
4203 * parameters to the end of our list if necessary.
4205 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4207 nasm_realloc(params,
4208 ((m->nparam_min + m->ndefs +
4209 1) * sizeof(*params)));
4210 while (nparam < m->nparam_min + m->ndefs) {
4211 params[nparam] = m->defaults[nparam - m->nparam_min];
4216 * If we've gone over the maximum parameter count (and
4217 * we're in Plus mode), ignore parameters beyond
4220 if (m->plus && nparam > m->nparam_max)
4221 nparam = m->nparam_max;
4223 * Then terminate the parameter list, and leave.
4225 if (!params) { /* need this special case */
4226 params = nasm_malloc(sizeof(*params));
4229 params[nparam] = NULL;
4230 *params_array = params;
4234 * This one wasn't right: look for the next one with the
4237 for (m = m->next; m; m = m->next)
4238 if (!mstrcmp(m->name, tline->text, m->casesense))
4243 * After all that, we didn't find one with the right number of
4244 * parameters. Issue a warning, and fail to expand the macro.
4246 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4247 "macro `%s' exists, but not taking %d parameters",
4248 tline->text, nparam);
4255 * Save MMacro invocation specific fields in
4256 * preparation for a recursive macro expansion
4258 static void push_mmacro(MMacro *m)
4260 MMacroInvocation *i;
4262 i = nasm_malloc(sizeof(MMacroInvocation));
4264 i->params = m->params;
4265 i->iline = m->iline;
4266 i->nparam = m->nparam;
4267 i->rotate = m->rotate;
4268 i->paramlen = m->paramlen;
4269 i->unique = m->unique;
4270 i->condcnt = m->condcnt;
4276 * Restore MMacro invocation specific fields that were
4277 * saved during a previous recursive macro expansion
4279 static void pop_mmacro(MMacro *m)
4281 MMacroInvocation *i;
4286 m->params = i->params;
4287 m->iline = i->iline;
4288 m->nparam = i->nparam;
4289 m->rotate = i->rotate;
4290 m->paramlen = i->paramlen;
4291 m->unique = i->unique;
4292 m->condcnt = i->condcnt;
4299 * Expand the multi-line macro call made by the given line, if
4300 * there is one to be expanded. If there is, push the expansion on
4301 * istk->expansion and return 1. Otherwise return 0.
4303 static int expand_mmacro(Token * tline)
4305 Token *startline = tline;
4306 Token *label = NULL;
4307 int dont_prepend = 0;
4308 Token **params, *t, *mtok, *tt;
4311 int i, nparam, *paramlen;
4316 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4317 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4320 m = is_mmacro(t, ¶ms);
4326 * We have an id which isn't a macro call. We'll assume
4327 * it might be a label; we'll also check to see if a
4328 * colon follows it. Then, if there's another id after
4329 * that lot, we'll check it again for macro-hood.
4333 if (tok_type_(t, TOK_WHITESPACE))
4334 last = t, t = t->next;
4335 if (tok_is_(t, ":")) {
4337 last = t, t = t->next;
4338 if (tok_type_(t, TOK_WHITESPACE))
4339 last = t, t = t->next;
4341 if (!tok_type_(t, TOK_ID) || !(m = is_mmacro(t, ¶ms)))
4349 * Fix up the parameters: this involves stripping leading and
4350 * trailing whitespace, then stripping braces if they are
4353 for (nparam = 0; params[nparam]; nparam++) ;
4354 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4356 for (i = 0; params[i]; i++) {
4358 int comma = (!m->plus || i < nparam - 1);
4362 if (tok_is_(t, "{"))
4363 t = t->next, brace = true, comma = false;
4367 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4368 break; /* ... because we have hit a comma */
4369 if (comma && t->type == TOK_WHITESPACE
4370 && tok_is_(t->next, ","))
4371 break; /* ... or a space then a comma */
4372 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4373 break; /* ... or a brace */
4380 * OK, we have a MMacro structure together with a set of
4381 * parameters. We must now go through the expansion and push
4382 * copies of each Line on to istk->expansion. Substitution of
4383 * parameter tokens and macro-local tokens doesn't get done
4384 * until the single-line macro substitution process; this is
4385 * because delaying them allows us to change the semantics
4386 * later through %rotate.
4388 * First, push an end marker on to istk->expansion, mark this
4389 * macro as in progress, and set up its invocation-specific
4392 ll = nasm_malloc(sizeof(Line));
4393 ll->next = istk->expansion;
4396 istk->expansion = ll;
4399 * Save the previous MMacro expansion in the case of
4402 if (m->max_depth && m->in_progress)
4410 m->paramlen = paramlen;
4411 m->unique = unique++;
4415 m->next_active = istk->mstk;
4418 for (l = m->expansion; l; l = l->next) {
4421 ll = nasm_malloc(sizeof(Line));
4422 ll->finishes = NULL;
4423 ll->next = istk->expansion;
4424 istk->expansion = ll;
4427 for (t = l->first; t; t = t->next) {
4431 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4433 case TOK_PREPROC_QQ:
4434 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4436 case TOK_PREPROC_ID:
4437 if (t->text[1] == '0' && t->text[2] == '0') {
4445 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4454 * If we had a label, push it on as the first line of
4455 * the macro expansion.
4458 if (dont_prepend < 0)
4459 free_tlist(startline);
4461 ll = nasm_malloc(sizeof(Line));
4462 ll->finishes = NULL;
4463 ll->next = istk->expansion;
4464 istk->expansion = ll;
4465 ll->first = startline;
4466 if (!dont_prepend) {
4468 label = label->next;
4469 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4474 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4479 /* The function that actually does the error reporting */
4480 static void verror(int severity, const char *fmt, va_list arg)
4484 vsnprintf(buff, sizeof(buff), fmt, arg);
4486 if (istk && istk->mstk && istk->mstk->name)
4487 nasm_error(severity, "(%s:%d) %s", istk->mstk->name,
4488 istk->mstk->lineno, buff);
4490 nasm_error(severity, "%s", buff);
4494 * Since preprocessor always operate only on the line that didn't
4495 * arrived yet, we should always use ERR_OFFBY1.
4497 static void error(int severity, const char *fmt, ...)
4501 /* If we're in a dead branch of IF or something like it, ignore the error */
4502 if (istk && istk->conds && !emitting(istk->conds->state))
4506 verror(severity, fmt, arg);
4511 * Because %else etc are evaluated in the state context
4512 * of the previous branch, errors might get lost with error():
4513 * %if 0 ... %else trailing garbage ... %endif
4514 * So %else etc should report errors with this function.
4516 static void error_precond(int severity, const char *fmt, ...)
4520 /* Only ignore the error if it's really in a dead branch */
4521 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4525 verror(severity, fmt, arg);
4530 pp_reset(char *file, int apass, ListGen * listgen, StrList **deplist)
4535 istk = nasm_malloc(sizeof(Include));
4538 istk->expansion = NULL;
4540 istk->fp = fopen(file, "r");
4542 src_set_fname(nasm_strdup(file));
4546 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4549 nested_mac_count = 0;
4550 nested_rep_count = 0;
4553 if (tasm_compatible_mode) {
4554 stdmacpos = nasm_stdmac;
4556 stdmacpos = nasm_stdmac_after_tasm;
4558 any_extrastdmac = extrastdmac && *extrastdmac;
4563 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4564 * The caller, however, will also pass in 3 for preprocess-only so
4565 * we can set __PASS__ accordingly.
4567 pass = apass > 2 ? 2 : apass;
4569 dephead = deptail = deplist;
4571 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4573 strcpy(sl->str, file);
4575 deptail = &sl->next;
4579 * Define the __PASS__ macro. This is defined here unlike
4580 * all the other builtins, because it is special -- it varies between
4583 t = nasm_malloc(sizeof(*t));
4585 make_tok_num(t, apass);
4587 define_smacro(NULL, "__PASS__", true, 0, t);
4590 static char *pp_getline(void)
4597 * Fetch a tokenized line, either from the macro-expansion
4598 * buffer or from the input file.
4601 while (istk->expansion && istk->expansion->finishes) {
4602 Line *l = istk->expansion;
4603 if (!l->finishes->name && l->finishes->in_progress > 1) {
4607 * This is a macro-end marker for a macro with no
4608 * name, which means it's not really a macro at all
4609 * but a %rep block, and the `in_progress' field is
4610 * more than 1, meaning that we still need to
4611 * repeat. (1 means the natural last repetition; 0
4612 * means termination by %exitrep.) We have
4613 * therefore expanded up to the %endrep, and must
4614 * push the whole block on to the expansion buffer
4615 * again. We don't bother to remove the macro-end
4616 * marker: we'd only have to generate another one
4619 l->finishes->in_progress--;
4620 for (l = l->finishes->expansion; l; l = l->next) {
4621 Token *t, *tt, **tail;
4623 ll = nasm_malloc(sizeof(Line));
4624 ll->next = istk->expansion;
4625 ll->finishes = NULL;
4629 for (t = l->first; t; t = t->next) {
4630 if (t->text || t->type == TOK_WHITESPACE) {
4632 new_Token(NULL, t->type, t->text, 0);
4637 istk->expansion = ll;
4641 * Check whether a `%rep' was started and not ended
4642 * within this macro expansion. This can happen and
4643 * should be detected. It's a fatal error because
4644 * I'm too confused to work out how to recover
4650 "defining with name in expansion");
4651 else if (istk->mstk->name)
4653 "`%%rep' without `%%endrep' within"
4654 " expansion of macro `%s'",
4659 * FIXME: investigate the relationship at this point between
4660 * istk->mstk and l->finishes
4663 MMacro *m = istk->mstk;
4664 istk->mstk = m->next_active;
4667 * This was a real macro call, not a %rep, and
4668 * therefore the parameter information needs to
4673 l->finishes->in_progress --;
4675 nasm_free(m->params);
4676 free_tlist(m->iline);
4677 nasm_free(m->paramlen);
4678 l->finishes->in_progress = 0;
4683 istk->expansion = l->next;
4685 list->downlevel(LIST_MACRO);
4688 while (1) { /* until we get a line we can use */
4690 if (istk->expansion) { /* from a macro expansion */
4692 Line *l = istk->expansion;
4694 istk->mstk->lineno++;
4696 istk->expansion = l->next;
4698 p = detoken(tline, false);
4699 list->line(LIST_MACRO, p);
4704 if (line) { /* from the current input file */
4705 line = prepreproc(line);
4706 tline = tokenize(line);
4711 * The current file has ended; work down the istk
4718 "expected `%%endif' before end of file");
4719 /* only set line and file name if there's a next node */
4721 src_set_linnum(i->lineno);
4722 nasm_free(src_set_fname(i->fname));
4725 list->downlevel(LIST_INCLUDE);
4729 if (istk->expansion && istk->expansion->finishes)
4735 * We must expand MMacro parameters and MMacro-local labels
4736 * _before_ we plunge into directive processing, to cope
4737 * with things like `%define something %1' such as STRUC
4738 * uses. Unless we're _defining_ a MMacro, in which case
4739 * those tokens should be left alone to go into the
4740 * definition; and unless we're in a non-emitting
4741 * condition, in which case we don't want to meddle with
4744 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4745 && !(istk->mstk && !istk->mstk->in_progress)) {
4746 tline = expand_mmac_params(tline);
4750 * Check the line to see if it's a preprocessor directive.
4752 if (do_directive(tline) == DIRECTIVE_FOUND) {
4754 } else if (defining) {
4756 * We're defining a multi-line macro. We emit nothing
4758 * shove the tokenized line on to the macro definition.
4760 Line *l = nasm_malloc(sizeof(Line));
4761 l->next = defining->expansion;
4764 defining->expansion = l;
4766 } else if (istk->conds && !emitting(istk->conds->state)) {
4768 * We're in a non-emitting branch of a condition block.
4769 * Emit nothing at all, not even a blank line: when we
4770 * emerge from the condition we'll give a line-number
4771 * directive so we keep our place correctly.
4775 } else if (istk->mstk && !istk->mstk->in_progress) {
4777 * We're in a %rep block which has been terminated, so
4778 * we're walking through to the %endrep without
4779 * emitting anything. Emit nothing at all, not even a
4780 * blank line: when we emerge from the %rep block we'll
4781 * give a line-number directive so we keep our place
4787 tline = expand_smacro(tline);
4788 if (!expand_mmacro(tline)) {
4790 * De-tokenize the line again, and emit it.
4792 line = detoken(tline, true);
4796 continue; /* expand_mmacro calls free_tlist */
4804 static void pp_cleanup(int pass)
4807 if (defining->name) {
4809 "end of file while still defining macro `%s'",
4812 error(ERR_NONFATAL, "end of file while still in %%rep");
4815 free_mmacro(defining);
4825 nasm_free(i->fname);
4830 nasm_free(src_set_fname(NULL));
4835 while ((i = ipath)) {
4844 void pp_include_path(char *path)
4848 i = nasm_malloc(sizeof(IncPath));
4849 i->path = path ? nasm_strdup(path) : NULL;
4862 void pp_pre_include(char *fname)
4864 Token *inc, *space, *name;
4867 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4868 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4869 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4871 l = nasm_malloc(sizeof(Line));
4878 void pp_pre_define(char *definition)
4884 equals = strchr(definition, '=');
4885 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4886 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4889 space->next = tokenize(definition);
4893 l = nasm_malloc(sizeof(Line));
4900 void pp_pre_undefine(char *definition)
4905 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4906 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4907 space->next = tokenize(definition);
4909 l = nasm_malloc(sizeof(Line));
4917 * Added by Keith Kanios:
4919 * This function is used to assist with "runtime" preprocessor
4920 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4922 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4923 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4926 void pp_runtime(char *definition)
4930 def = tokenize(definition);
4931 if (do_directive(def) == NO_DIRECTIVE_FOUND)
4936 void pp_extra_stdmac(macros_t *macros)
4938 extrastdmac = macros;
4941 static void make_tok_num(Token * tok, int64_t val)
4944 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4945 tok->text = nasm_strdup(numbuf);
4946 tok->type = TOK_NUMBER;