NASM 0.99.06
[nasm.git] / preproc.c
blob9bc6f71192cf637962c4c3052375055f5ba88dd4
1 /* preproc.c macro preprocessor for the Netwide Assembler
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the licence given in the file "Licence"
6 * distributed in the NASM archive.
8 * initial version 18/iii/97 by Simon Tatham
9 */
11 /* Typical flow of text through preproc
13 * pp_getline gets tokenized lines, either
15 * from a macro expansion
17 * or
18 * {
19 * read_line gets raw text from stdmacpos, or predef, or current input file
20 * tokenize converts to tokens
21 * }
23 * expand_mmac_params is used to expand %1 etc., unless a macro is being
24 * defined or a false conditional is being processed
25 * (%0, %1, %+1, %-1, %%foo
27 * do_directive checks for directives
29 * expand_smacro is used to expand single line macros
31 * expand_mmacro is used to expand multi-line macros
33 * detoken is used to convert the line back to text
36 #include "compiler.h"
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <stddef.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <limits.h>
45 #include <inttypes.h>
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "preproc.h"
50 #include "hashtbl.h"
51 #include "stdscan.h"
52 #include "tokens.h"
54 typedef struct SMacro SMacro;
55 typedef struct MMacro MMacro;
56 typedef struct Context Context;
57 typedef struct Token Token;
58 typedef struct Blocks Blocks;
59 typedef struct Line Line;
60 typedef struct Include Include;
61 typedef struct Cond Cond;
62 typedef struct IncPath IncPath;
65 * Note on the storage of both SMacro and MMacros: the hash table
66 * indexes them case-insensitively, and we then have to go through a
67 * linked list of potential case aliases (and, for MMacros, parameter
68 * ranges); this is to preserve the matching semantics of the earlier
69 * code. If the number of case aliases for a specific macro is a
70 * performance issue, you may want to reconsider your coding style.
74 * Store the definition of a single-line macro.
76 struct SMacro {
77 SMacro *next;
78 char *name;
79 bool casesense;
80 bool in_progress;
81 unsigned int nparam;
82 Token *expansion;
86 * Store the definition of a multi-line macro. This is also used to
87 * store the interiors of `%rep...%endrep' blocks, which are
88 * effectively self-re-invoking multi-line macros which simply
89 * don't have a name or bother to appear in the hash tables. %rep
90 * blocks are signified by having a NULL `name' field.
92 * In a MMacro describing a `%rep' block, the `in_progress' field
93 * isn't merely boolean, but gives the number of repeats left to
94 * run.
96 * The `next' field is used for storing MMacros in hash tables; the
97 * `next_active' field is for stacking them on istk entries.
99 * When a MMacro is being expanded, `params', `iline', `nparam',
100 * `paramlen', `rotate' and `unique' are local to the invocation.
102 struct MMacro {
103 MMacro *next;
104 char *name;
105 int nparam_min, nparam_max;
106 bool casesense;
107 bool plus; /* is the last parameter greedy? */
108 bool nolist; /* is this macro listing-inhibited? */
109 int64_t in_progress;
110 Token *dlist; /* All defaults as one list */
111 Token **defaults; /* Parameter default pointers */
112 int ndefs; /* number of default parameters */
113 Line *expansion;
115 MMacro *next_active;
116 MMacro *rep_nest; /* used for nesting %rep */
117 Token **params; /* actual parameters */
118 Token *iline; /* invocation line */
119 unsigned int nparam, rotate;
120 int *paramlen;
121 uint64_t unique;
122 int lineno; /* Current line number on expansion */
126 * The context stack is composed of a linked list of these.
128 struct Context {
129 Context *next;
130 SMacro *localmac;
131 char *name;
132 uint32_t number;
136 * This is the internal form which we break input lines up into.
137 * Typically stored in linked lists.
139 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
140 * necessarily used as-is, but is intended to denote the number of
141 * the substituted parameter. So in the definition
143 * %define a(x,y) ( (x) & ~(y) )
145 * the token representing `x' will have its type changed to
146 * TOK_SMAC_PARAM, but the one representing `y' will be
147 * TOK_SMAC_PARAM+1.
149 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
150 * which doesn't need quotes around it. Used in the pre-include
151 * mechanism as an alternative to trying to find a sensible type of
152 * quote to use on the filename we were passed.
154 enum pp_token_type {
155 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
156 TOK_PREPROC_ID, TOK_STRING,
157 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER, TOK_SMAC_PARAM,
158 TOK_INTERNAL_STRING
161 struct Token {
162 Token *next;
163 char *text;
164 SMacro *mac; /* associated macro for TOK_SMAC_END */
165 enum pp_token_type type;
169 * Multi-line macro definitions are stored as a linked list of
170 * these, which is essentially a container to allow several linked
171 * lists of Tokens.
173 * Note that in this module, linked lists are treated as stacks
174 * wherever possible. For this reason, Lines are _pushed_ on to the
175 * `expansion' field in MMacro structures, so that the linked list,
176 * if walked, would give the macro lines in reverse order; this
177 * means that we can walk the list when expanding a macro, and thus
178 * push the lines on to the `expansion' field in _istk_ in reverse
179 * order (so that when popped back off they are in the right
180 * order). It may seem cockeyed, and it relies on my design having
181 * an even number of steps in, but it works...
183 * Some of these structures, rather than being actual lines, are
184 * markers delimiting the end of the expansion of a given macro.
185 * This is for use in the cycle-tracking and %rep-handling code.
186 * Such structures have `finishes' non-NULL, and `first' NULL. All
187 * others have `finishes' NULL, but `first' may still be NULL if
188 * the line is blank.
190 struct Line {
191 Line *next;
192 MMacro *finishes;
193 Token *first;
197 * To handle an arbitrary level of file inclusion, we maintain a
198 * stack (ie linked list) of these things.
200 struct Include {
201 Include *next;
202 FILE *fp;
203 Cond *conds;
204 Line *expansion;
205 char *fname;
206 int lineno, lineinc;
207 MMacro *mstk; /* stack of active macros/reps */
211 * Include search path. This is simply a list of strings which get
212 * prepended, in turn, to the name of an include file, in an
213 * attempt to find the file if it's not in the current directory.
215 struct IncPath {
216 IncPath *next;
217 char *path;
221 * Conditional assembly: we maintain a separate stack of these for
222 * each level of file inclusion. (The only reason we keep the
223 * stacks separate is to ensure that a stray `%endif' in a file
224 * included from within the true branch of a `%if' won't terminate
225 * it and cause confusion: instead, rightly, it'll cause an error.)
227 struct Cond {
228 Cond *next;
229 int state;
231 enum {
233 * These states are for use just after %if or %elif: IF_TRUE
234 * means the condition has evaluated to truth so we are
235 * currently emitting, whereas IF_FALSE means we are not
236 * currently emitting but will start doing so if a %else comes
237 * up. In these states, all directives are admissible: %elif,
238 * %else and %endif. (And of course %if.)
240 COND_IF_TRUE, COND_IF_FALSE,
242 * These states come up after a %else: ELSE_TRUE means we're
243 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
244 * any %elif or %else will cause an error.
246 COND_ELSE_TRUE, COND_ELSE_FALSE,
248 * This state means that we're not emitting now, and also that
249 * nothing until %endif will be emitted at all. It's for use in
250 * two circumstances: (i) when we've had our moment of emission
251 * and have now started seeing %elifs, and (ii) when the
252 * condition construct in question is contained within a
253 * non-emitting branch of a larger condition construct.
255 COND_NEVER
257 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
260 * These defines are used as the possible return values for do_directive
262 #define NO_DIRECTIVE_FOUND 0
263 #define DIRECTIVE_FOUND 1
266 * Condition codes. Note that we use c_ prefix not C_ because C_ is
267 * used in nasm.h for the "real" condition codes. At _this_ level,
268 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
269 * ones, so we need a different enum...
271 static const char * const conditions[] = {
272 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
273 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
274 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
276 enum pp_conds {
277 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
278 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
279 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
280 c_none = -1
282 static const enum pp_conds inverse_ccs[] = {
283 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
284 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,
285 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
289 * Directive names.
291 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
292 static int is_condition(enum preproc_token arg)
294 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
297 /* For TASM compatibility we need to be able to recognise TASM compatible
298 * conditional compilation directives. Using the NASM pre-processor does
299 * not work, so we look for them specifically from the following list and
300 * then jam in the equivalent NASM directive into the input stream.
303 #ifndef MAX
304 # define MAX(a,b) ( ((a) > (b)) ? (a) : (b))
305 #endif
307 enum {
308 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
309 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
312 static const char * const tasm_directives[] = {
313 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
314 "ifndef", "include", "local"
317 static int StackSize = 4;
318 static char *StackPointer = "ebp";
319 static int ArgOffset = 8;
320 static int LocalOffset = 4;
322 static Context *cstk;
323 static Include *istk;
324 static IncPath *ipath = NULL;
326 static efunc _error; /* Pointer to client-provided error reporting function */
327 static evalfunc evaluate;
329 static int pass; /* HACK: pass 0 = generate dependencies only */
331 static uint64_t unique; /* unique identifier numbers */
333 static Line *predef = NULL;
335 static ListGen *list;
338 * The current set of multi-line macros we have defined.
340 static struct hash_table *mmacros;
343 * The current set of single-line macros we have defined.
345 static struct hash_table *smacros;
348 * The multi-line macro we are currently defining, or the %rep
349 * block we are currently reading, if any.
351 static MMacro *defining;
354 * The number of macro parameters to allocate space for at a time.
356 #define PARAM_DELTA 16
359 * The standard macro set: defined as `static char *stdmac[]'. Also
360 * gives our position in the macro set, when we're processing it.
362 #include "macros.c"
363 static const char **stdmacpos;
366 * The extra standard macros that come from the object format, if
367 * any.
369 static const char **extrastdmac = NULL;
370 bool any_extrastdmac;
373 * Tokens are allocated in blocks to improve speed
375 #define TOKEN_BLOCKSIZE 4096
376 static Token *freeTokens = NULL;
377 struct Blocks {
378 Blocks *next;
379 void *chunk;
382 static Blocks blocks = { NULL, NULL };
385 * Forward declarations.
387 static Token *expand_mmac_params(Token * tline);
388 static Token *expand_smacro(Token * tline);
389 static Token *expand_id(Token * tline);
390 static Context *get_ctx(char *name, bool all_contexts);
391 static void make_tok_num(Token * tok, int64_t val);
392 static void error(int severity, const char *fmt, ...);
393 static void *new_Block(size_t size);
394 static void delete_Blocks(void);
395 static Token *new_Token(Token * next, enum pp_token_type type, char *text, int txtlen);
396 static Token *delete_Token(Token * t);
399 * Macros for safe checking of token pointers, avoid *(NULL)
401 #define tok_type_(x,t) ((x) && (x)->type == (t))
402 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
403 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
404 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
406 /* Handle TASM specific directives, which do not contain a % in
407 * front of them. We do it here because I could not find any other
408 * place to do it for the moment, and it is a hack (ideally it would
409 * be nice to be able to use the NASM pre-processor to do it).
411 static char *check_tasm_directive(char *line)
413 int32_t i, j, k, m, len;
414 char *p = line, *oldline, oldchar;
416 /* Skip whitespace */
417 while (isspace(*p) && *p != 0)
418 p++;
420 /* Binary search for the directive name */
421 i = -1;
422 j = elements(tasm_directives);
423 len = 0;
424 while (!isspace(p[len]) && p[len] != 0)
425 len++;
426 if (len) {
427 oldchar = p[len];
428 p[len] = 0;
429 while (j - i > 1) {
430 k = (j + i) / 2;
431 m = nasm_stricmp(p, tasm_directives[k]);
432 if (m == 0) {
433 /* We have found a directive, so jam a % in front of it
434 * so that NASM will then recognise it as one if it's own.
436 p[len] = oldchar;
437 len = strlen(p);
438 oldline = line;
439 line = nasm_malloc(len + 2);
440 line[0] = '%';
441 if (k == TM_IFDIFI) {
442 /* NASM does not recognise IFDIFI, so we convert it to
443 * %ifdef BOGUS. This is not used in NASM comaptible
444 * code, but does need to parse for the TASM macro
445 * package.
447 strcpy(line + 1, "ifdef BOGUS");
448 } else {
449 memcpy(line + 1, p, len + 1);
451 nasm_free(oldline);
452 return line;
453 } else if (m < 0) {
454 j = k;
455 } else
456 i = k;
458 p[len] = oldchar;
460 return line;
464 * The pre-preprocessing stage... This function translates line
465 * number indications as they emerge from GNU cpp (`# lineno "file"
466 * flags') into NASM preprocessor line number indications (`%line
467 * lineno file').
469 static char *prepreproc(char *line)
471 int lineno, fnlen;
472 char *fname, *oldline;
474 if (line[0] == '#' && line[1] == ' ') {
475 oldline = line;
476 fname = oldline + 2;
477 lineno = atoi(fname);
478 fname += strspn(fname, "0123456789 ");
479 if (*fname == '"')
480 fname++;
481 fnlen = strcspn(fname, "\"");
482 line = nasm_malloc(20 + fnlen);
483 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
484 nasm_free(oldline);
486 if (tasm_compatible_mode)
487 return check_tasm_directive(line);
488 return line;
492 * Free a linked list of tokens.
494 static void free_tlist(Token * list)
496 while (list) {
497 list = delete_Token(list);
502 * Free a linked list of lines.
504 static void free_llist(Line * list)
506 Line *l;
507 while (list) {
508 l = list;
509 list = list->next;
510 free_tlist(l->first);
511 nasm_free(l);
516 * Free an MMacro
518 static void free_mmacro(MMacro * m)
520 nasm_free(m->name);
521 free_tlist(m->dlist);
522 nasm_free(m->defaults);
523 free_llist(m->expansion);
524 nasm_free(m);
528 * Free all currently defined macros, and free the hash tables
530 static void free_macros(void)
532 struct hash_tbl_node *it;
533 const char *key;
534 SMacro *s;
535 MMacro *m;
537 it = NULL;
538 while ((s = hash_iterate(smacros, &it, &key)) != NULL) {
539 nasm_free((void *)key);
540 while (s) {
541 SMacro *ns = s->next;
542 nasm_free(s->name);
543 free_tlist(s->expansion);
544 nasm_free(s);
545 s = ns;
548 hash_free(smacros);
550 it = NULL;
551 while ((m = hash_iterate(mmacros, &it, &key)) != NULL) {
552 nasm_free((void *)key);
553 while (m) {
554 MMacro *nm = m->next;
555 free_mmacro(m);
556 m = nm;
559 hash_free(mmacros);
563 * Initialize the hash tables
565 static void init_macros(void)
567 smacros = hash_init();
568 mmacros = hash_init();
572 * Pop the context stack.
574 static void ctx_pop(void)
576 Context *c = cstk;
577 SMacro *smac, *s;
579 cstk = cstk->next;
580 smac = c->localmac;
581 while (smac) {
582 s = smac;
583 smac = smac->next;
584 nasm_free(s->name);
585 free_tlist(s->expansion);
586 nasm_free(s);
588 nasm_free(c->name);
589 nasm_free(c);
592 #define BUF_DELTA 512
594 * Read a line from the top file in istk, handling multiple CR/LFs
595 * at the end of the line read, and handling spurious ^Zs. Will
596 * return lines from the standard macro set if this has not already
597 * been done.
599 static char *read_line(void)
601 char *buffer, *p, *q;
602 int bufsize, continued_count;
604 if (stdmacpos) {
605 if (*stdmacpos) {
606 char *ret = nasm_strdup(*stdmacpos++);
607 if (!*stdmacpos && any_extrastdmac) {
608 stdmacpos = extrastdmac;
609 any_extrastdmac = false;
610 return ret;
613 * Nasty hack: here we push the contents of `predef' on
614 * to the top-level expansion stack, since this is the
615 * most convenient way to implement the pre-include and
616 * pre-define features.
618 if (!*stdmacpos) {
619 Line *pd, *l;
620 Token *head, **tail, *t;
622 for (pd = predef; pd; pd = pd->next) {
623 head = NULL;
624 tail = &head;
625 for (t = pd->first; t; t = t->next) {
626 *tail = new_Token(NULL, t->type, t->text, 0);
627 tail = &(*tail)->next;
629 l = nasm_malloc(sizeof(Line));
630 l->next = istk->expansion;
631 l->first = head;
632 l->finishes = false;
633 istk->expansion = l;
636 return ret;
637 } else {
638 stdmacpos = NULL;
642 bufsize = BUF_DELTA;
643 buffer = nasm_malloc(BUF_DELTA);
644 p = buffer;
645 continued_count = 0;
646 while (1) {
647 q = fgets(p, bufsize - (p - buffer), istk->fp);
648 if (!q)
649 break;
650 p += strlen(p);
651 if (p > buffer && p[-1] == '\n') {
652 /* Convert backslash-CRLF line continuation sequences into
653 nothing at all (for DOS and Windows) */
654 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
655 p -= 3;
656 *p = 0;
657 continued_count++;
659 /* Also convert backslash-LF line continuation sequences into
660 nothing at all (for Unix) */
661 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
662 p -= 2;
663 *p = 0;
664 continued_count++;
665 } else {
666 break;
669 if (p - buffer > bufsize - 10) {
670 int32_t offset = p - buffer;
671 bufsize += BUF_DELTA;
672 buffer = nasm_realloc(buffer, bufsize);
673 p = buffer + offset; /* prevent stale-pointer problems */
677 if (!q && p == buffer) {
678 nasm_free(buffer);
679 return NULL;
682 src_set_linnum(src_get_linnum() + istk->lineinc +
683 (continued_count * istk->lineinc));
686 * Play safe: remove CRs as well as LFs, if any of either are
687 * present at the end of the line.
689 while (--p >= buffer && (*p == '\n' || *p == '\r'))
690 *p = '\0';
693 * Handle spurious ^Z, which may be inserted into source files
694 * by some file transfer utilities.
696 buffer[strcspn(buffer, "\032")] = '\0';
698 list->line(LIST_READ, buffer);
700 return buffer;
704 * Tokenize a line of text. This is a very simple process since we
705 * don't need to parse the value out of e.g. numeric tokens: we
706 * simply split one string into many.
708 static Token *tokenize(char *line)
710 char *p = line;
711 enum pp_token_type type;
712 Token *list = NULL;
713 Token *t, **tail = &list;
715 while (*line) {
716 p = line;
717 if (*p == '%') {
718 p++;
719 if (isdigit(*p) ||
720 ((*p == '-' || *p == '+') && isdigit(p[1])) ||
721 ((*p == '+') && (isspace(p[1]) || !p[1]))) {
722 do {
723 p++;
725 while (isdigit(*p));
726 type = TOK_PREPROC_ID;
727 } else if (*p == '{') {
728 p++;
729 while (*p && *p != '}') {
730 p[-1] = *p;
731 p++;
733 p[-1] = '\0';
734 if (*p)
735 p++;
736 type = TOK_PREPROC_ID;
737 } else if (isidchar(*p) ||
738 ((*p == '!' || *p == '%' || *p == '$') &&
739 isidchar(p[1]))) {
740 do {
741 p++;
743 while (isidchar(*p));
744 type = TOK_PREPROC_ID;
745 } else {
746 type = TOK_OTHER;
747 if (*p == '%')
748 p++;
750 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
751 type = TOK_ID;
752 p++;
753 while (*p && isidchar(*p))
754 p++;
755 } else if (*p == '\'' || *p == '"') {
757 * A string token.
759 char c = *p;
760 p++;
761 type = TOK_STRING;
762 while (*p && *p != c)
763 p++;
765 if (*p) {
766 p++;
767 } else {
768 error(ERR_WARNING, "unterminated string");
769 /* Handling unterminated strings by UNV */
770 /* type = -1; */
772 } else if (isnumstart(*p)) {
773 bool is_hex = false;
774 bool is_float = false;
775 bool has_e = false;
776 char c, *r;
779 * A numeric token.
782 if (*p == '$') {
783 p++;
784 is_hex = true;
787 for (;;) {
788 c = *p++;
790 if (!is_hex && (c == 'e' || c == 'E')) {
791 has_e = true;
792 if (*p == '+' || *p == '-') {
793 /* e can only be followed by +/- if it is either a
794 prefixed hex number or a floating-point number */
795 p++;
796 is_float = true;
798 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
799 is_hex = true;
800 } else if (c == 'P' || c == 'p') {
801 is_float = true;
802 if (*p == '+' || *p == '-')
803 p++;
804 } else if (isnumchar(c) || c == '_')
805 ; /* just advance */
806 else if (c == '.') {
807 /* we need to deal with consequences of the legacy
808 parser, like "1.nolist" being two tokens
809 (TOK_NUMBER, TOK_ID) here; at least give it
810 a shot for now. In the future, we probably need
811 a flex-based scanner with proper pattern matching
812 to do it as well as it can be done. Nothing in
813 the world is going to help the person who wants
814 0x123.p16 interpreted as two tokens, though. */
815 r = p;
816 while (*r == '_')
817 r++;
819 if (isdigit(*r) || (is_hex && isxdigit(*r)) ||
820 (!is_hex && (*r == 'e' || *r == 'E')) ||
821 (*r == 'p' || *r == 'P')) {
822 p = r;
823 is_float = true;
824 } else
825 break; /* Terminate the token */
826 } else
827 break;
829 p--; /* Point to first character beyond number */
831 if (has_e && !is_hex) {
832 /* 1e13 is floating-point, but 1e13h is not */
833 is_float = true;
836 type = is_float ? TOK_FLOAT : TOK_NUMBER;
837 } else if (isspace(*p)) {
838 type = TOK_WHITESPACE;
839 p++;
840 while (*p && isspace(*p))
841 p++;
843 * Whitespace just before end-of-line is discarded by
844 * pretending it's a comment; whitespace just before a
845 * comment gets lumped into the comment.
847 if (!*p || *p == ';') {
848 type = TOK_COMMENT;
849 while (*p)
850 p++;
852 } else if (*p == ';') {
853 type = TOK_COMMENT;
854 while (*p)
855 p++;
856 } else {
858 * Anything else is an operator of some kind. We check
859 * for all the double-character operators (>>, <<, //,
860 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
861 * else is a single-character operator.
863 type = TOK_OTHER;
864 if ((p[0] == '>' && p[1] == '>') ||
865 (p[0] == '<' && p[1] == '<') ||
866 (p[0] == '/' && p[1] == '/') ||
867 (p[0] == '<' && p[1] == '=') ||
868 (p[0] == '>' && p[1] == '=') ||
869 (p[0] == '=' && p[1] == '=') ||
870 (p[0] == '!' && p[1] == '=') ||
871 (p[0] == '<' && p[1] == '>') ||
872 (p[0] == '&' && p[1] == '&') ||
873 (p[0] == '|' && p[1] == '|') ||
874 (p[0] == '^' && p[1] == '^')) {
875 p++;
877 p++;
880 /* Handling unterminated string by UNV */
881 /*if (type == -1)
883 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
884 t->text[p-line] = *line;
885 tail = &t->next;
887 else */
888 if (type != TOK_COMMENT) {
889 *tail = t = new_Token(NULL, type, line, p - line);
890 tail = &t->next;
892 line = p;
894 return list;
898 * this function allocates a new managed block of memory and
899 * returns a pointer to the block. The managed blocks are
900 * deleted only all at once by the delete_Blocks function.
902 static void *new_Block(size_t size)
904 Blocks *b = &blocks;
906 /* first, get to the end of the linked list */
907 while (b->next)
908 b = b->next;
909 /* now allocate the requested chunk */
910 b->chunk = nasm_malloc(size);
912 /* now allocate a new block for the next request */
913 b->next = nasm_malloc(sizeof(Blocks));
914 /* and initialize the contents of the new block */
915 b->next->next = NULL;
916 b->next->chunk = NULL;
917 return b->chunk;
921 * this function deletes all managed blocks of memory
923 static void delete_Blocks(void)
925 Blocks *a, *b = &blocks;
928 * keep in mind that the first block, pointed to by blocks
929 * is a static and not dynamically allocated, so we don't
930 * free it.
932 while (b) {
933 if (b->chunk)
934 nasm_free(b->chunk);
935 a = b;
936 b = b->next;
937 if (a != &blocks)
938 nasm_free(a);
943 * this function creates a new Token and passes a pointer to it
944 * back to the caller. It sets the type and text elements, and
945 * also the mac and next elements to NULL.
947 static Token *new_Token(Token * next, enum pp_token_type type, char *text, int txtlen)
949 Token *t;
950 int i;
952 if (freeTokens == NULL) {
953 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
954 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
955 freeTokens[i].next = &freeTokens[i + 1];
956 freeTokens[i].next = NULL;
958 t = freeTokens;
959 freeTokens = t->next;
960 t->next = next;
961 t->mac = NULL;
962 t->type = type;
963 if (type == TOK_WHITESPACE || text == NULL) {
964 t->text = NULL;
965 } else {
966 if (txtlen == 0)
967 txtlen = strlen(text);
968 t->text = nasm_malloc(1 + txtlen);
969 strncpy(t->text, text, txtlen);
970 t->text[txtlen] = '\0';
972 return t;
975 static Token *delete_Token(Token * t)
977 Token *next = t->next;
978 nasm_free(t->text);
979 t->next = freeTokens;
980 freeTokens = t;
981 return next;
985 * Convert a line of tokens back into text.
986 * If expand_locals is not zero, identifiers of the form "%$*xxx"
987 * will be transformed into ..@ctxnum.xxx
989 static char *detoken(Token * tlist, int expand_locals)
991 Token *t;
992 int len;
993 char *line, *p;
995 len = 0;
996 for (t = tlist; t; t = t->next) {
997 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
998 char *p = getenv(t->text + 2);
999 nasm_free(t->text);
1000 if (p)
1001 t->text = nasm_strdup(p);
1002 else
1003 t->text = NULL;
1005 /* Expand local macros here and not during preprocessing */
1006 if (expand_locals &&
1007 t->type == TOK_PREPROC_ID && t->text &&
1008 t->text[0] == '%' && t->text[1] == '$') {
1009 Context *ctx = get_ctx(t->text, false);
1010 if (ctx) {
1011 char buffer[40];
1012 char *p, *q = t->text + 2;
1014 q += strspn(q, "$");
1015 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1016 p = nasm_strcat(buffer, q);
1017 nasm_free(t->text);
1018 t->text = p;
1021 if (t->type == TOK_WHITESPACE) {
1022 len++;
1023 } else if (t->text) {
1024 len += strlen(t->text);
1027 p = line = nasm_malloc(len + 1);
1028 for (t = tlist; t; t = t->next) {
1029 if (t->type == TOK_WHITESPACE) {
1030 *p = ' ';
1031 p++;
1032 *p = '\0';
1033 } else if (t->text) {
1034 strcpy(p, t->text);
1035 p += strlen(p);
1038 *p = '\0';
1039 return line;
1043 * A scanner, suitable for use by the expression evaluator, which
1044 * operates on a line of Tokens. Expects a pointer to a pointer to
1045 * the first token in the line to be passed in as its private_data
1046 * field.
1048 * FIX: This really needs to be unified with stdscan.
1050 static int ppscan(void *private_data, struct tokenval *tokval)
1052 Token **tlineptr = private_data;
1053 Token *tline;
1054 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1056 do {
1057 tline = *tlineptr;
1058 *tlineptr = tline ? tline->next : NULL;
1060 while (tline && (tline->type == TOK_WHITESPACE ||
1061 tline->type == TOK_COMMENT));
1063 if (!tline)
1064 return tokval->t_type = TOKEN_EOS;
1066 tokval->t_charptr = tline->text;
1068 if (tline->text[0] == '$' && !tline->text[1])
1069 return tokval->t_type = TOKEN_HERE;
1070 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1071 return tokval->t_type = TOKEN_BASE;
1073 if (tline->type == TOK_ID) {
1074 p = tokval->t_charptr = tline->text;
1075 if (p[0] == '$') {
1076 tokval->t_charptr++;
1077 return tokval->t_type = TOKEN_ID;
1080 for (r = p, s = ourcopy; *r; r++) {
1081 if (r > p+MAX_KEYWORD)
1082 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1083 *s++ = tolower(*r);
1085 *s = '\0';
1086 /* right, so we have an identifier sitting in temp storage. now,
1087 * is it actually a register or instruction name, or what? */
1088 return nasm_token_hash(ourcopy, tokval);
1091 if (tline->type == TOK_NUMBER) {
1092 bool rn_error;
1093 tokval->t_integer = readnum(tline->text, &rn_error);
1094 if (rn_error)
1095 return tokval->t_type = TOKEN_ERRNUM; /* some malformation occurred */
1096 tokval->t_charptr = tline->text;
1097 return tokval->t_type = TOKEN_NUM;
1100 if (tline->type == TOK_FLOAT) {
1101 return tokval->t_type = TOKEN_FLOAT;
1104 if (tline->type == TOK_STRING) {
1105 bool rn_warn;
1106 char q, *r;
1107 int l;
1109 r = tline->text;
1110 q = *r++;
1111 l = strlen(r);
1113 if (l == 0 || r[l - 1] != q)
1114 return tokval->t_type = TOKEN_ERRNUM;
1115 tokval->t_integer = readstrnum(r, l - 1, &rn_warn);
1116 if (rn_warn)
1117 error(ERR_WARNING | ERR_PASS1, "character constant too long");
1118 tokval->t_charptr = NULL;
1119 return tokval->t_type = TOKEN_NUM;
1122 if (tline->type == TOK_OTHER) {
1123 if (!strcmp(tline->text, "<<"))
1124 return tokval->t_type = TOKEN_SHL;
1125 if (!strcmp(tline->text, ">>"))
1126 return tokval->t_type = TOKEN_SHR;
1127 if (!strcmp(tline->text, "//"))
1128 return tokval->t_type = TOKEN_SDIV;
1129 if (!strcmp(tline->text, "%%"))
1130 return tokval->t_type = TOKEN_SMOD;
1131 if (!strcmp(tline->text, "=="))
1132 return tokval->t_type = TOKEN_EQ;
1133 if (!strcmp(tline->text, "<>"))
1134 return tokval->t_type = TOKEN_NE;
1135 if (!strcmp(tline->text, "!="))
1136 return tokval->t_type = TOKEN_NE;
1137 if (!strcmp(tline->text, "<="))
1138 return tokval->t_type = TOKEN_LE;
1139 if (!strcmp(tline->text, ">="))
1140 return tokval->t_type = TOKEN_GE;
1141 if (!strcmp(tline->text, "&&"))
1142 return tokval->t_type = TOKEN_DBL_AND;
1143 if (!strcmp(tline->text, "^^"))
1144 return tokval->t_type = TOKEN_DBL_XOR;
1145 if (!strcmp(tline->text, "||"))
1146 return tokval->t_type = TOKEN_DBL_OR;
1150 * We have no other options: just return the first character of
1151 * the token text.
1153 return tokval->t_type = tline->text[0];
1157 * Compare a string to the name of an existing macro; this is a
1158 * simple wrapper which calls either strcmp or nasm_stricmp
1159 * depending on the value of the `casesense' parameter.
1161 static int mstrcmp(const char *p, const char *q, bool casesense)
1163 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1167 * Return the Context structure associated with a %$ token. Return
1168 * NULL, having _already_ reported an error condition, if the
1169 * context stack isn't deep enough for the supplied number of $
1170 * signs.
1171 * If all_contexts == true, contexts that enclose current are
1172 * also scanned for such smacro, until it is found; if not -
1173 * only the context that directly results from the number of $'s
1174 * in variable's name.
1176 static Context *get_ctx(char *name, bool all_contexts)
1178 Context *ctx;
1179 SMacro *m;
1180 int i;
1182 if (!name || name[0] != '%' || name[1] != '$')
1183 return NULL;
1185 if (!cstk) {
1186 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1187 return NULL;
1190 for (i = strspn(name + 2, "$"), ctx = cstk; (i > 0) && ctx; i--) {
1191 ctx = ctx->next;
1192 /* i--; Lino - 02/25/02 */
1194 if (!ctx) {
1195 error(ERR_NONFATAL, "`%s': context stack is only"
1196 " %d level%s deep", name, i - 1, (i == 2 ? "" : "s"));
1197 return NULL;
1199 if (!all_contexts)
1200 return ctx;
1202 do {
1203 /* Search for this smacro in found context */
1204 m = ctx->localmac;
1205 while (m) {
1206 if (!mstrcmp(m->name, name, m->casesense))
1207 return ctx;
1208 m = m->next;
1210 ctx = ctx->next;
1212 while (ctx);
1213 return NULL;
1217 * Open an include file. This routine must always return a valid
1218 * file pointer if it returns - it's responsible for throwing an
1219 * ERR_FATAL and bombing out completely if not. It should also try
1220 * the include path one by one until it finds the file or reaches
1221 * the end of the path.
1223 static FILE *inc_fopen(char *file)
1225 FILE *fp;
1226 char *prefix = "", *combine;
1227 IncPath *ip = ipath;
1228 static int namelen = 0;
1229 int len = strlen(file);
1231 while (1) {
1232 combine = nasm_malloc(strlen(prefix) + len + 1);
1233 strcpy(combine, prefix);
1234 strcat(combine, file);
1235 fp = fopen(combine, "r");
1236 if (pass == 0 && fp) {
1237 namelen += strlen(combine) + 1;
1238 if (namelen > 62) {
1239 printf(" \\\n ");
1240 namelen = 2;
1242 printf(" %s", combine);
1244 nasm_free(combine);
1245 if (fp)
1246 return fp;
1247 if (!ip)
1248 break;
1249 prefix = ip->path;
1250 ip = ip->next;
1252 if (!prefix) {
1253 /* -MG given and file not found */
1254 if (pass == 0) {
1255 namelen += strlen(file) + 1;
1256 if (namelen > 62) {
1257 printf(" \\\n ");
1258 namelen = 2;
1260 printf(" %s", file);
1262 return NULL;
1266 error(ERR_FATAL, "unable to open include file `%s'", file);
1267 return NULL; /* never reached - placate compilers */
1271 * Search for a key in the hash index; adding it if necessary
1272 * (in which case we initialize the data pointer to NULL.)
1274 static void **
1275 hash_findi_add(struct hash_table *hash, const char *str)
1277 struct hash_insert hi;
1278 void **r;
1279 char *strx;
1281 r = hash_findi(hash, str, &hi);
1282 if (r)
1283 return r;
1285 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
1286 return hash_add(&hi, strx, NULL);
1290 * Like hash_findi, but returns the data element rather than a pointer
1291 * to it. Used only when not adding a new element, hence no third
1292 * argument.
1294 static void *
1295 hash_findix(struct hash_table *hash, const char *str)
1297 void **p;
1299 p = hash_findi(hash, str, NULL);
1300 return p ? *p : NULL;
1304 * Determine if we should warn on defining a single-line macro of
1305 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1306 * return true if _any_ single-line macro of that name is defined.
1307 * Otherwise, will return true if a single-line macro with either
1308 * `nparam' or no parameters is defined.
1310 * If a macro with precisely the right number of parameters is
1311 * defined, or nparam is -1, the address of the definition structure
1312 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1313 * is NULL, no action will be taken regarding its contents, and no
1314 * error will occur.
1316 * Note that this is also called with nparam zero to resolve
1317 * `ifdef'.
1319 * If you already know which context macro belongs to, you can pass
1320 * the context pointer as first parameter; if you won't but name begins
1321 * with %$ the context will be automatically computed. If all_contexts
1322 * is true, macro will be searched in outer contexts as well.
1324 static bool
1325 smacro_defined(Context * ctx, char *name, int nparam, SMacro ** defn,
1326 bool nocase)
1328 SMacro *m;
1330 if (ctx) {
1331 m = ctx->localmac;
1332 } else if (name[0] == '%' && name[1] == '$') {
1333 if (cstk)
1334 ctx = get_ctx(name, false);
1335 if (!ctx)
1336 return false; /* got to return _something_ */
1337 m = ctx->localmac;
1338 } else {
1339 m = (SMacro *) hash_findix(smacros, name);
1342 while (m) {
1343 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1344 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1345 if (defn) {
1346 if (nparam == (int) m->nparam || nparam == -1)
1347 *defn = m;
1348 else
1349 *defn = NULL;
1351 return true;
1353 m = m->next;
1356 return false;
1360 * Count and mark off the parameters in a multi-line macro call.
1361 * This is called both from within the multi-line macro expansion
1362 * code, and also to mark off the default parameters when provided
1363 * in a %macro definition line.
1365 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1367 int paramsize, brace;
1369 *nparam = paramsize = 0;
1370 *params = NULL;
1371 while (t) {
1372 if (*nparam >= paramsize) {
1373 paramsize += PARAM_DELTA;
1374 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1376 skip_white_(t);
1377 brace = false;
1378 if (tok_is_(t, "{"))
1379 brace = true;
1380 (*params)[(*nparam)++] = t;
1381 while (tok_isnt_(t, brace ? "}" : ","))
1382 t = t->next;
1383 if (t) { /* got a comma/brace */
1384 t = t->next;
1385 if (brace) {
1387 * Now we've found the closing brace, look further
1388 * for the comma.
1390 skip_white_(t);
1391 if (tok_isnt_(t, ",")) {
1392 error(ERR_NONFATAL,
1393 "braces do not enclose all of macro parameter");
1394 while (tok_isnt_(t, ","))
1395 t = t->next;
1397 if (t)
1398 t = t->next; /* eat the comma */
1405 * Determine whether one of the various `if' conditions is true or
1406 * not.
1408 * We must free the tline we get passed.
1410 static bool if_condition(Token * tline, enum preproc_token ct)
1412 enum pp_conditional i = PP_COND(ct);
1413 bool j;
1414 Token *t, *tt, **tptr, *origline;
1415 struct tokenval tokval;
1416 expr *evalresult;
1417 enum pp_token_type needtype;
1419 origline = tline;
1421 switch (i) {
1422 case PPC_IFCTX:
1423 j = false; /* have we matched yet? */
1424 while (cstk && tline) {
1425 skip_white_(tline);
1426 if (!tline || tline->type != TOK_ID) {
1427 error(ERR_NONFATAL,
1428 "`%s' expects context identifiers", pp_directives[ct]);
1429 free_tlist(origline);
1430 return -1;
1432 if (!nasm_stricmp(tline->text, cstk->name))
1433 j = true;
1434 tline = tline->next;
1436 break;
1438 case PPC_IFDEF:
1439 j = false; /* have we matched yet? */
1440 while (tline) {
1441 skip_white_(tline);
1442 if (!tline || (tline->type != TOK_ID &&
1443 (tline->type != TOK_PREPROC_ID ||
1444 tline->text[1] != '$'))) {
1445 error(ERR_NONFATAL,
1446 "`%s' expects macro identifiers", pp_directives[ct]);
1447 goto fail;
1449 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1450 j = true;
1451 tline = tline->next;
1453 break;
1455 case PPC_IFIDN:
1456 case PPC_IFIDNI:
1457 tline = expand_smacro(tline);
1458 t = tt = tline;
1459 while (tok_isnt_(tt, ","))
1460 tt = tt->next;
1461 if (!tt) {
1462 error(ERR_NONFATAL,
1463 "`%s' expects two comma-separated arguments",
1464 pp_directives[ct]);
1465 goto fail;
1467 tt = tt->next;
1468 j = true; /* assume equality unless proved not */
1469 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1470 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1471 error(ERR_NONFATAL, "`%s': more than one comma on line",
1472 pp_directives[ct]);
1473 goto fail;
1475 if (t->type == TOK_WHITESPACE) {
1476 t = t->next;
1477 continue;
1479 if (tt->type == TOK_WHITESPACE) {
1480 tt = tt->next;
1481 continue;
1483 if (tt->type != t->type) {
1484 j = false; /* found mismatching tokens */
1485 break;
1487 /* Unify surrounding quotes for strings */
1488 if (t->type == TOK_STRING) {
1489 tt->text[0] = t->text[0];
1490 tt->text[strlen(tt->text) - 1] = t->text[0];
1492 if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1493 j = false; /* found mismatching tokens */
1494 break;
1497 t = t->next;
1498 tt = tt->next;
1500 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1501 j = false; /* trailing gunk on one end or other */
1502 break;
1504 case PPC_IFMACRO:
1506 bool found = false;
1507 MMacro searching, *mmac;
1509 tline = tline->next;
1510 skip_white_(tline);
1511 tline = expand_id(tline);
1512 if (!tok_type_(tline, TOK_ID)) {
1513 error(ERR_NONFATAL,
1514 "`%s' expects a macro name", pp_directives[ct]);
1515 goto fail;
1517 searching.name = nasm_strdup(tline->text);
1518 searching.casesense = true;
1519 searching.plus = false;
1520 searching.nolist = false;
1521 searching.in_progress = 0;
1522 searching.rep_nest = NULL;
1523 searching.nparam_min = 0;
1524 searching.nparam_max = INT_MAX;
1525 tline = expand_smacro(tline->next);
1526 skip_white_(tline);
1527 if (!tline) {
1528 } else if (!tok_type_(tline, TOK_NUMBER)) {
1529 error(ERR_NONFATAL,
1530 "`%s' expects a parameter count or nothing",
1531 pp_directives[ct]);
1532 } else {
1533 searching.nparam_min = searching.nparam_max =
1534 readnum(tline->text, &j);
1535 if (j)
1536 error(ERR_NONFATAL,
1537 "unable to parse parameter count `%s'",
1538 tline->text);
1540 if (tline && tok_is_(tline->next, "-")) {
1541 tline = tline->next->next;
1542 if (tok_is_(tline, "*"))
1543 searching.nparam_max = INT_MAX;
1544 else if (!tok_type_(tline, TOK_NUMBER))
1545 error(ERR_NONFATAL,
1546 "`%s' expects a parameter count after `-'",
1547 pp_directives[ct]);
1548 else {
1549 searching.nparam_max = readnum(tline->text, &j);
1550 if (j)
1551 error(ERR_NONFATAL,
1552 "unable to parse parameter count `%s'",
1553 tline->text);
1554 if (searching.nparam_min > searching.nparam_max)
1555 error(ERR_NONFATAL,
1556 "minimum parameter count exceeds maximum");
1559 if (tline && tok_is_(tline->next, "+")) {
1560 tline = tline->next;
1561 searching.plus = true;
1563 mmac = (MMacro *) hash_findix(mmacros, searching.name);
1564 while (mmac) {
1565 if (!strcmp(mmac->name, searching.name) &&
1566 (mmac->nparam_min <= searching.nparam_max
1567 || searching.plus)
1568 && (searching.nparam_min <= mmac->nparam_max
1569 || mmac->plus)) {
1570 found = true;
1571 break;
1573 mmac = mmac->next;
1575 nasm_free(searching.name);
1576 j = found;
1577 break;
1580 case PPC_IFID:
1581 needtype = TOK_ID;
1582 goto iftype;
1583 case PPC_IFNUM:
1584 needtype = TOK_NUMBER;
1585 goto iftype;
1586 case PPC_IFSTR:
1587 needtype = TOK_STRING;
1588 goto iftype;
1590 iftype:
1591 tline = expand_smacro(tline);
1592 t = tline;
1593 while (tok_type_(t, TOK_WHITESPACE))
1594 t = t->next;
1595 j = false; /* placate optimiser */
1596 if (t)
1597 j = t->type == needtype;
1598 break;
1600 case PPC_IF:
1601 t = tline = expand_smacro(tline);
1602 tptr = &t;
1603 tokval.t_type = TOKEN_INVALID;
1604 evalresult = evaluate(ppscan, tptr, &tokval,
1605 NULL, pass | CRITICAL, error, NULL);
1606 if (!evalresult)
1607 return -1;
1608 if (tokval.t_type)
1609 error(ERR_WARNING,
1610 "trailing garbage after expression ignored");
1611 if (!is_simple(evalresult)) {
1612 error(ERR_NONFATAL,
1613 "non-constant value given to `%s'", pp_directives[ct]);
1614 goto fail;
1616 j = reloc_value(evalresult) != 0;
1617 return j;
1619 default:
1620 error(ERR_FATAL,
1621 "preprocessor directive `%s' not yet implemented",
1622 pp_directives[ct]);
1623 goto fail;
1626 free_tlist(origline);
1627 return j ^ PP_NEGATIVE(ct);
1629 fail:
1630 free_tlist(origline);
1631 return -1;
1635 * Expand macros in a string. Used in %error and %include directives.
1636 * First tokenize the string, apply "expand_smacro" and then de-tokenize back.
1637 * The returned variable should ALWAYS be freed after usage.
1639 void expand_macros_in_string(char **p)
1641 Token *line = tokenize(*p);
1642 line = expand_smacro(line);
1643 *p = detoken(line, false);
1647 * Common code for defining an smacro
1649 static bool define_smacro(Context *ctx, char *mname, bool casesense,
1650 int nparam, Token *expansion)
1652 SMacro *smac, **smhead;
1654 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1655 if (!smac) {
1656 error(ERR_WARNING,
1657 "single-line macro `%s' defined both with and"
1658 " without parameters", mname);
1660 /* Some instances of the old code considered this a failure,
1661 some others didn't. What is the right thing to do here? */
1662 free_tlist(expansion);
1663 return false; /* Failure */
1664 } else {
1666 * We're redefining, so we have to take over an
1667 * existing SMacro structure. This means freeing
1668 * what was already in it.
1670 nasm_free(smac->name);
1671 free_tlist(smac->expansion);
1673 } else {
1674 if (!ctx)
1675 smhead = (SMacro **) hash_findi_add(smacros, mname);
1676 else
1677 smhead = &ctx->localmac;
1679 smac = nasm_malloc(sizeof(SMacro));
1680 smac->next = *smhead;
1681 *smhead = smac;
1683 smac->name = nasm_strdup(mname);
1684 smac->casesense = casesense;
1685 smac->nparam = nparam;
1686 smac->expansion = expansion;
1687 smac->in_progress = false;
1688 return true; /* Success */
1692 * Undefine an smacro
1694 static void undef_smacro(Context *ctx, const char *mname)
1696 SMacro **smhead, *s, **sp;
1698 if (!ctx)
1699 smhead = (SMacro **) hash_findi(smacros, mname, NULL);
1700 else
1701 smhead = &ctx->localmac;
1703 if (smhead) {
1705 * We now have a macro name... go hunt for it.
1707 sp = smhead;
1708 while ((s = *sp) != NULL) {
1709 if (!mstrcmp(s->name, mname, s->casesense)) {
1710 *sp = s->next;
1711 nasm_free(s->name);
1712 free_tlist(s->expansion);
1713 nasm_free(s);
1714 } else {
1715 sp = &s->next;
1722 * find and process preprocessor directive in passed line
1723 * Find out if a line contains a preprocessor directive, and deal
1724 * with it if so.
1726 * If a directive _is_ found, it is the responsibility of this routine
1727 * (and not the caller) to free_tlist() the line.
1729 * @param tline a pointer to the current tokeninzed line linked list
1730 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
1733 static int do_directive(Token * tline)
1735 enum preproc_token i;
1736 int j;
1737 bool err;
1738 int nparam;
1739 bool nolist;
1740 bool casesense;
1741 int k, m;
1742 int offset;
1743 char *p, *mname;
1744 Include *inc;
1745 Context *ctx;
1746 Cond *cond;
1747 MMacro *mmac, **mmhead;
1748 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
1749 Line *l;
1750 struct tokenval tokval;
1751 expr *evalresult;
1752 MMacro *tmp_defining; /* Used when manipulating rep_nest */
1753 int64_t count;
1755 origline = tline;
1757 skip_white_(tline);
1758 if (!tok_type_(tline, TOK_PREPROC_ID) ||
1759 (tline->text[1] == '%' || tline->text[1] == '$'
1760 || tline->text[1] == '!'))
1761 return NO_DIRECTIVE_FOUND;
1763 i = pp_token_hash(tline->text);
1766 * If we're in a non-emitting branch of a condition construct,
1767 * or walking to the end of an already terminated %rep block,
1768 * we should ignore all directives except for condition
1769 * directives.
1771 if (((istk->conds && !emitting(istk->conds->state)) ||
1772 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
1773 return NO_DIRECTIVE_FOUND;
1777 * If we're defining a macro or reading a %rep block, we should
1778 * ignore all directives except for %macro/%imacro (which
1779 * generate an error), %endm/%endmacro, and (only if we're in a
1780 * %rep block) %endrep. If we're in a %rep block, another %rep
1781 * causes an error, so should be let through.
1783 if (defining && i != PP_MACRO && i != PP_IMACRO &&
1784 i != PP_ENDMACRO && i != PP_ENDM &&
1785 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
1786 return NO_DIRECTIVE_FOUND;
1789 switch (i) {
1790 case PP_INVALID:
1791 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
1792 tline->text);
1793 return NO_DIRECTIVE_FOUND; /* didn't get it */
1795 case PP_STACKSIZE:
1796 /* Directive to tell NASM what the default stack size is. The
1797 * default is for a 16-bit stack, and this can be overriden with
1798 * %stacksize large.
1799 * the following form:
1801 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1803 tline = tline->next;
1804 if (tline && tline->type == TOK_WHITESPACE)
1805 tline = tline->next;
1806 if (!tline || tline->type != TOK_ID) {
1807 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
1808 free_tlist(origline);
1809 return DIRECTIVE_FOUND;
1811 if (nasm_stricmp(tline->text, "flat") == 0) {
1812 /* All subsequent ARG directives are for a 32-bit stack */
1813 StackSize = 4;
1814 StackPointer = "ebp";
1815 ArgOffset = 8;
1816 LocalOffset = 4;
1817 } else if (nasm_stricmp(tline->text, "large") == 0) {
1818 /* All subsequent ARG directives are for a 16-bit stack,
1819 * far function call.
1821 StackSize = 2;
1822 StackPointer = "bp";
1823 ArgOffset = 4;
1824 LocalOffset = 2;
1825 } else if (nasm_stricmp(tline->text, "small") == 0) {
1826 /* All subsequent ARG directives are for a 16-bit stack,
1827 * far function call. We don't support near functions.
1829 StackSize = 2;
1830 StackPointer = "bp";
1831 ArgOffset = 6;
1832 LocalOffset = 2;
1833 } else {
1834 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
1835 free_tlist(origline);
1836 return DIRECTIVE_FOUND;
1838 free_tlist(origline);
1839 return DIRECTIVE_FOUND;
1841 case PP_ARG:
1842 /* TASM like ARG directive to define arguments to functions, in
1843 * the following form:
1845 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1847 offset = ArgOffset;
1848 do {
1849 char *arg, directive[256];
1850 int size = StackSize;
1852 /* Find the argument name */
1853 tline = tline->next;
1854 if (tline && tline->type == TOK_WHITESPACE)
1855 tline = tline->next;
1856 if (!tline || tline->type != TOK_ID) {
1857 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
1858 free_tlist(origline);
1859 return DIRECTIVE_FOUND;
1861 arg = tline->text;
1863 /* Find the argument size type */
1864 tline = tline->next;
1865 if (!tline || tline->type != TOK_OTHER
1866 || tline->text[0] != ':') {
1867 error(ERR_NONFATAL,
1868 "Syntax error processing `%%arg' directive");
1869 free_tlist(origline);
1870 return DIRECTIVE_FOUND;
1872 tline = tline->next;
1873 if (!tline || tline->type != TOK_ID) {
1874 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
1875 free_tlist(origline);
1876 return DIRECTIVE_FOUND;
1879 /* Allow macro expansion of type parameter */
1880 tt = tokenize(tline->text);
1881 tt = expand_smacro(tt);
1882 if (nasm_stricmp(tt->text, "byte") == 0) {
1883 size = MAX(StackSize, 1);
1884 } else if (nasm_stricmp(tt->text, "word") == 0) {
1885 size = MAX(StackSize, 2);
1886 } else if (nasm_stricmp(tt->text, "dword") == 0) {
1887 size = MAX(StackSize, 4);
1888 } else if (nasm_stricmp(tt->text, "qword") == 0) {
1889 size = MAX(StackSize, 8);
1890 } else if (nasm_stricmp(tt->text, "tword") == 0) {
1891 size = MAX(StackSize, 10);
1892 } else {
1893 error(ERR_NONFATAL,
1894 "Invalid size type for `%%arg' missing directive");
1895 free_tlist(tt);
1896 free_tlist(origline);
1897 return DIRECTIVE_FOUND;
1899 free_tlist(tt);
1901 /* Now define the macro for the argument */
1902 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
1903 arg, StackPointer, offset);
1904 do_directive(tokenize(directive));
1905 offset += size;
1907 /* Move to the next argument in the list */
1908 tline = tline->next;
1909 if (tline && tline->type == TOK_WHITESPACE)
1910 tline = tline->next;
1912 while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
1913 free_tlist(origline);
1914 return DIRECTIVE_FOUND;
1916 case PP_LOCAL:
1917 /* TASM like LOCAL directive to define local variables for a
1918 * function, in the following form:
1920 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
1922 * The '= LocalSize' at the end is ignored by NASM, but is
1923 * required by TASM to define the local parameter size (and used
1924 * by the TASM macro package).
1926 offset = LocalOffset;
1927 do {
1928 char *local, directive[256];
1929 int size = StackSize;
1931 /* Find the argument name */
1932 tline = tline->next;
1933 if (tline && tline->type == TOK_WHITESPACE)
1934 tline = tline->next;
1935 if (!tline || tline->type != TOK_ID) {
1936 error(ERR_NONFATAL,
1937 "`%%local' missing argument parameter");
1938 free_tlist(origline);
1939 return DIRECTIVE_FOUND;
1941 local = tline->text;
1943 /* Find the argument size type */
1944 tline = tline->next;
1945 if (!tline || tline->type != TOK_OTHER
1946 || tline->text[0] != ':') {
1947 error(ERR_NONFATAL,
1948 "Syntax error processing `%%local' directive");
1949 free_tlist(origline);
1950 return DIRECTIVE_FOUND;
1952 tline = tline->next;
1953 if (!tline || tline->type != TOK_ID) {
1954 error(ERR_NONFATAL,
1955 "`%%local' missing size type parameter");
1956 free_tlist(origline);
1957 return DIRECTIVE_FOUND;
1960 /* Allow macro expansion of type parameter */
1961 tt = tokenize(tline->text);
1962 tt = expand_smacro(tt);
1963 if (nasm_stricmp(tt->text, "byte") == 0) {
1964 size = MAX(StackSize, 1);
1965 } else if (nasm_stricmp(tt->text, "word") == 0) {
1966 size = MAX(StackSize, 2);
1967 } else if (nasm_stricmp(tt->text, "dword") == 0) {
1968 size = MAX(StackSize, 4);
1969 } else if (nasm_stricmp(tt->text, "qword") == 0) {
1970 size = MAX(StackSize, 8);
1971 } else if (nasm_stricmp(tt->text, "tword") == 0) {
1972 size = MAX(StackSize, 10);
1973 } else {
1974 error(ERR_NONFATAL,
1975 "Invalid size type for `%%local' missing directive");
1976 free_tlist(tt);
1977 free_tlist(origline);
1978 return DIRECTIVE_FOUND;
1980 free_tlist(tt);
1982 /* Now define the macro for the argument */
1983 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
1984 local, StackPointer, offset);
1985 do_directive(tokenize(directive));
1986 offset += size;
1988 /* Now define the assign to setup the enter_c macro correctly */
1989 snprintf(directive, sizeof(directive),
1990 "%%assign %%$localsize %%$localsize+%d", size);
1991 do_directive(tokenize(directive));
1993 /* Move to the next argument in the list */
1994 tline = tline->next;
1995 if (tline && tline->type == TOK_WHITESPACE)
1996 tline = tline->next;
1998 while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
1999 free_tlist(origline);
2000 return DIRECTIVE_FOUND;
2002 case PP_CLEAR:
2003 if (tline->next)
2004 error(ERR_WARNING, "trailing garbage after `%%clear' ignored");
2005 free_macros();
2006 init_macros();
2007 free_tlist(origline);
2008 return DIRECTIVE_FOUND;
2010 case PP_INCLUDE:
2011 tline = tline->next;
2012 skip_white_(tline);
2013 if (!tline || (tline->type != TOK_STRING &&
2014 tline->type != TOK_INTERNAL_STRING)) {
2015 error(ERR_NONFATAL, "`%%include' expects a file name");
2016 free_tlist(origline);
2017 return DIRECTIVE_FOUND; /* but we did _something_ */
2019 if (tline->next)
2020 error(ERR_WARNING,
2021 "trailing garbage after `%%include' ignored");
2022 if (tline->type != TOK_INTERNAL_STRING) {
2023 p = tline->text + 1; /* point past the quote to the name */
2024 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
2025 } else
2026 p = tline->text; /* internal_string is easier */
2027 expand_macros_in_string(&p);
2028 inc = nasm_malloc(sizeof(Include));
2029 inc->next = istk;
2030 inc->conds = NULL;
2031 inc->fp = inc_fopen(p);
2032 if (!inc->fp && pass == 0) {
2033 /* -MG given but file not found */
2034 nasm_free(inc);
2035 } else {
2036 inc->fname = src_set_fname(p);
2037 inc->lineno = src_set_linnum(0);
2038 inc->lineinc = 1;
2039 inc->expansion = NULL;
2040 inc->mstk = NULL;
2041 istk = inc;
2042 list->uplevel(LIST_INCLUDE);
2044 free_tlist(origline);
2045 return DIRECTIVE_FOUND;
2047 case PP_PUSH:
2048 tline = tline->next;
2049 skip_white_(tline);
2050 tline = expand_id(tline);
2051 if (!tok_type_(tline, TOK_ID)) {
2052 error(ERR_NONFATAL, "`%%push' expects a context identifier");
2053 free_tlist(origline);
2054 return DIRECTIVE_FOUND; /* but we did _something_ */
2056 if (tline->next)
2057 error(ERR_WARNING, "trailing garbage after `%%push' ignored");
2058 ctx = nasm_malloc(sizeof(Context));
2059 ctx->next = cstk;
2060 ctx->localmac = NULL;
2061 ctx->name = nasm_strdup(tline->text);
2062 ctx->number = unique++;
2063 cstk = ctx;
2064 free_tlist(origline);
2065 break;
2067 case PP_REPL:
2068 tline = tline->next;
2069 skip_white_(tline);
2070 tline = expand_id(tline);
2071 if (!tok_type_(tline, TOK_ID)) {
2072 error(ERR_NONFATAL, "`%%repl' expects a context identifier");
2073 free_tlist(origline);
2074 return DIRECTIVE_FOUND; /* but we did _something_ */
2076 if (tline->next)
2077 error(ERR_WARNING, "trailing garbage after `%%repl' ignored");
2078 if (!cstk)
2079 error(ERR_NONFATAL, "`%%repl': context stack is empty");
2080 else {
2081 nasm_free(cstk->name);
2082 cstk->name = nasm_strdup(tline->text);
2084 free_tlist(origline);
2085 break;
2087 case PP_POP:
2088 if (tline->next)
2089 error(ERR_WARNING, "trailing garbage after `%%pop' ignored");
2090 if (!cstk)
2091 error(ERR_NONFATAL, "`%%pop': context stack is already empty");
2092 else
2093 ctx_pop();
2094 free_tlist(origline);
2095 break;
2097 case PP_ERROR:
2098 tline->next = expand_smacro(tline->next);
2099 tline = tline->next;
2100 skip_white_(tline);
2101 if (tok_type_(tline, TOK_STRING)) {
2102 p = tline->text + 1; /* point past the quote to the name */
2103 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
2104 expand_macros_in_string(&p);
2105 error(ERR_NONFATAL, "%s", p);
2106 nasm_free(p);
2107 } else {
2108 p = detoken(tline, false);
2109 error(ERR_WARNING, "%s", p);
2110 nasm_free(p);
2112 free_tlist(origline);
2113 break;
2115 CASE_PP_IF:
2116 if (istk->conds && !emitting(istk->conds->state))
2117 j = COND_NEVER;
2118 else {
2119 j = if_condition(tline->next, i);
2120 tline->next = NULL; /* it got freed */
2121 free_tlist(origline);
2122 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2124 cond = nasm_malloc(sizeof(Cond));
2125 cond->next = istk->conds;
2126 cond->state = j;
2127 istk->conds = cond;
2128 return DIRECTIVE_FOUND;
2130 CASE_PP_ELIF:
2131 if (!istk->conds)
2132 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2133 if (emitting(istk->conds->state)
2134 || istk->conds->state == COND_NEVER)
2135 istk->conds->state = COND_NEVER;
2136 else {
2138 * IMPORTANT: In the case of %if, we will already have
2139 * called expand_mmac_params(); however, if we're
2140 * processing an %elif we must have been in a
2141 * non-emitting mode, which would have inhibited
2142 * the normal invocation of expand_mmac_params(). Therefore,
2143 * we have to do it explicitly here.
2145 j = if_condition(expand_mmac_params(tline->next), i);
2146 tline->next = NULL; /* it got freed */
2147 free_tlist(origline);
2148 istk->conds->state =
2149 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2151 return DIRECTIVE_FOUND;
2153 case PP_ELSE:
2154 if (tline->next)
2155 error(ERR_WARNING, "trailing garbage after `%%else' ignored");
2156 if (!istk->conds)
2157 error(ERR_FATAL, "`%%else': no matching `%%if'");
2158 if (emitting(istk->conds->state)
2159 || istk->conds->state == COND_NEVER)
2160 istk->conds->state = COND_ELSE_FALSE;
2161 else
2162 istk->conds->state = COND_ELSE_TRUE;
2163 free_tlist(origline);
2164 return DIRECTIVE_FOUND;
2166 case PP_ENDIF:
2167 if (tline->next)
2168 error(ERR_WARNING, "trailing garbage after `%%endif' ignored");
2169 if (!istk->conds)
2170 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2171 cond = istk->conds;
2172 istk->conds = cond->next;
2173 nasm_free(cond);
2174 free_tlist(origline);
2175 return DIRECTIVE_FOUND;
2177 case PP_MACRO:
2178 case PP_IMACRO:
2179 if (defining)
2180 error(ERR_FATAL,
2181 "`%%%smacro': already defining a macro",
2182 (i == PP_IMACRO ? "i" : ""));
2183 tline = tline->next;
2184 skip_white_(tline);
2185 tline = expand_id(tline);
2186 if (!tok_type_(tline, TOK_ID)) {
2187 error(ERR_NONFATAL,
2188 "`%%%smacro' expects a macro name",
2189 (i == PP_IMACRO ? "i" : ""));
2190 return DIRECTIVE_FOUND;
2192 defining = nasm_malloc(sizeof(MMacro));
2193 defining->name = nasm_strdup(tline->text);
2194 defining->casesense = (i == PP_MACRO);
2195 defining->plus = false;
2196 defining->nolist = false;
2197 defining->in_progress = 0;
2198 defining->rep_nest = NULL;
2199 tline = expand_smacro(tline->next);
2200 skip_white_(tline);
2201 if (!tok_type_(tline, TOK_NUMBER)) {
2202 error(ERR_NONFATAL,
2203 "`%%%smacro' expects a parameter count",
2204 (i == PP_IMACRO ? "i" : ""));
2205 defining->nparam_min = defining->nparam_max = 0;
2206 } else {
2207 defining->nparam_min = defining->nparam_max =
2208 readnum(tline->text, &err);
2209 if (err)
2210 error(ERR_NONFATAL,
2211 "unable to parse parameter count `%s'", tline->text);
2213 if (tline && tok_is_(tline->next, "-")) {
2214 tline = tline->next->next;
2215 if (tok_is_(tline, "*"))
2216 defining->nparam_max = INT_MAX;
2217 else if (!tok_type_(tline, TOK_NUMBER))
2218 error(ERR_NONFATAL,
2219 "`%%%smacro' expects a parameter count after `-'",
2220 (i == PP_IMACRO ? "i" : ""));
2221 else {
2222 defining->nparam_max = readnum(tline->text, &err);
2223 if (err)
2224 error(ERR_NONFATAL,
2225 "unable to parse parameter count `%s'",
2226 tline->text);
2227 if (defining->nparam_min > defining->nparam_max)
2228 error(ERR_NONFATAL,
2229 "minimum parameter count exceeds maximum");
2232 if (tline && tok_is_(tline->next, "+")) {
2233 tline = tline->next;
2234 defining->plus = true;
2236 if (tline && tok_type_(tline->next, TOK_ID) &&
2237 !nasm_stricmp(tline->next->text, ".nolist")) {
2238 tline = tline->next;
2239 defining->nolist = true;
2241 mmac = (MMacro *) hash_findix(mmacros, defining->name);
2242 while (mmac) {
2243 if (!strcmp(mmac->name, defining->name) &&
2244 (mmac->nparam_min <= defining->nparam_max
2245 || defining->plus)
2246 && (defining->nparam_min <= mmac->nparam_max
2247 || mmac->plus)) {
2248 error(ERR_WARNING,
2249 "redefining multi-line macro `%s'", defining->name);
2250 break;
2252 mmac = mmac->next;
2255 * Handle default parameters.
2257 if (tline && tline->next) {
2258 defining->dlist = tline->next;
2259 tline->next = NULL;
2260 count_mmac_params(defining->dlist, &defining->ndefs,
2261 &defining->defaults);
2262 } else {
2263 defining->dlist = NULL;
2264 defining->defaults = NULL;
2266 defining->expansion = NULL;
2267 free_tlist(origline);
2268 return DIRECTIVE_FOUND;
2270 case PP_ENDM:
2271 case PP_ENDMACRO:
2272 if (!defining) {
2273 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2274 return DIRECTIVE_FOUND;
2276 mmhead = (MMacro **) hash_findi_add(mmacros, defining->name);
2277 defining->next = *mmhead;
2278 *mmhead = defining;
2279 defining = NULL;
2280 free_tlist(origline);
2281 return DIRECTIVE_FOUND;
2283 case PP_ROTATE:
2284 if (tline->next && tline->next->type == TOK_WHITESPACE)
2285 tline = tline->next;
2286 if (tline->next == NULL) {
2287 free_tlist(origline);
2288 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2289 return DIRECTIVE_FOUND;
2291 t = expand_smacro(tline->next);
2292 tline->next = NULL;
2293 free_tlist(origline);
2294 tline = t;
2295 tptr = &t;
2296 tokval.t_type = TOKEN_INVALID;
2297 evalresult =
2298 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2299 free_tlist(tline);
2300 if (!evalresult)
2301 return DIRECTIVE_FOUND;
2302 if (tokval.t_type)
2303 error(ERR_WARNING,
2304 "trailing garbage after expression ignored");
2305 if (!is_simple(evalresult)) {
2306 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2307 return DIRECTIVE_FOUND;
2309 mmac = istk->mstk;
2310 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2311 mmac = mmac->next_active;
2312 if (!mmac) {
2313 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2314 } else if (mmac->nparam == 0) {
2315 error(ERR_NONFATAL,
2316 "`%%rotate' invoked within macro without parameters");
2317 } else {
2318 int rotate = mmac->rotate + reloc_value(evalresult);
2320 rotate %= (int)mmac->nparam;
2321 if (rotate < 0)
2322 rotate += mmac->nparam;
2324 mmac->rotate = rotate;
2326 return DIRECTIVE_FOUND;
2328 case PP_REP:
2329 nolist = false;
2330 do {
2331 tline = tline->next;
2332 } while (tok_type_(tline, TOK_WHITESPACE));
2334 if (tok_type_(tline, TOK_ID) &&
2335 nasm_stricmp(tline->text, ".nolist") == 0) {
2336 nolist = true;
2337 do {
2338 tline = tline->next;
2339 } while (tok_type_(tline, TOK_WHITESPACE));
2342 if (tline) {
2343 t = expand_smacro(tline);
2344 tptr = &t;
2345 tokval.t_type = TOKEN_INVALID;
2346 evalresult =
2347 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2348 if (!evalresult) {
2349 free_tlist(origline);
2350 return DIRECTIVE_FOUND;
2352 if (tokval.t_type)
2353 error(ERR_WARNING,
2354 "trailing garbage after expression ignored");
2355 if (!is_simple(evalresult)) {
2356 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2357 return DIRECTIVE_FOUND;
2359 count = reloc_value(evalresult) + 1;
2360 } else {
2361 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2362 count = 0;
2364 free_tlist(origline);
2366 tmp_defining = defining;
2367 defining = nasm_malloc(sizeof(MMacro));
2368 defining->name = NULL; /* flags this macro as a %rep block */
2369 defining->casesense = false;
2370 defining->plus = false;
2371 defining->nolist = nolist;
2372 defining->in_progress = count;
2373 defining->nparam_min = defining->nparam_max = 0;
2374 defining->defaults = NULL;
2375 defining->dlist = NULL;
2376 defining->expansion = NULL;
2377 defining->next_active = istk->mstk;
2378 defining->rep_nest = tmp_defining;
2379 return DIRECTIVE_FOUND;
2381 case PP_ENDREP:
2382 if (!defining || defining->name) {
2383 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2384 return DIRECTIVE_FOUND;
2388 * Now we have a "macro" defined - although it has no name
2389 * and we won't be entering it in the hash tables - we must
2390 * push a macro-end marker for it on to istk->expansion.
2391 * After that, it will take care of propagating itself (a
2392 * macro-end marker line for a macro which is really a %rep
2393 * block will cause the macro to be re-expanded, complete
2394 * with another macro-end marker to ensure the process
2395 * continues) until the whole expansion is forcibly removed
2396 * from istk->expansion by a %exitrep.
2398 l = nasm_malloc(sizeof(Line));
2399 l->next = istk->expansion;
2400 l->finishes = defining;
2401 l->first = NULL;
2402 istk->expansion = l;
2404 istk->mstk = defining;
2406 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2407 tmp_defining = defining;
2408 defining = defining->rep_nest;
2409 free_tlist(origline);
2410 return DIRECTIVE_FOUND;
2412 case PP_EXITREP:
2414 * We must search along istk->expansion until we hit a
2415 * macro-end marker for a macro with no name. Then we set
2416 * its `in_progress' flag to 0.
2418 for (l = istk->expansion; l; l = l->next)
2419 if (l->finishes && !l->finishes->name)
2420 break;
2422 if (l)
2423 l->finishes->in_progress = 0;
2424 else
2425 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2426 free_tlist(origline);
2427 return DIRECTIVE_FOUND;
2429 case PP_XDEFINE:
2430 case PP_IXDEFINE:
2431 case PP_DEFINE:
2432 case PP_IDEFINE:
2433 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2435 tline = tline->next;
2436 skip_white_(tline);
2437 tline = expand_id(tline);
2438 if (!tline || (tline->type != TOK_ID &&
2439 (tline->type != TOK_PREPROC_ID ||
2440 tline->text[1] != '$'))) {
2441 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2442 pp_directives[i]);
2443 free_tlist(origline);
2444 return DIRECTIVE_FOUND;
2447 ctx = get_ctx(tline->text, false);
2449 mname = tline->text;
2450 last = tline;
2451 param_start = tline = tline->next;
2452 nparam = 0;
2454 /* Expand the macro definition now for %xdefine and %ixdefine */
2455 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2456 tline = expand_smacro(tline);
2458 if (tok_is_(tline, "(")) {
2460 * This macro has parameters.
2463 tline = tline->next;
2464 while (1) {
2465 skip_white_(tline);
2466 if (!tline) {
2467 error(ERR_NONFATAL, "parameter identifier expected");
2468 free_tlist(origline);
2469 return DIRECTIVE_FOUND;
2471 if (tline->type != TOK_ID) {
2472 error(ERR_NONFATAL,
2473 "`%s': parameter identifier expected",
2474 tline->text);
2475 free_tlist(origline);
2476 return DIRECTIVE_FOUND;
2478 tline->type = TOK_SMAC_PARAM + nparam++;
2479 tline = tline->next;
2480 skip_white_(tline);
2481 if (tok_is_(tline, ",")) {
2482 tline = tline->next;
2483 continue;
2485 if (!tok_is_(tline, ")")) {
2486 error(ERR_NONFATAL,
2487 "`)' expected to terminate macro template");
2488 free_tlist(origline);
2489 return DIRECTIVE_FOUND;
2491 break;
2493 last = tline;
2494 tline = tline->next;
2496 if (tok_type_(tline, TOK_WHITESPACE))
2497 last = tline, tline = tline->next;
2498 macro_start = NULL;
2499 last->next = NULL;
2500 t = tline;
2501 while (t) {
2502 if (t->type == TOK_ID) {
2503 for (tt = param_start; tt; tt = tt->next)
2504 if (tt->type >= TOK_SMAC_PARAM &&
2505 !strcmp(tt->text, t->text))
2506 t->type = tt->type;
2508 tt = t->next;
2509 t->next = macro_start;
2510 macro_start = t;
2511 t = tt;
2514 * Good. We now have a macro name, a parameter count, and a
2515 * token list (in reverse order) for an expansion. We ought
2516 * to be OK just to create an SMacro, store it, and let
2517 * free_tlist have the rest of the line (which we have
2518 * carefully re-terminated after chopping off the expansion
2519 * from the end).
2521 define_smacro(ctx, mname, casesense, nparam, macro_start);
2522 free_tlist(origline);
2523 return DIRECTIVE_FOUND;
2525 case PP_UNDEF:
2526 tline = tline->next;
2527 skip_white_(tline);
2528 tline = expand_id(tline);
2529 if (!tline || (tline->type != TOK_ID &&
2530 (tline->type != TOK_PREPROC_ID ||
2531 tline->text[1] != '$'))) {
2532 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2533 free_tlist(origline);
2534 return DIRECTIVE_FOUND;
2536 if (tline->next) {
2537 error(ERR_WARNING,
2538 "trailing garbage after macro name ignored");
2541 /* Find the context that symbol belongs to */
2542 ctx = get_ctx(tline->text, false);
2543 undef_smacro(ctx, tline->text);
2544 free_tlist(origline);
2545 return DIRECTIVE_FOUND;
2547 case PP_STRLEN:
2548 casesense = true;
2550 tline = tline->next;
2551 skip_white_(tline);
2552 tline = expand_id(tline);
2553 if (!tline || (tline->type != TOK_ID &&
2554 (tline->type != TOK_PREPROC_ID ||
2555 tline->text[1] != '$'))) {
2556 error(ERR_NONFATAL,
2557 "`%%strlen' expects a macro identifier as first parameter");
2558 free_tlist(origline);
2559 return DIRECTIVE_FOUND;
2561 ctx = get_ctx(tline->text, false);
2563 mname = tline->text;
2564 last = tline;
2565 tline = expand_smacro(tline->next);
2566 last->next = NULL;
2568 t = tline;
2569 while (tok_type_(t, TOK_WHITESPACE))
2570 t = t->next;
2571 /* t should now point to the string */
2572 if (t->type != TOK_STRING) {
2573 error(ERR_NONFATAL,
2574 "`%%strlen` requires string as second parameter");
2575 free_tlist(tline);
2576 free_tlist(origline);
2577 return DIRECTIVE_FOUND;
2580 macro_start = nasm_malloc(sizeof(*macro_start));
2581 macro_start->next = NULL;
2582 make_tok_num(macro_start, strlen(t->text) - 2);
2583 macro_start->mac = NULL;
2586 * We now have a macro name, an implicit parameter count of
2587 * zero, and a numeric token to use as an expansion. Create
2588 * and store an SMacro.
2590 define_smacro(ctx, mname, casesense, 0, macro_start);
2591 free_tlist(tline);
2592 free_tlist(origline);
2593 return DIRECTIVE_FOUND;
2595 case PP_SUBSTR:
2596 casesense = true;
2598 tline = tline->next;
2599 skip_white_(tline);
2600 tline = expand_id(tline);
2601 if (!tline || (tline->type != TOK_ID &&
2602 (tline->type != TOK_PREPROC_ID ||
2603 tline->text[1] != '$'))) {
2604 error(ERR_NONFATAL,
2605 "`%%substr' expects a macro identifier as first parameter");
2606 free_tlist(origline);
2607 return DIRECTIVE_FOUND;
2609 ctx = get_ctx(tline->text, false);
2611 mname = tline->text;
2612 last = tline;
2613 tline = expand_smacro(tline->next);
2614 last->next = NULL;
2616 t = tline->next;
2617 while (tok_type_(t, TOK_WHITESPACE))
2618 t = t->next;
2620 /* t should now point to the string */
2621 if (t->type != TOK_STRING) {
2622 error(ERR_NONFATAL,
2623 "`%%substr` requires string as second parameter");
2624 free_tlist(tline);
2625 free_tlist(origline);
2626 return DIRECTIVE_FOUND;
2629 tt = t->next;
2630 tptr = &tt;
2631 tokval.t_type = TOKEN_INVALID;
2632 evalresult =
2633 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2634 if (!evalresult) {
2635 free_tlist(tline);
2636 free_tlist(origline);
2637 return DIRECTIVE_FOUND;
2639 if (!is_simple(evalresult)) {
2640 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
2641 free_tlist(tline);
2642 free_tlist(origline);
2643 return DIRECTIVE_FOUND;
2646 macro_start = nasm_malloc(sizeof(*macro_start));
2647 macro_start->next = NULL;
2648 macro_start->text = nasm_strdup("'''");
2649 if (evalresult->value > 0
2650 && evalresult->value < (int) strlen(t->text) - 1) {
2651 macro_start->text[1] = t->text[evalresult->value];
2652 } else {
2653 macro_start->text[2] = '\0';
2655 macro_start->type = TOK_STRING;
2656 macro_start->mac = NULL;
2659 * We now have a macro name, an implicit parameter count of
2660 * zero, and a numeric token to use as an expansion. Create
2661 * and store an SMacro.
2663 define_smacro(ctx, mname, casesense, 0, macro_start);
2664 free_tlist(tline);
2665 free_tlist(origline);
2666 return DIRECTIVE_FOUND;
2668 case PP_ASSIGN:
2669 case PP_IASSIGN:
2670 casesense = (i == PP_ASSIGN);
2672 tline = tline->next;
2673 skip_white_(tline);
2674 tline = expand_id(tline);
2675 if (!tline || (tline->type != TOK_ID &&
2676 (tline->type != TOK_PREPROC_ID ||
2677 tline->text[1] != '$'))) {
2678 error(ERR_NONFATAL,
2679 "`%%%sassign' expects a macro identifier",
2680 (i == PP_IASSIGN ? "i" : ""));
2681 free_tlist(origline);
2682 return DIRECTIVE_FOUND;
2684 ctx = get_ctx(tline->text, false);
2686 mname = tline->text;
2687 last = tline;
2688 tline = expand_smacro(tline->next);
2689 last->next = NULL;
2691 t = tline;
2692 tptr = &t;
2693 tokval.t_type = TOKEN_INVALID;
2694 evalresult =
2695 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2696 free_tlist(tline);
2697 if (!evalresult) {
2698 free_tlist(origline);
2699 return DIRECTIVE_FOUND;
2702 if (tokval.t_type)
2703 error(ERR_WARNING,
2704 "trailing garbage after expression ignored");
2706 if (!is_simple(evalresult)) {
2707 error(ERR_NONFATAL,
2708 "non-constant value given to `%%%sassign'",
2709 (i == PP_IASSIGN ? "i" : ""));
2710 free_tlist(origline);
2711 return DIRECTIVE_FOUND;
2714 macro_start = nasm_malloc(sizeof(*macro_start));
2715 macro_start->next = NULL;
2716 make_tok_num(macro_start, reloc_value(evalresult));
2717 macro_start->mac = NULL;
2720 * We now have a macro name, an implicit parameter count of
2721 * zero, and a numeric token to use as an expansion. Create
2722 * and store an SMacro.
2724 define_smacro(ctx, mname, casesense, 0, macro_start);
2725 free_tlist(origline);
2726 return DIRECTIVE_FOUND;
2728 case PP_LINE:
2730 * Syntax is `%line nnn[+mmm] [filename]'
2732 tline = tline->next;
2733 skip_white_(tline);
2734 if (!tok_type_(tline, TOK_NUMBER)) {
2735 error(ERR_NONFATAL, "`%%line' expects line number");
2736 free_tlist(origline);
2737 return DIRECTIVE_FOUND;
2739 k = readnum(tline->text, &err);
2740 m = 1;
2741 tline = tline->next;
2742 if (tok_is_(tline, "+")) {
2743 tline = tline->next;
2744 if (!tok_type_(tline, TOK_NUMBER)) {
2745 error(ERR_NONFATAL, "`%%line' expects line increment");
2746 free_tlist(origline);
2747 return DIRECTIVE_FOUND;
2749 m = readnum(tline->text, &err);
2750 tline = tline->next;
2752 skip_white_(tline);
2753 src_set_linnum(k);
2754 istk->lineinc = m;
2755 if (tline) {
2756 nasm_free(src_set_fname(detoken(tline, false)));
2758 free_tlist(origline);
2759 return DIRECTIVE_FOUND;
2761 default:
2762 error(ERR_FATAL,
2763 "preprocessor directive `%s' not yet implemented",
2764 pp_directives[i]);
2765 break;
2767 return DIRECTIVE_FOUND;
2771 * Ensure that a macro parameter contains a condition code and
2772 * nothing else. Return the condition code index if so, or -1
2773 * otherwise.
2775 static int find_cc(Token * t)
2777 Token *tt;
2778 int i, j, k, m;
2780 if (!t)
2781 return -1; /* Probably a %+ without a space */
2783 skip_white_(t);
2784 if (t->type != TOK_ID)
2785 return -1;
2786 tt = t->next;
2787 skip_white_(tt);
2788 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
2789 return -1;
2791 i = -1;
2792 j = elements(conditions);
2793 while (j - i > 1) {
2794 k = (j + i) / 2;
2795 m = nasm_stricmp(t->text, conditions[k]);
2796 if (m == 0) {
2797 i = k;
2798 j = -2;
2799 break;
2800 } else if (m < 0) {
2801 j = k;
2802 } else
2803 i = k;
2805 if (j != -2)
2806 return -1;
2807 return i;
2811 * Expand MMacro-local things: parameter references (%0, %n, %+n,
2812 * %-n) and MMacro-local identifiers (%%foo).
2814 static Token *expand_mmac_params(Token * tline)
2816 Token *t, *tt, **tail, *thead;
2818 tail = &thead;
2819 thead = NULL;
2821 while (tline) {
2822 if (tline->type == TOK_PREPROC_ID &&
2823 (((tline->text[1] == '+' || tline->text[1] == '-')
2824 && tline->text[2]) || tline->text[1] == '%'
2825 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
2826 char *text = NULL;
2827 int type = 0, cc; /* type = 0 to placate optimisers */
2828 char tmpbuf[30];
2829 unsigned int n;
2830 int i;
2831 MMacro *mac;
2833 t = tline;
2834 tline = tline->next;
2836 mac = istk->mstk;
2837 while (mac && !mac->name) /* avoid mistaking %reps for macros */
2838 mac = mac->next_active;
2839 if (!mac)
2840 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
2841 else
2842 switch (t->text[1]) {
2844 * We have to make a substitution of one of the
2845 * forms %1, %-1, %+1, %%foo, %0.
2847 case '0':
2848 type = TOK_NUMBER;
2849 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
2850 text = nasm_strdup(tmpbuf);
2851 break;
2852 case '%':
2853 type = TOK_ID;
2854 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
2855 mac->unique);
2856 text = nasm_strcat(tmpbuf, t->text + 2);
2857 break;
2858 case '-':
2859 n = atoi(t->text + 2) - 1;
2860 if (n >= mac->nparam)
2861 tt = NULL;
2862 else {
2863 if (mac->nparam > 1)
2864 n = (n + mac->rotate) % mac->nparam;
2865 tt = mac->params[n];
2867 cc = find_cc(tt);
2868 if (cc == -1) {
2869 error(ERR_NONFATAL,
2870 "macro parameter %d is not a condition code",
2871 n + 1);
2872 text = NULL;
2873 } else {
2874 type = TOK_ID;
2875 if (inverse_ccs[cc] == -1) {
2876 error(ERR_NONFATAL,
2877 "condition code `%s' is not invertible",
2878 conditions[cc]);
2879 text = NULL;
2880 } else
2881 text =
2882 nasm_strdup(conditions[inverse_ccs[cc]]);
2884 break;
2885 case '+':
2886 n = atoi(t->text + 2) - 1;
2887 if (n >= mac->nparam)
2888 tt = NULL;
2889 else {
2890 if (mac->nparam > 1)
2891 n = (n + mac->rotate) % mac->nparam;
2892 tt = mac->params[n];
2894 cc = find_cc(tt);
2895 if (cc == -1) {
2896 error(ERR_NONFATAL,
2897 "macro parameter %d is not a condition code",
2898 n + 1);
2899 text = NULL;
2900 } else {
2901 type = TOK_ID;
2902 text = nasm_strdup(conditions[cc]);
2904 break;
2905 default:
2906 n = atoi(t->text + 1) - 1;
2907 if (n >= mac->nparam)
2908 tt = NULL;
2909 else {
2910 if (mac->nparam > 1)
2911 n = (n + mac->rotate) % mac->nparam;
2912 tt = mac->params[n];
2914 if (tt) {
2915 for (i = 0; i < mac->paramlen[n]; i++) {
2916 *tail = new_Token(NULL, tt->type, tt->text, 0);
2917 tail = &(*tail)->next;
2918 tt = tt->next;
2921 text = NULL; /* we've done it here */
2922 break;
2924 if (!text) {
2925 delete_Token(t);
2926 } else {
2927 *tail = t;
2928 tail = &t->next;
2929 t->type = type;
2930 nasm_free(t->text);
2931 t->text = text;
2932 t->mac = NULL;
2934 continue;
2935 } else {
2936 t = *tail = tline;
2937 tline = tline->next;
2938 t->mac = NULL;
2939 tail = &t->next;
2942 *tail = NULL;
2943 t = thead;
2944 for (; t && (tt = t->next) != NULL; t = t->next)
2945 switch (t->type) {
2946 case TOK_WHITESPACE:
2947 if (tt->type == TOK_WHITESPACE) {
2948 t->next = delete_Token(tt);
2950 break;
2951 case TOK_ID:
2952 if (tt->type == TOK_ID || tt->type == TOK_NUMBER) {
2953 char *tmp = nasm_strcat(t->text, tt->text);
2954 nasm_free(t->text);
2955 t->text = tmp;
2956 t->next = delete_Token(tt);
2958 break;
2959 case TOK_NUMBER:
2960 if (tt->type == TOK_NUMBER) {
2961 char *tmp = nasm_strcat(t->text, tt->text);
2962 nasm_free(t->text);
2963 t->text = tmp;
2964 t->next = delete_Token(tt);
2966 break;
2967 default:
2968 break;
2971 return thead;
2975 * Expand all single-line macro calls made in the given line.
2976 * Return the expanded version of the line. The original is deemed
2977 * to be destroyed in the process. (In reality we'll just move
2978 * Tokens from input to output a lot of the time, rather than
2979 * actually bothering to destroy and replicate.)
2981 static Token *expand_smacro(Token * tline)
2983 Token *t, *tt, *mstart, **tail, *thead;
2984 SMacro *head = NULL, *m;
2985 Token **params;
2986 int *paramsize;
2987 unsigned int nparam, sparam;
2988 int brackets, rescan;
2989 Token *org_tline = tline;
2990 Context *ctx;
2991 char *mname;
2994 * Trick: we should avoid changing the start token pointer since it can
2995 * be contained in "next" field of other token. Because of this
2996 * we allocate a copy of first token and work with it; at the end of
2997 * routine we copy it back
2999 if (org_tline) {
3000 tline =
3001 new_Token(org_tline->next, org_tline->type, org_tline->text,
3003 tline->mac = org_tline->mac;
3004 nasm_free(org_tline->text);
3005 org_tline->text = NULL;
3008 again:
3009 tail = &thead;
3010 thead = NULL;
3012 while (tline) { /* main token loop */
3013 if ((mname = tline->text)) {
3014 /* if this token is a local macro, look in local context */
3015 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3016 ctx = get_ctx(mname, true);
3017 else
3018 ctx = NULL;
3019 if (!ctx) {
3020 head = (SMacro *) hash_findix(smacros, mname);
3021 } else {
3022 head = ctx->localmac;
3025 * We've hit an identifier. As in is_mmacro below, we first
3026 * check whether the identifier is a single-line macro at
3027 * all, then think about checking for parameters if
3028 * necessary.
3030 for (m = head; m; m = m->next)
3031 if (!mstrcmp(m->name, mname, m->casesense))
3032 break;
3033 if (m) {
3034 mstart = tline;
3035 params = NULL;
3036 paramsize = NULL;
3037 if (m->nparam == 0) {
3039 * Simple case: the macro is parameterless. Discard the
3040 * one token that the macro call took, and push the
3041 * expansion back on the to-do stack.
3043 if (!m->expansion) {
3044 if (!strcmp("__FILE__", m->name)) {
3045 int32_t num = 0;
3046 src_get(&num, &(tline->text));
3047 nasm_quote(&(tline->text));
3048 tline->type = TOK_STRING;
3049 continue;
3051 if (!strcmp("__LINE__", m->name)) {
3052 nasm_free(tline->text);
3053 make_tok_num(tline, src_get_linnum());
3054 continue;
3056 if (!strcmp("__BITS__", m->name)) {
3057 nasm_free(tline->text);
3058 make_tok_num(tline, globalbits);
3059 continue;
3061 tline = delete_Token(tline);
3062 continue;
3064 } else {
3066 * Complicated case: at least one macro with this name
3067 * exists and takes parameters. We must find the
3068 * parameters in the call, count them, find the SMacro
3069 * that corresponds to that form of the macro call, and
3070 * substitute for the parameters when we expand. What a
3071 * pain.
3073 /*tline = tline->next;
3074 skip_white_(tline); */
3075 do {
3076 t = tline->next;
3077 while (tok_type_(t, TOK_SMAC_END)) {
3078 t->mac->in_progress = false;
3079 t->text = NULL;
3080 t = tline->next = delete_Token(t);
3082 tline = t;
3083 } while (tok_type_(tline, TOK_WHITESPACE));
3084 if (!tok_is_(tline, "(")) {
3086 * This macro wasn't called with parameters: ignore
3087 * the call. (Behaviour borrowed from gnu cpp.)
3089 tline = mstart;
3090 m = NULL;
3091 } else {
3092 int paren = 0;
3093 int white = 0;
3094 brackets = 0;
3095 nparam = 0;
3096 sparam = PARAM_DELTA;
3097 params = nasm_malloc(sparam * sizeof(Token *));
3098 params[0] = tline->next;
3099 paramsize = nasm_malloc(sparam * sizeof(int));
3100 paramsize[0] = 0;
3101 while (true) { /* parameter loop */
3103 * For some unusual expansions
3104 * which concatenates function call
3106 t = tline->next;
3107 while (tok_type_(t, TOK_SMAC_END)) {
3108 t->mac->in_progress = false;
3109 t->text = NULL;
3110 t = tline->next = delete_Token(t);
3112 tline = t;
3114 if (!tline) {
3115 error(ERR_NONFATAL,
3116 "macro call expects terminating `)'");
3117 break;
3119 if (tline->type == TOK_WHITESPACE
3120 && brackets <= 0) {
3121 if (paramsize[nparam])
3122 white++;
3123 else
3124 params[nparam] = tline->next;
3125 continue; /* parameter loop */
3127 if (tline->type == TOK_OTHER
3128 && tline->text[1] == 0) {
3129 char ch = tline->text[0];
3130 if (ch == ',' && !paren && brackets <= 0) {
3131 if (++nparam >= sparam) {
3132 sparam += PARAM_DELTA;
3133 params = nasm_realloc(params,
3134 sparam *
3135 sizeof(Token
3136 *));
3137 paramsize =
3138 nasm_realloc(paramsize,
3139 sparam *
3140 sizeof(int));
3142 params[nparam] = tline->next;
3143 paramsize[nparam] = 0;
3144 white = 0;
3145 continue; /* parameter loop */
3147 if (ch == '{' &&
3148 (brackets > 0 || (brackets == 0 &&
3149 !paramsize[nparam])))
3151 if (!(brackets++)) {
3152 params[nparam] = tline->next;
3153 continue; /* parameter loop */
3156 if (ch == '}' && brackets > 0)
3157 if (--brackets == 0) {
3158 brackets = -1;
3159 continue; /* parameter loop */
3161 if (ch == '(' && !brackets)
3162 paren++;
3163 if (ch == ')' && brackets <= 0)
3164 if (--paren < 0)
3165 break;
3167 if (brackets < 0) {
3168 brackets = 0;
3169 error(ERR_NONFATAL, "braces do not "
3170 "enclose all of macro parameter");
3172 paramsize[nparam] += white + 1;
3173 white = 0;
3174 } /* parameter loop */
3175 nparam++;
3176 while (m && (m->nparam != nparam ||
3177 mstrcmp(m->name, mname,
3178 m->casesense)))
3179 m = m->next;
3180 if (!m)
3181 error(ERR_WARNING | ERR_WARN_MNP,
3182 "macro `%s' exists, "
3183 "but not taking %d parameters",
3184 mstart->text, nparam);
3187 if (m && m->in_progress)
3188 m = NULL;
3189 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3191 * Design question: should we handle !tline, which
3192 * indicates missing ')' here, or expand those
3193 * macros anyway, which requires the (t) test a few
3194 * lines down?
3196 nasm_free(params);
3197 nasm_free(paramsize);
3198 tline = mstart;
3199 } else {
3201 * Expand the macro: we are placed on the last token of the
3202 * call, so that we can easily split the call from the
3203 * following tokens. We also start by pushing an SMAC_END
3204 * token for the cycle removal.
3206 t = tline;
3207 if (t) {
3208 tline = t->next;
3209 t->next = NULL;
3211 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3212 tt->mac = m;
3213 m->in_progress = true;
3214 tline = tt;
3215 for (t = m->expansion; t; t = t->next) {
3216 if (t->type >= TOK_SMAC_PARAM) {
3217 Token *pcopy = tline, **ptail = &pcopy;
3218 Token *ttt, *pt;
3219 int i;
3221 ttt = params[t->type - TOK_SMAC_PARAM];
3222 for (i = paramsize[t->type - TOK_SMAC_PARAM];
3223 --i >= 0;) {
3224 pt = *ptail =
3225 new_Token(tline, ttt->type, ttt->text,
3227 ptail = &pt->next;
3228 ttt = ttt->next;
3230 tline = pcopy;
3231 } else {
3232 tt = new_Token(tline, t->type, t->text, 0);
3233 tline = tt;
3238 * Having done that, get rid of the macro call, and clean
3239 * up the parameters.
3241 nasm_free(params);
3242 nasm_free(paramsize);
3243 free_tlist(mstart);
3244 continue; /* main token loop */
3249 if (tline->type == TOK_SMAC_END) {
3250 tline->mac->in_progress = false;
3251 tline = delete_Token(tline);
3252 } else {
3253 t = *tail = tline;
3254 tline = tline->next;
3255 t->mac = NULL;
3256 t->next = NULL;
3257 tail = &t->next;
3262 * Now scan the entire line and look for successive TOK_IDs that resulted
3263 * after expansion (they can't be produced by tokenize()). The successive
3264 * TOK_IDs should be concatenated.
3265 * Also we look for %+ tokens and concatenate the tokens before and after
3266 * them (without white spaces in between).
3268 t = thead;
3269 rescan = 0;
3270 while (t) {
3271 while (t && t->type != TOK_ID && t->type != TOK_PREPROC_ID)
3272 t = t->next;
3273 if (!t || !t->next)
3274 break;
3275 if (t->next->type == TOK_ID ||
3276 t->next->type == TOK_PREPROC_ID ||
3277 t->next->type == TOK_NUMBER) {
3278 char *p = nasm_strcat(t->text, t->next->text);
3279 nasm_free(t->text);
3280 t->next = delete_Token(t->next);
3281 t->text = p;
3282 rescan = 1;
3283 } else if (t->next->type == TOK_WHITESPACE && t->next->next &&
3284 t->next->next->type == TOK_PREPROC_ID &&
3285 strcmp(t->next->next->text, "%+") == 0) {
3286 /* free the next whitespace, the %+ token and next whitespace */
3287 int i;
3288 for (i = 1; i <= 3; i++) {
3289 if (!t->next
3290 || (i != 2 && t->next->type != TOK_WHITESPACE))
3291 break;
3292 t->next = delete_Token(t->next);
3293 } /* endfor */
3294 } else
3295 t = t->next;
3297 /* If we concatenaded something, re-scan the line for macros */
3298 if (rescan) {
3299 tline = thead;
3300 goto again;
3303 if (org_tline) {
3304 if (thead) {
3305 *org_tline = *thead;
3306 /* since we just gave text to org_line, don't free it */
3307 thead->text = NULL;
3308 delete_Token(thead);
3309 } else {
3310 /* the expression expanded to empty line;
3311 we can't return NULL for some reasons
3312 we just set the line to a single WHITESPACE token. */
3313 memset(org_tline, 0, sizeof(*org_tline));
3314 org_tline->text = NULL;
3315 org_tline->type = TOK_WHITESPACE;
3317 thead = org_tline;
3320 return thead;
3324 * Similar to expand_smacro but used exclusively with macro identifiers
3325 * right before they are fetched in. The reason is that there can be
3326 * identifiers consisting of several subparts. We consider that if there
3327 * are more than one element forming the name, user wants a expansion,
3328 * otherwise it will be left as-is. Example:
3330 * %define %$abc cde
3332 * the identifier %$abc will be left as-is so that the handler for %define
3333 * will suck it and define the corresponding value. Other case:
3335 * %define _%$abc cde
3337 * In this case user wants name to be expanded *before* %define starts
3338 * working, so we'll expand %$abc into something (if it has a value;
3339 * otherwise it will be left as-is) then concatenate all successive
3340 * PP_IDs into one.
3342 static Token *expand_id(Token * tline)
3344 Token *cur, *oldnext = NULL;
3346 if (!tline || !tline->next)
3347 return tline;
3349 cur = tline;
3350 while (cur->next &&
3351 (cur->next->type == TOK_ID ||
3352 cur->next->type == TOK_PREPROC_ID
3353 || cur->next->type == TOK_NUMBER))
3354 cur = cur->next;
3356 /* If identifier consists of just one token, don't expand */
3357 if (cur == tline)
3358 return tline;
3360 if (cur) {
3361 oldnext = cur->next; /* Detach the tail past identifier */
3362 cur->next = NULL; /* so that expand_smacro stops here */
3365 tline = expand_smacro(tline);
3367 if (cur) {
3368 /* expand_smacro possibly changhed tline; re-scan for EOL */
3369 cur = tline;
3370 while (cur && cur->next)
3371 cur = cur->next;
3372 if (cur)
3373 cur->next = oldnext;
3376 return tline;
3380 * Determine whether the given line constitutes a multi-line macro
3381 * call, and return the MMacro structure called if so. Doesn't have
3382 * to check for an initial label - that's taken care of in
3383 * expand_mmacro - but must check numbers of parameters. Guaranteed
3384 * to be called with tline->type == TOK_ID, so the putative macro
3385 * name is easy to find.
3387 static MMacro *is_mmacro(Token * tline, Token *** params_array)
3389 MMacro *head, *m;
3390 Token **params;
3391 int nparam;
3393 head = (MMacro *) hash_findix(mmacros, tline->text);
3396 * Efficiency: first we see if any macro exists with the given
3397 * name. If not, we can return NULL immediately. _Then_ we
3398 * count the parameters, and then we look further along the
3399 * list if necessary to find the proper MMacro.
3401 for (m = head; m; m = m->next)
3402 if (!mstrcmp(m->name, tline->text, m->casesense))
3403 break;
3404 if (!m)
3405 return NULL;
3408 * OK, we have a potential macro. Count and demarcate the
3409 * parameters.
3411 count_mmac_params(tline->next, &nparam, &params);
3414 * So we know how many parameters we've got. Find the MMacro
3415 * structure that handles this number.
3417 while (m) {
3418 if (m->nparam_min <= nparam
3419 && (m->plus || nparam <= m->nparam_max)) {
3421 * This one is right. Just check if cycle removal
3422 * prohibits us using it before we actually celebrate...
3424 if (m->in_progress) {
3425 #if 0
3426 error(ERR_NONFATAL,
3427 "self-reference in multi-line macro `%s'", m->name);
3428 #endif
3429 nasm_free(params);
3430 return NULL;
3433 * It's right, and we can use it. Add its default
3434 * parameters to the end of our list if necessary.
3436 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
3437 params =
3438 nasm_realloc(params,
3439 ((m->nparam_min + m->ndefs +
3440 1) * sizeof(*params)));
3441 while (nparam < m->nparam_min + m->ndefs) {
3442 params[nparam] = m->defaults[nparam - m->nparam_min];
3443 nparam++;
3447 * If we've gone over the maximum parameter count (and
3448 * we're in Plus mode), ignore parameters beyond
3449 * nparam_max.
3451 if (m->plus && nparam > m->nparam_max)
3452 nparam = m->nparam_max;
3454 * Then terminate the parameter list, and leave.
3456 if (!params) { /* need this special case */
3457 params = nasm_malloc(sizeof(*params));
3458 nparam = 0;
3460 params[nparam] = NULL;
3461 *params_array = params;
3462 return m;
3465 * This one wasn't right: look for the next one with the
3466 * same name.
3468 for (m = m->next; m; m = m->next)
3469 if (!mstrcmp(m->name, tline->text, m->casesense))
3470 break;
3474 * After all that, we didn't find one with the right number of
3475 * parameters. Issue a warning, and fail to expand the macro.
3477 error(ERR_WARNING | ERR_WARN_MNP,
3478 "macro `%s' exists, but not taking %d parameters",
3479 tline->text, nparam);
3480 nasm_free(params);
3481 return NULL;
3485 * Expand the multi-line macro call made by the given line, if
3486 * there is one to be expanded. If there is, push the expansion on
3487 * istk->expansion and return 1. Otherwise return 0.
3489 static int expand_mmacro(Token * tline)
3491 Token *startline = tline;
3492 Token *label = NULL;
3493 int dont_prepend = 0;
3494 Token **params, *t, *tt;
3495 MMacro *m;
3496 Line *l, *ll;
3497 int i, nparam, *paramlen;
3499 t = tline;
3500 skip_white_(t);
3501 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
3502 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
3503 return 0;
3504 m = is_mmacro(t, &params);
3505 if (!m) {
3506 Token *last;
3508 * We have an id which isn't a macro call. We'll assume
3509 * it might be a label; we'll also check to see if a
3510 * colon follows it. Then, if there's another id after
3511 * that lot, we'll check it again for macro-hood.
3513 label = last = t;
3514 t = t->next;
3515 if (tok_type_(t, TOK_WHITESPACE))
3516 last = t, t = t->next;
3517 if (tok_is_(t, ":")) {
3518 dont_prepend = 1;
3519 last = t, t = t->next;
3520 if (tok_type_(t, TOK_WHITESPACE))
3521 last = t, t = t->next;
3523 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
3524 return 0;
3525 last->next = NULL;
3526 tline = t;
3530 * Fix up the parameters: this involves stripping leading and
3531 * trailing whitespace, then stripping braces if they are
3532 * present.
3534 for (nparam = 0; params[nparam]; nparam++) ;
3535 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
3537 for (i = 0; params[i]; i++) {
3538 int brace = false;
3539 int comma = (!m->plus || i < nparam - 1);
3541 t = params[i];
3542 skip_white_(t);
3543 if (tok_is_(t, "{"))
3544 t = t->next, brace = true, comma = false;
3545 params[i] = t;
3546 paramlen[i] = 0;
3547 while (t) {
3548 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
3549 break; /* ... because we have hit a comma */
3550 if (comma && t->type == TOK_WHITESPACE
3551 && tok_is_(t->next, ","))
3552 break; /* ... or a space then a comma */
3553 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
3554 break; /* ... or a brace */
3555 t = t->next;
3556 paramlen[i]++;
3561 * OK, we have a MMacro structure together with a set of
3562 * parameters. We must now go through the expansion and push
3563 * copies of each Line on to istk->expansion. Substitution of
3564 * parameter tokens and macro-local tokens doesn't get done
3565 * until the single-line macro substitution process; this is
3566 * because delaying them allows us to change the semantics
3567 * later through %rotate.
3569 * First, push an end marker on to istk->expansion, mark this
3570 * macro as in progress, and set up its invocation-specific
3571 * variables.
3573 ll = nasm_malloc(sizeof(Line));
3574 ll->next = istk->expansion;
3575 ll->finishes = m;
3576 ll->first = NULL;
3577 istk->expansion = ll;
3579 m->in_progress = true;
3580 m->params = params;
3581 m->iline = tline;
3582 m->nparam = nparam;
3583 m->rotate = 0;
3584 m->paramlen = paramlen;
3585 m->unique = unique++;
3586 m->lineno = 0;
3588 m->next_active = istk->mstk;
3589 istk->mstk = m;
3591 for (l = m->expansion; l; l = l->next) {
3592 Token **tail;
3594 ll = nasm_malloc(sizeof(Line));
3595 ll->finishes = NULL;
3596 ll->next = istk->expansion;
3597 istk->expansion = ll;
3598 tail = &ll->first;
3600 for (t = l->first; t; t = t->next) {
3601 Token *x = t;
3602 if (t->type == TOK_PREPROC_ID &&
3603 t->text[1] == '0' && t->text[2] == '0') {
3604 dont_prepend = -1;
3605 x = label;
3606 if (!x)
3607 continue;
3609 tt = *tail = new_Token(NULL, x->type, x->text, 0);
3610 tail = &tt->next;
3612 *tail = NULL;
3616 * If we had a label, push it on as the first line of
3617 * the macro expansion.
3619 if (label) {
3620 if (dont_prepend < 0)
3621 free_tlist(startline);
3622 else {
3623 ll = nasm_malloc(sizeof(Line));
3624 ll->finishes = NULL;
3625 ll->next = istk->expansion;
3626 istk->expansion = ll;
3627 ll->first = startline;
3628 if (!dont_prepend) {
3629 while (label->next)
3630 label = label->next;
3631 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
3636 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
3638 return 1;
3642 * Since preprocessor always operate only on the line that didn't
3643 * arrived yet, we should always use ERR_OFFBY1. Also since user
3644 * won't want to see same error twice (preprocessing is done once
3645 * per pass) we will want to show errors only during pass one.
3647 static void error(int severity, const char *fmt, ...)
3649 va_list arg;
3650 char buff[1024];
3652 /* If we're in a dead branch of IF or something like it, ignore the error */
3653 if (istk && istk->conds && !emitting(istk->conds->state))
3654 return;
3656 va_start(arg, fmt);
3657 vsnprintf(buff, sizeof(buff), fmt, arg);
3658 va_end(arg);
3660 if (istk && istk->mstk && istk->mstk->name)
3661 _error(severity | ERR_PASS1, "(%s:%d) %s", istk->mstk->name,
3662 istk->mstk->lineno, buff);
3663 else
3664 _error(severity | ERR_PASS1, "%s", buff);
3667 static void
3668 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
3669 ListGen * listgen)
3671 _error = errfunc;
3672 cstk = NULL;
3673 istk = nasm_malloc(sizeof(Include));
3674 istk->next = NULL;
3675 istk->conds = NULL;
3676 istk->expansion = NULL;
3677 istk->mstk = NULL;
3678 istk->fp = fopen(file, "r");
3679 istk->fname = NULL;
3680 src_set_fname(nasm_strdup(file));
3681 src_set_linnum(0);
3682 istk->lineinc = 1;
3683 if (!istk->fp)
3684 error(ERR_FATAL | ERR_NOFILE, "unable to open input file `%s'",
3685 file);
3686 defining = NULL;
3687 init_macros();
3688 unique = 0;
3689 if (tasm_compatible_mode) {
3690 stdmacpos = stdmac;
3691 } else {
3692 stdmacpos = &stdmac[TASM_MACRO_COUNT];
3694 any_extrastdmac = (extrastdmac != NULL);
3695 list = listgen;
3696 evaluate = eval;
3697 pass = apass;
3700 static char *pp_getline(void)
3702 char *line;
3703 Token *tline;
3705 while (1) {
3707 * Fetch a tokenized line, either from the macro-expansion
3708 * buffer or from the input file.
3710 tline = NULL;
3711 while (istk->expansion && istk->expansion->finishes) {
3712 Line *l = istk->expansion;
3713 if (!l->finishes->name && l->finishes->in_progress > 1) {
3714 Line *ll;
3717 * This is a macro-end marker for a macro with no
3718 * name, which means it's not really a macro at all
3719 * but a %rep block, and the `in_progress' field is
3720 * more than 1, meaning that we still need to
3721 * repeat. (1 means the natural last repetition; 0
3722 * means termination by %exitrep.) We have
3723 * therefore expanded up to the %endrep, and must
3724 * push the whole block on to the expansion buffer
3725 * again. We don't bother to remove the macro-end
3726 * marker: we'd only have to generate another one
3727 * if we did.
3729 l->finishes->in_progress--;
3730 for (l = l->finishes->expansion; l; l = l->next) {
3731 Token *t, *tt, **tail;
3733 ll = nasm_malloc(sizeof(Line));
3734 ll->next = istk->expansion;
3735 ll->finishes = NULL;
3736 ll->first = NULL;
3737 tail = &ll->first;
3739 for (t = l->first; t; t = t->next) {
3740 if (t->text || t->type == TOK_WHITESPACE) {
3741 tt = *tail =
3742 new_Token(NULL, t->type, t->text, 0);
3743 tail = &tt->next;
3747 istk->expansion = ll;
3749 } else {
3751 * Check whether a `%rep' was started and not ended
3752 * within this macro expansion. This can happen and
3753 * should be detected. It's a fatal error because
3754 * I'm too confused to work out how to recover
3755 * sensibly from it.
3757 if (defining) {
3758 if (defining->name)
3759 error(ERR_PANIC,
3760 "defining with name in expansion");
3761 else if (istk->mstk->name)
3762 error(ERR_FATAL,
3763 "`%%rep' without `%%endrep' within"
3764 " expansion of macro `%s'",
3765 istk->mstk->name);
3769 * FIXME: investigate the relationship at this point between
3770 * istk->mstk and l->finishes
3773 MMacro *m = istk->mstk;
3774 istk->mstk = m->next_active;
3775 if (m->name) {
3777 * This was a real macro call, not a %rep, and
3778 * therefore the parameter information needs to
3779 * be freed.
3781 nasm_free(m->params);
3782 free_tlist(m->iline);
3783 nasm_free(m->paramlen);
3784 l->finishes->in_progress = false;
3785 } else
3786 free_mmacro(m);
3788 istk->expansion = l->next;
3789 nasm_free(l);
3790 list->downlevel(LIST_MACRO);
3793 while (1) { /* until we get a line we can use */
3795 if (istk->expansion) { /* from a macro expansion */
3796 char *p;
3797 Line *l = istk->expansion;
3798 if (istk->mstk)
3799 istk->mstk->lineno++;
3800 tline = l->first;
3801 istk->expansion = l->next;
3802 nasm_free(l);
3803 p = detoken(tline, false);
3804 list->line(LIST_MACRO, p);
3805 nasm_free(p);
3806 break;
3808 line = read_line();
3809 if (line) { /* from the current input file */
3810 line = prepreproc(line);
3811 tline = tokenize(line);
3812 nasm_free(line);
3813 break;
3816 * The current file has ended; work down the istk
3819 Include *i = istk;
3820 fclose(i->fp);
3821 if (i->conds)
3822 error(ERR_FATAL,
3823 "expected `%%endif' before end of file");
3824 /* only set line and file name if there's a next node */
3825 if (i->next) {
3826 src_set_linnum(i->lineno);
3827 nasm_free(src_set_fname(i->fname));
3829 istk = i->next;
3830 list->downlevel(LIST_INCLUDE);
3831 nasm_free(i);
3832 if (!istk)
3833 return NULL;
3838 * We must expand MMacro parameters and MMacro-local labels
3839 * _before_ we plunge into directive processing, to cope
3840 * with things like `%define something %1' such as STRUC
3841 * uses. Unless we're _defining_ a MMacro, in which case
3842 * those tokens should be left alone to go into the
3843 * definition; and unless we're in a non-emitting
3844 * condition, in which case we don't want to meddle with
3845 * anything.
3847 if (!defining && !(istk->conds && !emitting(istk->conds->state)))
3848 tline = expand_mmac_params(tline);
3851 * Check the line to see if it's a preprocessor directive.
3853 if (do_directive(tline) == DIRECTIVE_FOUND) {
3854 continue;
3855 } else if (defining) {
3857 * We're defining a multi-line macro. We emit nothing
3858 * at all, and just
3859 * shove the tokenized line on to the macro definition.
3861 Line *l = nasm_malloc(sizeof(Line));
3862 l->next = defining->expansion;
3863 l->first = tline;
3864 l->finishes = false;
3865 defining->expansion = l;
3866 continue;
3867 } else if (istk->conds && !emitting(istk->conds->state)) {
3869 * We're in a non-emitting branch of a condition block.
3870 * Emit nothing at all, not even a blank line: when we
3871 * emerge from the condition we'll give a line-number
3872 * directive so we keep our place correctly.
3874 free_tlist(tline);
3875 continue;
3876 } else if (istk->mstk && !istk->mstk->in_progress) {
3878 * We're in a %rep block which has been terminated, so
3879 * we're walking through to the %endrep without
3880 * emitting anything. Emit nothing at all, not even a
3881 * blank line: when we emerge from the %rep block we'll
3882 * give a line-number directive so we keep our place
3883 * correctly.
3885 free_tlist(tline);
3886 continue;
3887 } else {
3888 tline = expand_smacro(tline);
3889 if (!expand_mmacro(tline)) {
3891 * De-tokenize the line again, and emit it.
3893 line = detoken(tline, true);
3894 free_tlist(tline);
3895 break;
3896 } else {
3897 continue; /* expand_mmacro calls free_tlist */
3902 return line;
3905 static void pp_cleanup(int pass)
3907 if (defining) {
3908 error(ERR_NONFATAL, "end of file while still defining macro `%s'",
3909 defining->name);
3910 free_mmacro(defining);
3912 while (cstk)
3913 ctx_pop();
3914 free_macros();
3915 while (istk) {
3916 Include *i = istk;
3917 istk = istk->next;
3918 fclose(i->fp);
3919 nasm_free(i->fname);
3920 nasm_free(i);
3922 while (cstk)
3923 ctx_pop();
3924 if (pass == 0) {
3925 free_llist(predef);
3926 delete_Blocks();
3930 void pp_include_path(char *path)
3932 IncPath *i;
3934 i = nasm_malloc(sizeof(IncPath));
3935 i->path = path ? nasm_strdup(path) : NULL;
3936 i->next = NULL;
3938 if (ipath != NULL) {
3939 IncPath *j = ipath;
3940 while (j->next != NULL)
3941 j = j->next;
3942 j->next = i;
3943 } else {
3944 ipath = i;
3949 * added by alexfru:
3951 * This function is used to "export" the include paths, e.g.
3952 * the paths specified in the '-I' command switch.
3953 * The need for such exporting is due to the 'incbin' directive,
3954 * which includes raw binary files (unlike '%include', which
3955 * includes text source files). It would be real nice to be
3956 * able to specify paths to search for incbin'ned files also.
3957 * So, this is a simple workaround.
3959 * The function use is simple:
3961 * The 1st call (with NULL argument) returns a pointer to the 1st path
3962 * (char** type) or NULL if none include paths available.
3964 * All subsequent calls take as argument the value returned by this
3965 * function last. The return value is either the next path
3966 * (char** type) or NULL if the end of the paths list is reached.
3968 * It is maybe not the best way to do things, but I didn't want
3969 * to export too much, just one or two functions and no types or
3970 * variables exported.
3972 * Can't say I like the current situation with e.g. this path list either,
3973 * it seems to be never deallocated after creation...
3975 char **pp_get_include_path_ptr(char **pPrevPath)
3977 /* This macro returns offset of a member of a structure */
3978 #define GetMemberOffset(StructType,MemberName)\
3979 ((size_t)&((StructType*)0)->MemberName)
3980 IncPath *i;
3982 if (pPrevPath == NULL) {
3983 if (ipath != NULL)
3984 return &ipath->path;
3985 else
3986 return NULL;
3988 i = (IncPath *) ((char *)pPrevPath - GetMemberOffset(IncPath, path));
3989 i = i->next;
3990 if (i != NULL)
3991 return &i->path;
3992 else
3993 return NULL;
3994 #undef GetMemberOffset
3997 void pp_pre_include(char *fname)
3999 Token *inc, *space, *name;
4000 Line *l;
4002 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4003 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4004 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4006 l = nasm_malloc(sizeof(Line));
4007 l->next = predef;
4008 l->first = inc;
4009 l->finishes = false;
4010 predef = l;
4013 void pp_pre_define(char *definition)
4015 Token *def, *space;
4016 Line *l;
4017 char *equals;
4019 equals = strchr(definition, '=');
4020 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4021 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4022 if (equals)
4023 *equals = ' ';
4024 space->next = tokenize(definition);
4025 if (equals)
4026 *equals = '=';
4028 l = nasm_malloc(sizeof(Line));
4029 l->next = predef;
4030 l->first = def;
4031 l->finishes = false;
4032 predef = l;
4035 void pp_pre_undefine(char *definition)
4037 Token *def, *space;
4038 Line *l;
4040 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4041 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4042 space->next = tokenize(definition);
4044 l = nasm_malloc(sizeof(Line));
4045 l->next = predef;
4046 l->first = def;
4047 l->finishes = false;
4048 predef = l;
4052 * Added by Keith Kanios:
4054 * This function is used to assist with "runtime" preprocessor
4055 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4057 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4058 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4061 void pp_runtime(char *definition)
4063 Token *def;
4065 def = tokenize(definition);
4066 if(do_directive(def) == NO_DIRECTIVE_FOUND)
4067 free_tlist(def);
4071 void pp_extra_stdmac(const char **macros)
4073 extrastdmac = macros;
4076 static void make_tok_num(Token * tok, int64_t val)
4078 char numbuf[20];
4079 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4080 tok->text = nasm_strdup(numbuf);
4081 tok->type = TOK_NUMBER;
4084 Preproc nasmpp = {
4085 pp_reset,
4086 pp_getline,
4087 pp_cleanup