preproc: don't pass an enum to %s
[nasm/sigaren-mirror.git] / preproc.c
blobd92b4bf8685dc53432250d1eca47fb685e6460f8
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2009 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
44 * or
45 * {
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
48 * }
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
63 #include "compiler.h"
65 #include <stdio.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <stddef.h>
69 #include <string.h>
70 #include <ctype.h>
71 #include <limits.h>
72 #include <inttypes.h>
74 #include "nasm.h"
75 #include "nasmlib.h"
76 #include "preproc.h"
77 #include "hashtbl.h"
78 #include "quote.h"
79 #include "stdscan.h"
80 #include "tokens.h"
81 #include "tables.h"
83 typedef struct SMacro SMacro;
84 typedef struct MMacro MMacro;
85 typedef struct MMacroInvocation MMacroInvocation;
86 typedef struct Context Context;
87 typedef struct Token Token;
88 typedef struct Blocks Blocks;
89 typedef struct Line Line;
90 typedef struct Include Include;
91 typedef struct Cond Cond;
92 typedef struct IncPath IncPath;
95 * Note on the storage of both SMacro and MMacros: the hash table
96 * indexes them case-insensitively, and we then have to go through a
97 * linked list of potential case aliases (and, for MMacros, parameter
98 * ranges); this is to preserve the matching semantics of the earlier
99 * code. If the number of case aliases for a specific macro is a
100 * performance issue, you may want to reconsider your coding style.
104 * Store the definition of a single-line macro.
106 struct SMacro {
107 SMacro *next;
108 char *name;
109 bool casesense;
110 bool in_progress;
111 unsigned int nparam;
112 Token *expansion;
116 * Store the definition of a multi-line macro. This is also used to
117 * store the interiors of `%rep...%endrep' blocks, which are
118 * effectively self-re-invoking multi-line macros which simply
119 * don't have a name or bother to appear in the hash tables. %rep
120 * blocks are signified by having a NULL `name' field.
122 * In a MMacro describing a `%rep' block, the `in_progress' field
123 * isn't merely boolean, but gives the number of repeats left to
124 * run.
126 * The `next' field is used for storing MMacros in hash tables; the
127 * `next_active' field is for stacking them on istk entries.
129 * When a MMacro is being expanded, `params', `iline', `nparam',
130 * `paramlen', `rotate' and `unique' are local to the invocation.
132 struct MMacro {
133 MMacro *next;
134 MMacroInvocation *prev; /* previous invocation */
135 char *name;
136 int nparam_min, nparam_max;
137 bool casesense;
138 bool plus; /* is the last parameter greedy? */
139 bool nolist; /* is this macro listing-inhibited? */
140 int64_t in_progress; /* is this macro currently being expanded? */
141 int32_t max_depth; /* maximum number of recursive expansions allowed */
142 Token *dlist; /* All defaults as one list */
143 Token **defaults; /* Parameter default pointers */
144 int ndefs; /* number of default parameters */
145 Line *expansion;
147 MMacro *next_active;
148 MMacro *rep_nest; /* used for nesting %rep */
149 Token **params; /* actual parameters */
150 Token *iline; /* invocation line */
151 unsigned int nparam, rotate;
152 int *paramlen;
153 uint64_t unique;
154 int lineno; /* Current line number on expansion */
158 /* Store the definition of a multi-line macro, as defined in a
159 * previous recursive macro expansion.
161 struct MMacroInvocation {
162 MMacroInvocation *prev; /* previous invocation */
163 Token **params; /* actual parameters */
164 Token *iline; /* invocation line */
165 unsigned int nparam, rotate;
166 int *paramlen;
167 uint64_t unique;
172 * The context stack is composed of a linked list of these.
174 struct Context {
175 Context *next;
176 char *name;
177 struct hash_table localmac;
178 uint32_t number;
182 * This is the internal form which we break input lines up into.
183 * Typically stored in linked lists.
185 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
186 * necessarily used as-is, but is intended to denote the number of
187 * the substituted parameter. So in the definition
189 * %define a(x,y) ( (x) & ~(y) )
191 * the token representing `x' will have its type changed to
192 * TOK_SMAC_PARAM, but the one representing `y' will be
193 * TOK_SMAC_PARAM+1.
195 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
196 * which doesn't need quotes around it. Used in the pre-include
197 * mechanism as an alternative to trying to find a sensible type of
198 * quote to use on the filename we were passed.
200 enum pp_token_type {
201 TOK_NONE = 0, TOK_WHITESPACE, TOK_COMMENT, TOK_ID,
202 TOK_PREPROC_ID, TOK_STRING,
203 TOK_NUMBER, TOK_FLOAT, TOK_SMAC_END, TOK_OTHER,
204 TOK_INTERNAL_STRING,
205 TOK_PREPROC_Q, TOK_PREPROC_QQ,
206 TOK_PASTE, /* %+ */
207 TOK_INDIRECT, /* %[...] */
208 TOK_SMAC_PARAM, /* MUST BE LAST IN THE LIST!!! */
209 TOK_MAX = INT_MAX /* Keep compiler from reducing the range */
212 struct Token {
213 Token *next;
214 char *text;
215 union {
216 SMacro *mac; /* associated macro for TOK_SMAC_END */
217 size_t len; /* scratch length field */
218 } a; /* Auxiliary data */
219 enum pp_token_type type;
223 * Multi-line macro definitions are stored as a linked list of
224 * these, which is essentially a container to allow several linked
225 * lists of Tokens.
227 * Note that in this module, linked lists are treated as stacks
228 * wherever possible. For this reason, Lines are _pushed_ on to the
229 * `expansion' field in MMacro structures, so that the linked list,
230 * if walked, would give the macro lines in reverse order; this
231 * means that we can walk the list when expanding a macro, and thus
232 * push the lines on to the `expansion' field in _istk_ in reverse
233 * order (so that when popped back off they are in the right
234 * order). It may seem cockeyed, and it relies on my design having
235 * an even number of steps in, but it works...
237 * Some of these structures, rather than being actual lines, are
238 * markers delimiting the end of the expansion of a given macro.
239 * This is for use in the cycle-tracking and %rep-handling code.
240 * Such structures have `finishes' non-NULL, and `first' NULL. All
241 * others have `finishes' NULL, but `first' may still be NULL if
242 * the line is blank.
244 struct Line {
245 Line *next;
246 MMacro *finishes;
247 Token *first;
251 * To handle an arbitrary level of file inclusion, we maintain a
252 * stack (ie linked list) of these things.
254 struct Include {
255 Include *next;
256 FILE *fp;
257 Cond *conds;
258 Line *expansion;
259 char *fname;
260 int lineno, lineinc;
261 MMacro *mstk; /* stack of active macros/reps */
265 * Include search path. This is simply a list of strings which get
266 * prepended, in turn, to the name of an include file, in an
267 * attempt to find the file if it's not in the current directory.
269 struct IncPath {
270 IncPath *next;
271 char *path;
275 * Conditional assembly: we maintain a separate stack of these for
276 * each level of file inclusion. (The only reason we keep the
277 * stacks separate is to ensure that a stray `%endif' in a file
278 * included from within the true branch of a `%if' won't terminate
279 * it and cause confusion: instead, rightly, it'll cause an error.)
281 struct Cond {
282 Cond *next;
283 int state;
285 enum {
287 * These states are for use just after %if or %elif: IF_TRUE
288 * means the condition has evaluated to truth so we are
289 * currently emitting, whereas IF_FALSE means we are not
290 * currently emitting but will start doing so if a %else comes
291 * up. In these states, all directives are admissible: %elif,
292 * %else and %endif. (And of course %if.)
294 COND_IF_TRUE, COND_IF_FALSE,
296 * These states come up after a %else: ELSE_TRUE means we're
297 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
298 * any %elif or %else will cause an error.
300 COND_ELSE_TRUE, COND_ELSE_FALSE,
302 * These states mean that we're not emitting now, and also that
303 * nothing until %endif will be emitted at all. COND_DONE is
304 * used when we've had our moment of emission
305 * and have now started seeing %elifs. COND_NEVER is used when
306 * the condition construct in question is contained within a
307 * non-emitting branch of a larger condition construct,
308 * or if there is an error.
310 COND_DONE, COND_NEVER
312 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
315 * These defines are used as the possible return values for do_directive
317 #define NO_DIRECTIVE_FOUND 0
318 #define DIRECTIVE_FOUND 1
321 * This define sets the upper limit for smacro and recursive mmacro
322 * expansions
324 #define DEADMAN_LIMIT (1 << 20)
327 * Condition codes. Note that we use c_ prefix not C_ because C_ is
328 * used in nasm.h for the "real" condition codes. At _this_ level,
329 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
330 * ones, so we need a different enum...
332 static const char * const conditions[] = {
333 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
334 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
335 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
337 enum pp_conds {
338 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
339 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
340 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
341 c_none = -1
343 static const enum pp_conds inverse_ccs[] = {
344 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
345 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,
346 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
350 * Directive names.
352 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
353 static int is_condition(enum preproc_token arg)
355 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
358 /* For TASM compatibility we need to be able to recognise TASM compatible
359 * conditional compilation directives. Using the NASM pre-processor does
360 * not work, so we look for them specifically from the following list and
361 * then jam in the equivalent NASM directive into the input stream.
364 enum {
365 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
366 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
369 static const char * const tasm_directives[] = {
370 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
371 "ifndef", "include", "local"
374 static int StackSize = 4;
375 static char *StackPointer = "ebp";
376 static int ArgOffset = 8;
377 static int LocalOffset = 0;
379 static Context *cstk;
380 static Include *istk;
381 static IncPath *ipath = NULL;
383 static efunc _error; /* Pointer to client-provided error reporting function */
384 static evalfunc evaluate;
386 static int pass; /* HACK: pass 0 = generate dependencies only */
387 static StrList **dephead, **deptail; /* Dependency list */
389 static uint64_t unique; /* unique identifier numbers */
391 static Line *predef = NULL;
392 static bool do_predef;
394 static ListGen *list;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro *defining;
412 static uint64_t nested_mac_count;
413 static uint64_t nested_rep_count;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t *stdmacpos;
427 * The extra standard macros that come from the object format, if
428 * any.
430 static macros_t *extrastdmac = NULL;
431 static bool any_extrastdmac;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token *freeTokens = NULL;
438 struct Blocks {
439 Blocks *next;
440 void *chunk;
443 static Blocks blocks = { NULL, NULL };
446 * Forward declarations.
448 static Token *expand_mmac_params(Token * tline);
449 static Token *expand_smacro(Token * tline);
450 static Token *expand_id(Token * tline);
451 static Context *get_ctx(const char *name, const char **namep,
452 bool all_contexts);
453 static void make_tok_num(Token * tok, int64_t val);
454 static void error(int severity, const char *fmt, ...);
455 static void error_precond(int severity, const char *fmt, ...);
456 static void *new_Block(size_t size);
457 static void delete_Blocks(void);
458 static Token *new_Token(Token * next, enum pp_token_type type,
459 const char *text, int txtlen);
460 static Token *delete_Token(Token * t);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
470 /* Handle TASM specific directives, which do not contain a % in
471 * front of them. We do it here because I could not find any other
472 * place to do it for the moment, and it is a hack (ideally it would
473 * be nice to be able to use the NASM pre-processor to do it).
475 static char *check_tasm_directive(char *line)
477 int32_t i, j, k, m, len;
478 char *p = line, *oldline, oldchar;
480 /* Skip whitespace */
481 while (nasm_isspace(*p) && *p != 0)
482 p++;
484 /* Binary search for the directive name */
485 i = -1;
486 j = elements(tasm_directives);
487 len = 0;
488 while (!nasm_isspace(p[len]) && p[len] != 0)
489 len++;
490 if (len) {
491 oldchar = p[len];
492 p[len] = 0;
493 while (j - i > 1) {
494 k = (j + i) / 2;
495 m = nasm_stricmp(p, tasm_directives[k]);
496 if (m == 0) {
497 /* We have found a directive, so jam a % in front of it
498 * so that NASM will then recognise it as one if it's own.
500 p[len] = oldchar;
501 len = strlen(p);
502 oldline = line;
503 line = nasm_malloc(len + 2);
504 line[0] = '%';
505 if (k == TM_IFDIFI) {
507 * NASM does not recognise IFDIFI, so we convert
508 * it to %if 0. This is not used in NASM
509 * compatible code, but does need to parse for the
510 * TASM macro package.
512 strcpy(line + 1, "if 0");
513 } else {
514 memcpy(line + 1, p, len + 1);
516 nasm_free(oldline);
517 return line;
518 } else if (m < 0) {
519 j = k;
520 } else
521 i = k;
523 p[len] = oldchar;
525 return line;
529 * The pre-preprocessing stage... This function translates line
530 * number indications as they emerge from GNU cpp (`# lineno "file"
531 * flags') into NASM preprocessor line number indications (`%line
532 * lineno file').
534 static char *prepreproc(char *line)
536 int lineno, fnlen;
537 char *fname, *oldline;
539 if (line[0] == '#' && line[1] == ' ') {
540 oldline = line;
541 fname = oldline + 2;
542 lineno = atoi(fname);
543 fname += strspn(fname, "0123456789 ");
544 if (*fname == '"')
545 fname++;
546 fnlen = strcspn(fname, "\"");
547 line = nasm_malloc(20 + fnlen);
548 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
549 nasm_free(oldline);
551 if (tasm_compatible_mode)
552 return check_tasm_directive(line);
553 return line;
557 * Free a linked list of tokens.
559 static void free_tlist(Token * list)
561 while (list) {
562 list = delete_Token(list);
567 * Free a linked list of lines.
569 static void free_llist(Line * list)
571 Line *l;
572 while (list) {
573 l = list;
574 list = list->next;
575 free_tlist(l->first);
576 nasm_free(l);
581 * Free an MMacro
583 static void free_mmacro(MMacro * m)
585 nasm_free(m->name);
586 free_tlist(m->dlist);
587 nasm_free(m->defaults);
588 free_llist(m->expansion);
589 nasm_free(m);
593 * Free all currently defined macros, and free the hash tables
595 static void free_smacro_table(struct hash_table *smt)
597 SMacro *s;
598 const char *key;
599 struct hash_tbl_node *it = NULL;
601 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
602 nasm_free((void *)key);
603 while (s) {
604 SMacro *ns = s->next;
605 nasm_free(s->name);
606 free_tlist(s->expansion);
607 nasm_free(s);
608 s = ns;
611 hash_free(smt);
614 static void free_mmacro_table(struct hash_table *mmt)
616 MMacro *m;
617 const char *key;
618 struct hash_tbl_node *it = NULL;
620 it = NULL;
621 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
622 nasm_free((void *)key);
623 while (m) {
624 MMacro *nm = m->next;
625 free_mmacro(m);
626 m = nm;
629 hash_free(mmt);
632 static void free_macros(void)
634 free_smacro_table(&smacros);
635 free_mmacro_table(&mmacros);
639 * Initialize the hash tables
641 static void init_macros(void)
643 hash_init(&smacros, HASH_LARGE);
644 hash_init(&mmacros, HASH_LARGE);
648 * Pop the context stack.
650 static void ctx_pop(void)
652 Context *c = cstk;
654 cstk = cstk->next;
655 free_smacro_table(&c->localmac);
656 nasm_free(c->name);
657 nasm_free(c);
661 * Search for a key in the hash index; adding it if necessary
662 * (in which case we initialize the data pointer to NULL.)
664 static void **
665 hash_findi_add(struct hash_table *hash, const char *str)
667 struct hash_insert hi;
668 void **r;
669 char *strx;
671 r = hash_findi(hash, str, &hi);
672 if (r)
673 return r;
675 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
676 return hash_add(&hi, strx, NULL);
680 * Like hash_findi, but returns the data element rather than a pointer
681 * to it. Used only when not adding a new element, hence no third
682 * argument.
684 static void *
685 hash_findix(struct hash_table *hash, const char *str)
687 void **p;
689 p = hash_findi(hash, str, NULL);
690 return p ? *p : NULL;
693 #define BUF_DELTA 512
695 * Read a line from the top file in istk, handling multiple CR/LFs
696 * at the end of the line read, and handling spurious ^Zs. Will
697 * return lines from the standard macro set if this has not already
698 * been done.
700 static char *read_line(void)
702 char *buffer, *p, *q;
703 int bufsize, continued_count;
705 if (stdmacpos) {
706 unsigned char c;
707 const unsigned char *p = stdmacpos;
708 char *ret, *q;
709 size_t len = 0;
710 while ((c = *p++)) {
711 if (c >= 0x80)
712 len += pp_directives_len[c-0x80]+1;
713 else
714 len++;
716 ret = nasm_malloc(len+1);
717 q = ret;
718 while ((c = *stdmacpos++)) {
719 if (c >= 0x80) {
720 memcpy(q, pp_directives[c-0x80], pp_directives_len[c-0x80]);
721 q += pp_directives_len[c-0x80];
722 *q++ = ' ';
723 } else {
724 *q++ = c;
727 stdmacpos = p;
728 *q = '\0';
730 if (!*stdmacpos) {
731 /* This was the last of the standard macro chain... */
732 stdmacpos = NULL;
733 if (any_extrastdmac) {
734 stdmacpos = extrastdmac;
735 any_extrastdmac = false;
736 } else if (do_predef) {
737 Line *pd, *l;
738 Token *head, **tail, *t;
741 * Nasty hack: here we push the contents of
742 * `predef' on to the top-level expansion stack,
743 * since this is the most convenient way to
744 * implement the pre-include and pre-define
745 * features.
747 for (pd = predef; pd; pd = pd->next) {
748 head = NULL;
749 tail = &head;
750 for (t = pd->first; t; t = t->next) {
751 *tail = new_Token(NULL, t->type, t->text, 0);
752 tail = &(*tail)->next;
754 l = nasm_malloc(sizeof(Line));
755 l->next = istk->expansion;
756 l->first = head;
757 l->finishes = NULL;
758 istk->expansion = l;
760 do_predef = false;
763 return ret;
766 bufsize = BUF_DELTA;
767 buffer = nasm_malloc(BUF_DELTA);
768 p = buffer;
769 continued_count = 0;
770 while (1) {
771 q = fgets(p, bufsize - (p - buffer), istk->fp);
772 if (!q)
773 break;
774 p += strlen(p);
775 if (p > buffer && p[-1] == '\n') {
776 /* Convert backslash-CRLF line continuation sequences into
777 nothing at all (for DOS and Windows) */
778 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
779 p -= 3;
780 *p = 0;
781 continued_count++;
783 /* Also convert backslash-LF line continuation sequences into
784 nothing at all (for Unix) */
785 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
786 p -= 2;
787 *p = 0;
788 continued_count++;
789 } else {
790 break;
793 if (p - buffer > bufsize - 10) {
794 int32_t offset = p - buffer;
795 bufsize += BUF_DELTA;
796 buffer = nasm_realloc(buffer, bufsize);
797 p = buffer + offset; /* prevent stale-pointer problems */
801 if (!q && p == buffer) {
802 nasm_free(buffer);
803 return NULL;
806 src_set_linnum(src_get_linnum() + istk->lineinc +
807 (continued_count * istk->lineinc));
810 * Play safe: remove CRs as well as LFs, if any of either are
811 * present at the end of the line.
813 while (--p >= buffer && (*p == '\n' || *p == '\r'))
814 *p = '\0';
817 * Handle spurious ^Z, which may be inserted into source files
818 * by some file transfer utilities.
820 buffer[strcspn(buffer, "\032")] = '\0';
822 list->line(LIST_READ, buffer);
824 return buffer;
828 * Tokenize a line of text. This is a very simple process since we
829 * don't need to parse the value out of e.g. numeric tokens: we
830 * simply split one string into many.
832 static Token *tokenize(char *line)
834 char c, *p = line;
835 enum pp_token_type type;
836 Token *list = NULL;
837 Token *t, **tail = &list;
839 while (*line) {
840 p = line;
841 if (*p == '%') {
842 p++;
843 if (*p == '+' && !nasm_isdigit(p[1])) {
844 p++;
845 type = TOK_PASTE;
846 } else if (nasm_isdigit(*p) ||
847 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
848 do {
849 p++;
851 while (nasm_isdigit(*p));
852 type = TOK_PREPROC_ID;
853 } else if (*p == '{') {
854 p++;
855 while (*p && *p != '}') {
856 p[-1] = *p;
857 p++;
859 p[-1] = '\0';
860 if (*p)
861 p++;
862 type = TOK_PREPROC_ID;
863 } else if (*p == '[') {
864 int lvl = 1;
865 line += 2; /* Skip the leading %[ */
866 p++;
867 while (lvl && (c = *p++)) {
868 switch (c) {
869 case ']':
870 lvl--;
871 break;
872 case '%':
873 if (*p == '[')
874 lvl++;
875 break;
876 case '\'':
877 case '\"':
878 case '`':
879 p = nasm_skip_string(p)+1;
880 break;
881 default:
882 break;
885 p--;
886 if (*p)
887 *p++ = '\0';
888 if (lvl)
889 error(ERR_NONFATAL, "unterminated %[ construct");
890 type = TOK_INDIRECT;
891 } else if (*p == '?') {
892 type = TOK_PREPROC_Q; /* %? */
893 p++;
894 if (*p == '?') {
895 type = TOK_PREPROC_QQ; /* %?? */
896 p++;
898 } else if (isidchar(*p) ||
899 ((*p == '!' || *p == '%' || *p == '$') &&
900 isidchar(p[1]))) {
901 do {
902 p++;
904 while (isidchar(*p));
905 type = TOK_PREPROC_ID;
906 } else {
907 type = TOK_OTHER;
908 if (*p == '%')
909 p++;
911 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
912 type = TOK_ID;
913 p++;
914 while (*p && isidchar(*p))
915 p++;
916 } else if (*p == '\'' || *p == '"' || *p == '`') {
918 * A string token.
920 type = TOK_STRING;
921 p = nasm_skip_string(p);
923 if (*p) {
924 p++;
925 } else {
926 error(ERR_WARNING|ERR_PASS1, "unterminated string");
927 /* Handling unterminated strings by UNV */
928 /* type = -1; */
930 } else if (p[0] == '$' && p[1] == '$') {
931 type = TOK_OTHER; /* TOKEN_BASE */
932 p += 2;
933 } else if (isnumstart(*p)) {
934 bool is_hex = false;
935 bool is_float = false;
936 bool has_e = false;
937 char c, *r;
940 * A numeric token.
943 if (*p == '$') {
944 p++;
945 is_hex = true;
948 for (;;) {
949 c = *p++;
951 if (!is_hex && (c == 'e' || c == 'E')) {
952 has_e = true;
953 if (*p == '+' || *p == '-') {
954 /* e can only be followed by +/- if it is either a
955 prefixed hex number or a floating-point number */
956 p++;
957 is_float = true;
959 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
960 is_hex = true;
961 } else if (c == 'P' || c == 'p') {
962 is_float = true;
963 if (*p == '+' || *p == '-')
964 p++;
965 } else if (isnumchar(c) || c == '_')
966 ; /* just advance */
967 else if (c == '.') {
968 /* we need to deal with consequences of the legacy
969 parser, like "1.nolist" being two tokens
970 (TOK_NUMBER, TOK_ID) here; at least give it
971 a shot for now. In the future, we probably need
972 a flex-based scanner with proper pattern matching
973 to do it as well as it can be done. Nothing in
974 the world is going to help the person who wants
975 0x123.p16 interpreted as two tokens, though. */
976 r = p;
977 while (*r == '_')
978 r++;
980 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
981 (!is_hex && (*r == 'e' || *r == 'E')) ||
982 (*r == 'p' || *r == 'P')) {
983 p = r;
984 is_float = true;
985 } else
986 break; /* Terminate the token */
987 } else
988 break;
990 p--; /* Point to first character beyond number */
992 if (p == line+1 && *line == '$') {
993 type = TOK_OTHER; /* TOKEN_HERE */
994 } else {
995 if (has_e && !is_hex) {
996 /* 1e13 is floating-point, but 1e13h is not */
997 is_float = true;
1000 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1002 } else if (nasm_isspace(*p)) {
1003 type = TOK_WHITESPACE;
1004 p++;
1005 while (*p && nasm_isspace(*p))
1006 p++;
1008 * Whitespace just before end-of-line is discarded by
1009 * pretending it's a comment; whitespace just before a
1010 * comment gets lumped into the comment.
1012 if (!*p || *p == ';') {
1013 type = TOK_COMMENT;
1014 while (*p)
1015 p++;
1017 } else if (*p == ';') {
1018 type = TOK_COMMENT;
1019 while (*p)
1020 p++;
1021 } else {
1023 * Anything else is an operator of some kind. We check
1024 * for all the double-character operators (>>, <<, //,
1025 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1026 * else is a single-character operator.
1028 type = TOK_OTHER;
1029 if ((p[0] == '>' && p[1] == '>') ||
1030 (p[0] == '<' && p[1] == '<') ||
1031 (p[0] == '/' && p[1] == '/') ||
1032 (p[0] == '<' && p[1] == '=') ||
1033 (p[0] == '>' && p[1] == '=') ||
1034 (p[0] == '=' && p[1] == '=') ||
1035 (p[0] == '!' && p[1] == '=') ||
1036 (p[0] == '<' && p[1] == '>') ||
1037 (p[0] == '&' && p[1] == '&') ||
1038 (p[0] == '|' && p[1] == '|') ||
1039 (p[0] == '^' && p[1] == '^')) {
1040 p++;
1042 p++;
1045 /* Handling unterminated string by UNV */
1046 /*if (type == -1)
1048 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1049 t->text[p-line] = *line;
1050 tail = &t->next;
1052 else */
1053 if (type != TOK_COMMENT) {
1054 *tail = t = new_Token(NULL, type, line, p - line);
1055 tail = &t->next;
1057 line = p;
1059 return list;
1063 * this function allocates a new managed block of memory and
1064 * returns a pointer to the block. The managed blocks are
1065 * deleted only all at once by the delete_Blocks function.
1067 static void *new_Block(size_t size)
1069 Blocks *b = &blocks;
1071 /* first, get to the end of the linked list */
1072 while (b->next)
1073 b = b->next;
1074 /* now allocate the requested chunk */
1075 b->chunk = nasm_malloc(size);
1077 /* now allocate a new block for the next request */
1078 b->next = nasm_malloc(sizeof(Blocks));
1079 /* and initialize the contents of the new block */
1080 b->next->next = NULL;
1081 b->next->chunk = NULL;
1082 return b->chunk;
1086 * this function deletes all managed blocks of memory
1088 static void delete_Blocks(void)
1090 Blocks *a, *b = &blocks;
1093 * keep in mind that the first block, pointed to by blocks
1094 * is a static and not dynamically allocated, so we don't
1095 * free it.
1097 while (b) {
1098 if (b->chunk)
1099 nasm_free(b->chunk);
1100 a = b;
1101 b = b->next;
1102 if (a != &blocks)
1103 nasm_free(a);
1108 * this function creates a new Token and passes a pointer to it
1109 * back to the caller. It sets the type and text elements, and
1110 * also the a.mac and next elements to NULL.
1112 static Token *new_Token(Token * next, enum pp_token_type type,
1113 const char *text, int txtlen)
1115 Token *t;
1116 int i;
1118 if (freeTokens == NULL) {
1119 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1120 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1121 freeTokens[i].next = &freeTokens[i + 1];
1122 freeTokens[i].next = NULL;
1124 t = freeTokens;
1125 freeTokens = t->next;
1126 t->next = next;
1127 t->a.mac = NULL;
1128 t->type = type;
1129 if (type == TOK_WHITESPACE || text == NULL) {
1130 t->text = NULL;
1131 } else {
1132 if (txtlen == 0)
1133 txtlen = strlen(text);
1134 t->text = nasm_malloc(txtlen+1);
1135 memcpy(t->text, text, txtlen);
1136 t->text[txtlen] = '\0';
1138 return t;
1141 static Token *delete_Token(Token * t)
1143 Token *next = t->next;
1144 nasm_free(t->text);
1145 t->next = freeTokens;
1146 freeTokens = t;
1147 return next;
1151 * Convert a line of tokens back into text.
1152 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1153 * will be transformed into ..@ctxnum.xxx
1155 static char *detoken(Token * tlist, bool expand_locals)
1157 Token *t;
1158 int len;
1159 char *line, *p;
1160 const char *q;
1162 len = 0;
1163 for (t = tlist; t; t = t->next) {
1164 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1165 char *p = getenv(t->text + 2);
1166 nasm_free(t->text);
1167 if (p)
1168 t->text = nasm_strdup(p);
1169 else
1170 t->text = NULL;
1172 /* Expand local macros here and not during preprocessing */
1173 if (expand_locals &&
1174 t->type == TOK_PREPROC_ID && t->text &&
1175 t->text[0] == '%' && t->text[1] == '$') {
1176 const char *q;
1177 char *p;
1178 Context *ctx = get_ctx(t->text, &q, false);
1179 if (ctx) {
1180 char buffer[40];
1181 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1182 p = nasm_strcat(buffer, q);
1183 nasm_free(t->text);
1184 t->text = p;
1187 if (t->type == TOK_WHITESPACE) {
1188 len++;
1189 } else if (t->text) {
1190 len += strlen(t->text);
1193 p = line = nasm_malloc(len + 1);
1194 for (t = tlist; t; t = t->next) {
1195 if (t->type == TOK_WHITESPACE) {
1196 *p++ = ' ';
1197 } else if (t->text) {
1198 q = t->text;
1199 while (*q)
1200 *p++ = *q++;
1203 *p = '\0';
1204 return line;
1208 * A scanner, suitable for use by the expression evaluator, which
1209 * operates on a line of Tokens. Expects a pointer to a pointer to
1210 * the first token in the line to be passed in as its private_data
1211 * field.
1213 * FIX: This really needs to be unified with stdscan.
1215 static int ppscan(void *private_data, struct tokenval *tokval)
1217 Token **tlineptr = private_data;
1218 Token *tline;
1219 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1221 do {
1222 tline = *tlineptr;
1223 *tlineptr = tline ? tline->next : NULL;
1225 while (tline && (tline->type == TOK_WHITESPACE ||
1226 tline->type == TOK_COMMENT));
1228 if (!tline)
1229 return tokval->t_type = TOKEN_EOS;
1231 tokval->t_charptr = tline->text;
1233 if (tline->text[0] == '$' && !tline->text[1])
1234 return tokval->t_type = TOKEN_HERE;
1235 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1236 return tokval->t_type = TOKEN_BASE;
1238 if (tline->type == TOK_ID) {
1239 p = tokval->t_charptr = tline->text;
1240 if (p[0] == '$') {
1241 tokval->t_charptr++;
1242 return tokval->t_type = TOKEN_ID;
1245 for (r = p, s = ourcopy; *r; r++) {
1246 if (r >= p+MAX_KEYWORD)
1247 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1248 *s++ = nasm_tolower(*r);
1250 *s = '\0';
1251 /* right, so we have an identifier sitting in temp storage. now,
1252 * is it actually a register or instruction name, or what? */
1253 return nasm_token_hash(ourcopy, tokval);
1256 if (tline->type == TOK_NUMBER) {
1257 bool rn_error;
1258 tokval->t_integer = readnum(tline->text, &rn_error);
1259 tokval->t_charptr = tline->text;
1260 if (rn_error)
1261 return tokval->t_type = TOKEN_ERRNUM;
1262 else
1263 return tokval->t_type = TOKEN_NUM;
1266 if (tline->type == TOK_FLOAT) {
1267 return tokval->t_type = TOKEN_FLOAT;
1270 if (tline->type == TOK_STRING) {
1271 char bq, *ep;
1273 bq = tline->text[0];
1274 tokval->t_charptr = tline->text;
1275 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1277 if (ep[0] != bq || ep[1] != '\0')
1278 return tokval->t_type = TOKEN_ERRSTR;
1279 else
1280 return tokval->t_type = TOKEN_STR;
1283 if (tline->type == TOK_OTHER) {
1284 if (!strcmp(tline->text, "<<"))
1285 return tokval->t_type = TOKEN_SHL;
1286 if (!strcmp(tline->text, ">>"))
1287 return tokval->t_type = TOKEN_SHR;
1288 if (!strcmp(tline->text, "//"))
1289 return tokval->t_type = TOKEN_SDIV;
1290 if (!strcmp(tline->text, "%%"))
1291 return tokval->t_type = TOKEN_SMOD;
1292 if (!strcmp(tline->text, "=="))
1293 return tokval->t_type = TOKEN_EQ;
1294 if (!strcmp(tline->text, "<>"))
1295 return tokval->t_type = TOKEN_NE;
1296 if (!strcmp(tline->text, "!="))
1297 return tokval->t_type = TOKEN_NE;
1298 if (!strcmp(tline->text, "<="))
1299 return tokval->t_type = TOKEN_LE;
1300 if (!strcmp(tline->text, ">="))
1301 return tokval->t_type = TOKEN_GE;
1302 if (!strcmp(tline->text, "&&"))
1303 return tokval->t_type = TOKEN_DBL_AND;
1304 if (!strcmp(tline->text, "^^"))
1305 return tokval->t_type = TOKEN_DBL_XOR;
1306 if (!strcmp(tline->text, "||"))
1307 return tokval->t_type = TOKEN_DBL_OR;
1311 * We have no other options: just return the first character of
1312 * the token text.
1314 return tokval->t_type = tline->text[0];
1318 * Compare a string to the name of an existing macro; this is a
1319 * simple wrapper which calls either strcmp or nasm_stricmp
1320 * depending on the value of the `casesense' parameter.
1322 static int mstrcmp(const char *p, const char *q, bool casesense)
1324 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1328 * Compare a string to the name of an existing macro; this is a
1329 * simple wrapper which calls either strcmp or nasm_stricmp
1330 * depending on the value of the `casesense' parameter.
1332 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1334 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1338 * Return the Context structure associated with a %$ token. Return
1339 * NULL, having _already_ reported an error condition, if the
1340 * context stack isn't deep enough for the supplied number of $
1341 * signs.
1342 * If all_contexts == true, contexts that enclose current are
1343 * also scanned for such smacro, until it is found; if not -
1344 * only the context that directly results from the number of $'s
1345 * in variable's name.
1347 * If "namep" is non-NULL, set it to the pointer to the macro name
1348 * tail, i.e. the part beyond %$...
1350 static Context *get_ctx(const char *name, const char **namep,
1351 bool all_contexts)
1353 Context *ctx;
1354 SMacro *m;
1355 int i;
1357 if (namep)
1358 *namep = name;
1360 if (!name || name[0] != '%' || name[1] != '$')
1361 return NULL;
1363 if (!cstk) {
1364 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1365 return NULL;
1368 name += 2;
1369 ctx = cstk;
1370 i = 0;
1371 while (ctx && *name == '$') {
1372 name++;
1373 i++;
1374 ctx = ctx->next;
1376 if (!ctx) {
1377 error(ERR_NONFATAL, "`%s': context stack is only"
1378 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1379 return NULL;
1382 if (namep)
1383 *namep = name;
1385 if (!all_contexts)
1386 return ctx;
1388 do {
1389 /* Search for this smacro in found context */
1390 m = hash_findix(&ctx->localmac, name);
1391 while (m) {
1392 if (!mstrcmp(m->name, name, m->casesense))
1393 return ctx;
1394 m = m->next;
1396 ctx = ctx->next;
1398 while (ctx);
1399 return NULL;
1403 * Check to see if a file is already in a string list
1405 static bool in_list(const StrList *list, const char *str)
1407 while (list) {
1408 if (!strcmp(list->str, str))
1409 return true;
1410 list = list->next;
1412 return false;
1416 * Open an include file. This routine must always return a valid
1417 * file pointer if it returns - it's responsible for throwing an
1418 * ERR_FATAL and bombing out completely if not. It should also try
1419 * the include path one by one until it finds the file or reaches
1420 * the end of the path.
1422 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1423 bool missing_ok)
1425 FILE *fp;
1426 char *prefix = "";
1427 IncPath *ip = ipath;
1428 int len = strlen(file);
1429 size_t prefix_len = 0;
1430 StrList *sl;
1432 while (1) {
1433 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1434 memcpy(sl->str, prefix, prefix_len);
1435 memcpy(sl->str+prefix_len, file, len+1);
1436 fp = fopen(sl->str, "r");
1437 if (fp && dhead && !in_list(*dhead, sl->str)) {
1438 sl->next = NULL;
1439 **dtail = sl;
1440 *dtail = &sl->next;
1441 } else {
1442 nasm_free(sl);
1444 if (fp)
1445 return fp;
1446 if (!ip) {
1447 if (!missing_ok)
1448 break;
1449 prefix = NULL;
1450 } else {
1451 prefix = ip->path;
1452 ip = ip->next;
1454 if (prefix) {
1455 prefix_len = strlen(prefix);
1456 } else {
1457 /* -MG given and file not found */
1458 if (dhead && !in_list(*dhead, file)) {
1459 sl = nasm_malloc(len+1+sizeof sl->next);
1460 sl->next = NULL;
1461 strcpy(sl->str, file);
1462 **dtail = sl;
1463 *dtail = &sl->next;
1465 return NULL;
1469 error(ERR_FATAL, "unable to open include file `%s'", file);
1470 return NULL; /* never reached - placate compilers */
1474 * Determine if we should warn on defining a single-line macro of
1475 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1476 * return true if _any_ single-line macro of that name is defined.
1477 * Otherwise, will return true if a single-line macro with either
1478 * `nparam' or no parameters is defined.
1480 * If a macro with precisely the right number of parameters is
1481 * defined, or nparam is -1, the address of the definition structure
1482 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1483 * is NULL, no action will be taken regarding its contents, and no
1484 * error will occur.
1486 * Note that this is also called with nparam zero to resolve
1487 * `ifdef'.
1489 * If you already know which context macro belongs to, you can pass
1490 * the context pointer as first parameter; if you won't but name begins
1491 * with %$ the context will be automatically computed. If all_contexts
1492 * is true, macro will be searched in outer contexts as well.
1494 static bool
1495 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1496 bool nocase)
1498 struct hash_table *smtbl;
1499 SMacro *m;
1501 if (ctx) {
1502 smtbl = &ctx->localmac;
1503 } else if (name[0] == '%' && name[1] == '$') {
1504 if (cstk)
1505 ctx = get_ctx(name, &name, false);
1506 if (!ctx)
1507 return false; /* got to return _something_ */
1508 smtbl = &ctx->localmac;
1509 } else {
1510 smtbl = &smacros;
1512 m = (SMacro *) hash_findix(smtbl, name);
1514 while (m) {
1515 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1516 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1517 if (defn) {
1518 if (nparam == (int) m->nparam || nparam == -1)
1519 *defn = m;
1520 else
1521 *defn = NULL;
1523 return true;
1525 m = m->next;
1528 return false;
1532 * Count and mark off the parameters in a multi-line macro call.
1533 * This is called both from within the multi-line macro expansion
1534 * code, and also to mark off the default parameters when provided
1535 * in a %macro definition line.
1537 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1539 int paramsize, brace;
1541 *nparam = paramsize = 0;
1542 *params = NULL;
1543 while (t) {
1544 /* +1: we need space for the final NULL */
1545 if (*nparam+1 >= paramsize) {
1546 paramsize += PARAM_DELTA;
1547 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1549 skip_white_(t);
1550 brace = false;
1551 if (tok_is_(t, "{"))
1552 brace = true;
1553 (*params)[(*nparam)++] = t;
1554 while (tok_isnt_(t, brace ? "}" : ","))
1555 t = t->next;
1556 if (t) { /* got a comma/brace */
1557 t = t->next;
1558 if (brace) {
1560 * Now we've found the closing brace, look further
1561 * for the comma.
1563 skip_white_(t);
1564 if (tok_isnt_(t, ",")) {
1565 error(ERR_NONFATAL,
1566 "braces do not enclose all of macro parameter");
1567 while (tok_isnt_(t, ","))
1568 t = t->next;
1570 if (t)
1571 t = t->next; /* eat the comma */
1578 * Determine whether one of the various `if' conditions is true or
1579 * not.
1581 * We must free the tline we get passed.
1583 static bool if_condition(Token * tline, enum preproc_token ct)
1585 enum pp_conditional i = PP_COND(ct);
1586 bool j;
1587 Token *t, *tt, **tptr, *origline;
1588 struct tokenval tokval;
1589 expr *evalresult;
1590 enum pp_token_type needtype;
1592 origline = tline;
1594 switch (i) {
1595 case PPC_IFCTX:
1596 j = false; /* have we matched yet? */
1597 while (true) {
1598 skip_white_(tline);
1599 if (!tline)
1600 break;
1601 if (tline->type != TOK_ID) {
1602 error(ERR_NONFATAL,
1603 "`%s' expects context identifiers", pp_directives[ct]);
1604 free_tlist(origline);
1605 return -1;
1607 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1608 j = true;
1609 tline = tline->next;
1611 break;
1613 case PPC_IFDEF:
1614 j = false; /* have we matched yet? */
1615 while (tline) {
1616 skip_white_(tline);
1617 if (!tline || (tline->type != TOK_ID &&
1618 (tline->type != TOK_PREPROC_ID ||
1619 tline->text[1] != '$'))) {
1620 error(ERR_NONFATAL,
1621 "`%s' expects macro identifiers", pp_directives[ct]);
1622 goto fail;
1624 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1625 j = true;
1626 tline = tline->next;
1628 break;
1630 case PPC_IFIDN:
1631 case PPC_IFIDNI:
1632 tline = expand_smacro(tline);
1633 t = tt = tline;
1634 while (tok_isnt_(tt, ","))
1635 tt = tt->next;
1636 if (!tt) {
1637 error(ERR_NONFATAL,
1638 "`%s' expects two comma-separated arguments",
1639 pp_directives[ct]);
1640 goto fail;
1642 tt = tt->next;
1643 j = true; /* assume equality unless proved not */
1644 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1645 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1646 error(ERR_NONFATAL, "`%s': more than one comma on line",
1647 pp_directives[ct]);
1648 goto fail;
1650 if (t->type == TOK_WHITESPACE) {
1651 t = t->next;
1652 continue;
1654 if (tt->type == TOK_WHITESPACE) {
1655 tt = tt->next;
1656 continue;
1658 if (tt->type != t->type) {
1659 j = false; /* found mismatching tokens */
1660 break;
1662 /* When comparing strings, need to unquote them first */
1663 if (t->type == TOK_STRING) {
1664 size_t l1 = nasm_unquote(t->text, NULL);
1665 size_t l2 = nasm_unquote(tt->text, NULL);
1667 if (l1 != l2) {
1668 j = false;
1669 break;
1671 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1672 j = false;
1673 break;
1675 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1676 j = false; /* found mismatching tokens */
1677 break;
1680 t = t->next;
1681 tt = tt->next;
1683 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1684 j = false; /* trailing gunk on one end or other */
1685 break;
1687 case PPC_IFMACRO:
1689 bool found = false;
1690 MMacro searching, *mmac;
1692 skip_white_(tline);
1693 tline = expand_id(tline);
1694 if (!tok_type_(tline, TOK_ID)) {
1695 error(ERR_NONFATAL,
1696 "`%s' expects a macro name", pp_directives[ct]);
1697 goto fail;
1699 searching.name = nasm_strdup(tline->text);
1700 searching.casesense = true;
1701 searching.plus = false;
1702 searching.nolist = false;
1703 searching.in_progress = 0;
1704 searching.max_depth = 0;
1705 searching.rep_nest = NULL;
1706 searching.nparam_min = 0;
1707 searching.nparam_max = INT_MAX;
1708 tline = expand_smacro(tline->next);
1709 skip_white_(tline);
1710 if (!tline) {
1711 } else if (!tok_type_(tline, TOK_NUMBER)) {
1712 error(ERR_NONFATAL,
1713 "`%s' expects a parameter count or nothing",
1714 pp_directives[ct]);
1715 } else {
1716 searching.nparam_min = searching.nparam_max =
1717 readnum(tline->text, &j);
1718 if (j)
1719 error(ERR_NONFATAL,
1720 "unable to parse parameter count `%s'",
1721 tline->text);
1723 if (tline && tok_is_(tline->next, "-")) {
1724 tline = tline->next->next;
1725 if (tok_is_(tline, "*"))
1726 searching.nparam_max = INT_MAX;
1727 else if (!tok_type_(tline, TOK_NUMBER))
1728 error(ERR_NONFATAL,
1729 "`%s' expects a parameter count after `-'",
1730 pp_directives[ct]);
1731 else {
1732 searching.nparam_max = readnum(tline->text, &j);
1733 if (j)
1734 error(ERR_NONFATAL,
1735 "unable to parse parameter count `%s'",
1736 tline->text);
1737 if (searching.nparam_min > searching.nparam_max)
1738 error(ERR_NONFATAL,
1739 "minimum parameter count exceeds maximum");
1742 if (tline && tok_is_(tline->next, "+")) {
1743 tline = tline->next;
1744 searching.plus = true;
1746 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1747 while (mmac) {
1748 if (!strcmp(mmac->name, searching.name) &&
1749 (mmac->nparam_min <= searching.nparam_max
1750 || searching.plus)
1751 && (searching.nparam_min <= mmac->nparam_max
1752 || mmac->plus)) {
1753 found = true;
1754 break;
1756 mmac = mmac->next;
1758 if(tline && tline->next)
1759 error(ERR_WARNING|ERR_PASS1,
1760 "trailing garbage after %%ifmacro ignored");
1761 nasm_free(searching.name);
1762 j = found;
1763 break;
1766 case PPC_IFID:
1767 needtype = TOK_ID;
1768 goto iftype;
1769 case PPC_IFNUM:
1770 needtype = TOK_NUMBER;
1771 goto iftype;
1772 case PPC_IFSTR:
1773 needtype = TOK_STRING;
1774 goto iftype;
1776 iftype:
1777 t = tline = expand_smacro(tline);
1779 while (tok_type_(t, TOK_WHITESPACE) ||
1780 (needtype == TOK_NUMBER &&
1781 tok_type_(t, TOK_OTHER) &&
1782 (t->text[0] == '-' || t->text[0] == '+') &&
1783 !t->text[1]))
1784 t = t->next;
1786 j = tok_type_(t, needtype);
1787 break;
1789 case PPC_IFTOKEN:
1790 t = tline = expand_smacro(tline);
1791 while (tok_type_(t, TOK_WHITESPACE))
1792 t = t->next;
1794 j = false;
1795 if (t) {
1796 t = t->next; /* Skip the actual token */
1797 while (tok_type_(t, TOK_WHITESPACE))
1798 t = t->next;
1799 j = !t; /* Should be nothing left */
1801 break;
1803 case PPC_IFEMPTY:
1804 t = tline = expand_smacro(tline);
1805 while (tok_type_(t, TOK_WHITESPACE))
1806 t = t->next;
1808 j = !t; /* Should be empty */
1809 break;
1811 case PPC_IF:
1812 t = tline = expand_smacro(tline);
1813 tptr = &t;
1814 tokval.t_type = TOKEN_INVALID;
1815 evalresult = evaluate(ppscan, tptr, &tokval,
1816 NULL, pass | CRITICAL, error, NULL);
1817 if (!evalresult)
1818 return -1;
1819 if (tokval.t_type)
1820 error(ERR_WARNING|ERR_PASS1,
1821 "trailing garbage after expression ignored");
1822 if (!is_simple(evalresult)) {
1823 error(ERR_NONFATAL,
1824 "non-constant value given to `%s'", pp_directives[ct]);
1825 goto fail;
1827 j = reloc_value(evalresult) != 0;
1828 break;
1830 default:
1831 error(ERR_FATAL,
1832 "preprocessor directive `%s' not yet implemented",
1833 pp_directives[ct]);
1834 goto fail;
1837 free_tlist(origline);
1838 return j ^ PP_NEGATIVE(ct);
1840 fail:
1841 free_tlist(origline);
1842 return -1;
1846 * Common code for defining an smacro
1848 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1849 int nparam, Token *expansion)
1851 SMacro *smac, **smhead;
1852 struct hash_table *smtbl;
1854 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1855 if (!smac) {
1856 error(ERR_WARNING|ERR_PASS1,
1857 "single-line macro `%s' defined both with and"
1858 " without parameters", mname);
1860 /* Some instances of the old code considered this a failure,
1861 some others didn't. What is the right thing to do here? */
1862 free_tlist(expansion);
1863 return false; /* Failure */
1864 } else {
1866 * We're redefining, so we have to take over an
1867 * existing SMacro structure. This means freeing
1868 * what was already in it.
1870 nasm_free(smac->name);
1871 free_tlist(smac->expansion);
1873 } else {
1874 smtbl = ctx ? &ctx->localmac : &smacros;
1875 smhead = (SMacro **) hash_findi_add(smtbl, mname);
1876 smac = nasm_malloc(sizeof(SMacro));
1877 smac->next = *smhead;
1878 *smhead = smac;
1880 smac->name = nasm_strdup(mname);
1881 smac->casesense = casesense;
1882 smac->nparam = nparam;
1883 smac->expansion = expansion;
1884 smac->in_progress = false;
1885 return true; /* Success */
1889 * Undefine an smacro
1891 static void undef_smacro(Context *ctx, const char *mname)
1893 SMacro **smhead, *s, **sp;
1894 struct hash_table *smtbl;
1896 smtbl = ctx ? &ctx->localmac : &smacros;
1897 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
1899 if (smhead) {
1901 * We now have a macro name... go hunt for it.
1903 sp = smhead;
1904 while ((s = *sp) != NULL) {
1905 if (!mstrcmp(s->name, mname, s->casesense)) {
1906 *sp = s->next;
1907 nasm_free(s->name);
1908 free_tlist(s->expansion);
1909 nasm_free(s);
1910 } else {
1911 sp = &s->next;
1918 * Parse a mmacro specification.
1920 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
1922 bool err;
1924 tline = tline->next;
1925 skip_white_(tline);
1926 tline = expand_id(tline);
1927 if (!tok_type_(tline, TOK_ID)) {
1928 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
1929 return false;
1932 def->prev = NULL;
1933 def->name = nasm_strdup(tline->text);
1934 def->plus = false;
1935 def->nolist = false;
1936 def->in_progress = 0;
1937 def->rep_nest = NULL;
1938 def->nparam_min = 0;
1939 def->nparam_max = 0;
1941 tline = expand_smacro(tline->next);
1942 skip_white_(tline);
1943 if (!tok_type_(tline, TOK_NUMBER)) {
1944 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
1945 } else {
1946 def->nparam_min = def->nparam_max =
1947 readnum(tline->text, &err);
1948 if (err)
1949 error(ERR_NONFATAL,
1950 "unable to parse parameter count `%s'", tline->text);
1952 if (tline && tok_is_(tline->next, "-")) {
1953 tline = tline->next->next;
1954 if (tok_is_(tline, "*")) {
1955 def->nparam_max = INT_MAX;
1956 } else if (!tok_type_(tline, TOK_NUMBER)) {
1957 error(ERR_NONFATAL,
1958 "`%s' expects a parameter count after `-'", directive);
1959 } else {
1960 def->nparam_max = readnum(tline->text, &err);
1961 if (err) {
1962 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
1963 tline->text);
1965 if (def->nparam_min > def->nparam_max) {
1966 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
1970 if (tline && tok_is_(tline->next, "+")) {
1971 tline = tline->next;
1972 def->plus = true;
1974 if (tline && tok_type_(tline->next, TOK_ID) &&
1975 !nasm_stricmp(tline->next->text, ".nolist")) {
1976 tline = tline->next;
1977 def->nolist = true;
1981 * Handle default parameters.
1983 if (tline && tline->next) {
1984 def->dlist = tline->next;
1985 tline->next = NULL;
1986 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
1987 } else {
1988 def->dlist = NULL;
1989 def->defaults = NULL;
1991 def->expansion = NULL;
1993 if(def->defaults &&
1994 def->ndefs > def->nparam_max - def->nparam_min &&
1995 !def->plus)
1996 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
1997 "too many default macro parameters");
1999 return true;
2004 * Decode a size directive
2006 static int parse_size(const char *str) {
2007 static const char *size_names[] =
2008 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2009 static const int sizes[] =
2010 { 0, 1, 4, 16, 8, 10, 2, 32 };
2012 return sizes[bsii(str, size_names, elements(size_names))+1];
2016 * nasm_unquote with error if the string contains NUL characters.
2017 * If the string contains NUL characters, issue an error and return
2018 * the C len, i.e. truncate at the NUL.
2020 static size_t nasm_unquote_cstr(char *qstr, enum preproc_token directive)
2022 size_t len = nasm_unquote(qstr, NULL);
2023 size_t clen = strlen(qstr);
2025 if (len != clen)
2026 error(ERR_NONFATAL, "NUL character in `%s' directive",
2027 pp_directives[directive]);
2029 return clen;
2033 * find and process preprocessor directive in passed line
2034 * Find out if a line contains a preprocessor directive, and deal
2035 * with it if so.
2037 * If a directive _is_ found, it is the responsibility of this routine
2038 * (and not the caller) to free_tlist() the line.
2040 * @param tline a pointer to the current tokeninzed line linked list
2041 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2044 static int do_directive(Token * tline)
2046 enum preproc_token i;
2047 int j;
2048 bool err;
2049 int nparam;
2050 bool nolist;
2051 bool casesense;
2052 int k, m;
2053 int offset;
2054 char *p, *pp;
2055 const char *mname;
2056 Include *inc;
2057 Context *ctx;
2058 Cond *cond;
2059 MMacro *mmac, **mmhead;
2060 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2061 Line *l;
2062 struct tokenval tokval;
2063 expr *evalresult;
2064 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2065 int64_t count;
2066 size_t len;
2067 int severity;
2069 origline = tline;
2071 skip_white_(tline);
2072 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2073 (tline->text[1] == '%' || tline->text[1] == '$'
2074 || tline->text[1] == '!'))
2075 return NO_DIRECTIVE_FOUND;
2077 i = pp_token_hash(tline->text);
2080 * If we're in a non-emitting branch of a condition construct,
2081 * or walking to the end of an already terminated %rep block,
2082 * we should ignore all directives except for condition
2083 * directives.
2085 if (((istk->conds && !emitting(istk->conds->state)) ||
2086 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2087 return NO_DIRECTIVE_FOUND;
2091 * If we're defining a macro or reading a %rep block, we should
2092 * ignore all directives except for %macro/%imacro (which nest),
2093 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2094 * If we're in a %rep block, another %rep nests, so should be let through.
2096 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2097 i != PP_RMACRO && i != PP_RIMACRO &&
2098 i != PP_ENDMACRO && i != PP_ENDM &&
2099 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2100 return NO_DIRECTIVE_FOUND;
2103 if (defining) {
2104 if (i == PP_MACRO || i == PP_IMACRO ||
2105 i == PP_RMACRO || i == PP_RIMACRO) {
2106 nested_mac_count++;
2107 return NO_DIRECTIVE_FOUND;
2108 } else if (nested_mac_count > 0) {
2109 if (i == PP_ENDMACRO) {
2110 nested_mac_count--;
2111 return NO_DIRECTIVE_FOUND;
2114 if (!defining->name) {
2115 if (i == PP_REP) {
2116 nested_rep_count++;
2117 return NO_DIRECTIVE_FOUND;
2118 } else if (nested_rep_count > 0) {
2119 if (i == PP_ENDREP) {
2120 nested_rep_count--;
2121 return NO_DIRECTIVE_FOUND;
2127 switch (i) {
2128 case PP_INVALID:
2129 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2130 tline->text);
2131 return NO_DIRECTIVE_FOUND; /* didn't get it */
2133 case PP_STACKSIZE:
2134 /* Directive to tell NASM what the default stack size is. The
2135 * default is for a 16-bit stack, and this can be overriden with
2136 * %stacksize large.
2137 * the following form:
2139 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2141 tline = tline->next;
2142 if (tline && tline->type == TOK_WHITESPACE)
2143 tline = tline->next;
2144 if (!tline || tline->type != TOK_ID) {
2145 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2146 free_tlist(origline);
2147 return DIRECTIVE_FOUND;
2149 if (nasm_stricmp(tline->text, "flat") == 0) {
2150 /* All subsequent ARG directives are for a 32-bit stack */
2151 StackSize = 4;
2152 StackPointer = "ebp";
2153 ArgOffset = 8;
2154 LocalOffset = 0;
2155 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2156 /* All subsequent ARG directives are for a 64-bit stack */
2157 StackSize = 8;
2158 StackPointer = "rbp";
2159 ArgOffset = 8;
2160 LocalOffset = 0;
2161 } else if (nasm_stricmp(tline->text, "large") == 0) {
2162 /* All subsequent ARG directives are for a 16-bit stack,
2163 * far function call.
2165 StackSize = 2;
2166 StackPointer = "bp";
2167 ArgOffset = 4;
2168 LocalOffset = 0;
2169 } else if (nasm_stricmp(tline->text, "small") == 0) {
2170 /* All subsequent ARG directives are for a 16-bit stack,
2171 * far function call. We don't support near functions.
2173 StackSize = 2;
2174 StackPointer = "bp";
2175 ArgOffset = 6;
2176 LocalOffset = 0;
2177 } else {
2178 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2179 free_tlist(origline);
2180 return DIRECTIVE_FOUND;
2182 free_tlist(origline);
2183 return DIRECTIVE_FOUND;
2185 case PP_ARG:
2186 /* TASM like ARG directive to define arguments to functions, in
2187 * the following form:
2189 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2191 offset = ArgOffset;
2192 do {
2193 char *arg, directive[256];
2194 int size = StackSize;
2196 /* Find the argument name */
2197 tline = tline->next;
2198 if (tline && tline->type == TOK_WHITESPACE)
2199 tline = tline->next;
2200 if (!tline || tline->type != TOK_ID) {
2201 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2202 free_tlist(origline);
2203 return DIRECTIVE_FOUND;
2205 arg = tline->text;
2207 /* Find the argument size type */
2208 tline = tline->next;
2209 if (!tline || tline->type != TOK_OTHER
2210 || tline->text[0] != ':') {
2211 error(ERR_NONFATAL,
2212 "Syntax error processing `%%arg' directive");
2213 free_tlist(origline);
2214 return DIRECTIVE_FOUND;
2216 tline = tline->next;
2217 if (!tline || tline->type != TOK_ID) {
2218 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2219 free_tlist(origline);
2220 return DIRECTIVE_FOUND;
2223 /* Allow macro expansion of type parameter */
2224 tt = tokenize(tline->text);
2225 tt = expand_smacro(tt);
2226 size = parse_size(tt->text);
2227 if (!size) {
2228 error(ERR_NONFATAL,
2229 "Invalid size type for `%%arg' missing directive");
2230 free_tlist(tt);
2231 free_tlist(origline);
2232 return DIRECTIVE_FOUND;
2234 free_tlist(tt);
2236 /* Round up to even stack slots */
2237 size = (size+StackSize-1) & ~(StackSize-1);
2239 /* Now define the macro for the argument */
2240 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2241 arg, StackPointer, offset);
2242 do_directive(tokenize(directive));
2243 offset += size;
2245 /* Move to the next argument in the list */
2246 tline = tline->next;
2247 if (tline && tline->type == TOK_WHITESPACE)
2248 tline = tline->next;
2249 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2250 ArgOffset = offset;
2251 free_tlist(origline);
2252 return DIRECTIVE_FOUND;
2254 case PP_LOCAL:
2255 /* TASM like LOCAL directive to define local variables for a
2256 * function, in the following form:
2258 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2260 * The '= LocalSize' at the end is ignored by NASM, but is
2261 * required by TASM to define the local parameter size (and used
2262 * by the TASM macro package).
2264 offset = LocalOffset;
2265 do {
2266 char *local, directive[256];
2267 int size = StackSize;
2269 /* Find the argument name */
2270 tline = tline->next;
2271 if (tline && tline->type == TOK_WHITESPACE)
2272 tline = tline->next;
2273 if (!tline || tline->type != TOK_ID) {
2274 error(ERR_NONFATAL,
2275 "`%%local' missing argument parameter");
2276 free_tlist(origline);
2277 return DIRECTIVE_FOUND;
2279 local = tline->text;
2281 /* Find the argument size type */
2282 tline = tline->next;
2283 if (!tline || tline->type != TOK_OTHER
2284 || tline->text[0] != ':') {
2285 error(ERR_NONFATAL,
2286 "Syntax error processing `%%local' directive");
2287 free_tlist(origline);
2288 return DIRECTIVE_FOUND;
2290 tline = tline->next;
2291 if (!tline || tline->type != TOK_ID) {
2292 error(ERR_NONFATAL,
2293 "`%%local' missing size type parameter");
2294 free_tlist(origline);
2295 return DIRECTIVE_FOUND;
2298 /* Allow macro expansion of type parameter */
2299 tt = tokenize(tline->text);
2300 tt = expand_smacro(tt);
2301 size = parse_size(tt->text);
2302 if (!size) {
2303 error(ERR_NONFATAL,
2304 "Invalid size type for `%%local' missing directive");
2305 free_tlist(tt);
2306 free_tlist(origline);
2307 return DIRECTIVE_FOUND;
2309 free_tlist(tt);
2311 /* Round up to even stack slots */
2312 size = (size+StackSize-1) & ~(StackSize-1);
2314 offset += size; /* Negative offset, increment before */
2316 /* Now define the macro for the argument */
2317 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2318 local, StackPointer, offset);
2319 do_directive(tokenize(directive));
2321 /* Now define the assign to setup the enter_c macro correctly */
2322 snprintf(directive, sizeof(directive),
2323 "%%assign %%$localsize %%$localsize+%d", size);
2324 do_directive(tokenize(directive));
2326 /* Move to the next argument in the list */
2327 tline = tline->next;
2328 if (tline && tline->type == TOK_WHITESPACE)
2329 tline = tline->next;
2330 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2331 LocalOffset = offset;
2332 free_tlist(origline);
2333 return DIRECTIVE_FOUND;
2335 case PP_CLEAR:
2336 if (tline->next)
2337 error(ERR_WARNING|ERR_PASS1,
2338 "trailing garbage after `%%clear' ignored");
2339 free_macros();
2340 init_macros();
2341 free_tlist(origline);
2342 return DIRECTIVE_FOUND;
2344 case PP_DEPEND:
2345 t = tline->next = expand_smacro(tline->next);
2346 skip_white_(t);
2347 if (!t || (t->type != TOK_STRING &&
2348 t->type != TOK_INTERNAL_STRING)) {
2349 error(ERR_NONFATAL, "`%%depend' expects a file name");
2350 free_tlist(origline);
2351 return DIRECTIVE_FOUND; /* but we did _something_ */
2353 if (t->next)
2354 error(ERR_WARNING|ERR_PASS1,
2355 "trailing garbage after `%%depend' ignored");
2356 p = t->text;
2357 if (t->type != TOK_INTERNAL_STRING)
2358 nasm_unquote_cstr(p, i);
2359 if (dephead && !in_list(*dephead, p)) {
2360 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2361 sl->next = NULL;
2362 strcpy(sl->str, p);
2363 *deptail = sl;
2364 deptail = &sl->next;
2366 free_tlist(origline);
2367 return DIRECTIVE_FOUND;
2369 case PP_INCLUDE:
2370 t = tline->next = expand_smacro(tline->next);
2371 skip_white_(t);
2373 if (!t || (t->type != TOK_STRING &&
2374 t->type != TOK_INTERNAL_STRING)) {
2375 error(ERR_NONFATAL, "`%%include' expects a file name");
2376 free_tlist(origline);
2377 return DIRECTIVE_FOUND; /* but we did _something_ */
2379 if (t->next)
2380 error(ERR_WARNING|ERR_PASS1,
2381 "trailing garbage after `%%include' ignored");
2382 p = t->text;
2383 if (t->type != TOK_INTERNAL_STRING)
2384 nasm_unquote_cstr(p, i);
2385 inc = nasm_malloc(sizeof(Include));
2386 inc->next = istk;
2387 inc->conds = NULL;
2388 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2389 if (!inc->fp) {
2390 /* -MG given but file not found */
2391 nasm_free(inc);
2392 } else {
2393 inc->fname = src_set_fname(nasm_strdup(p));
2394 inc->lineno = src_set_linnum(0);
2395 inc->lineinc = 1;
2396 inc->expansion = NULL;
2397 inc->mstk = NULL;
2398 istk = inc;
2399 list->uplevel(LIST_INCLUDE);
2401 free_tlist(origline);
2402 return DIRECTIVE_FOUND;
2404 case PP_USE:
2406 static macros_t *use_pkg;
2407 const char *pkg_macro;
2409 tline = tline->next;
2410 skip_white_(tline);
2411 tline = expand_id(tline);
2413 if (!tline || (tline->type != TOK_STRING &&
2414 tline->type != TOK_INTERNAL_STRING &&
2415 tline->type != TOK_ID)) {
2416 error(ERR_NONFATAL, "`%%use' expects a package name");
2417 free_tlist(origline);
2418 return DIRECTIVE_FOUND; /* but we did _something_ */
2420 if (tline->next)
2421 error(ERR_WARNING|ERR_PASS1,
2422 "trailing garbage after `%%use' ignored");
2423 if (tline->type == TOK_STRING)
2424 nasm_unquote_cstr(tline->text, i);
2425 use_pkg = nasm_stdmac_find_package(tline->text);
2426 if (!use_pkg)
2427 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2428 /* The first string will be <%define>__USE_*__ */
2429 pkg_macro = (char *)use_pkg + 1;
2430 if (!smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2431 /* Not already included, go ahead and include it */
2432 stdmacpos = use_pkg;
2434 free_tlist(origline);
2435 return DIRECTIVE_FOUND;
2437 case PP_PUSH:
2438 case PP_REPL:
2439 case PP_POP:
2440 tline = tline->next;
2441 skip_white_(tline);
2442 tline = expand_id(tline);
2443 if (tline) {
2444 if (!tok_type_(tline, TOK_ID)) {
2445 error(ERR_NONFATAL, "`%s' expects a context identifier",
2446 pp_directives[i]);
2447 free_tlist(origline);
2448 return DIRECTIVE_FOUND; /* but we did _something_ */
2450 if (tline->next)
2451 error(ERR_WARNING|ERR_PASS1,
2452 "trailing garbage after `%s' ignored",
2453 pp_directives[i]);
2454 p = nasm_strdup(tline->text);
2455 } else {
2456 p = NULL; /* Anonymous */
2459 if (i == PP_PUSH) {
2460 ctx = nasm_malloc(sizeof(Context));
2461 ctx->next = cstk;
2462 hash_init(&ctx->localmac, HASH_SMALL);
2463 ctx->name = p;
2464 ctx->number = unique++;
2465 cstk = ctx;
2466 } else {
2467 /* %pop or %repl */
2468 if (!cstk) {
2469 error(ERR_NONFATAL, "`%s': context stack is empty",
2470 pp_directives[i]);
2471 } else if (i == PP_POP) {
2472 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2473 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2474 "expected %s",
2475 cstk->name ? cstk->name : "anonymous", p);
2476 else
2477 ctx_pop();
2478 } else {
2479 /* i == PP_REPL */
2480 nasm_free(cstk->name);
2481 cstk->name = p;
2482 p = NULL;
2484 nasm_free(p);
2486 free_tlist(origline);
2487 return DIRECTIVE_FOUND;
2488 case PP_FATAL:
2489 severity = ERR_FATAL;
2490 goto issue_error;
2491 case PP_ERROR:
2492 severity = ERR_NONFATAL;
2493 goto issue_error;
2494 case PP_WARNING:
2495 severity = ERR_WARNING|ERR_WARN_USER;
2496 goto issue_error;
2498 issue_error:
2500 /* Only error out if this is the final pass */
2501 if (pass != 2 && i != PP_FATAL)
2502 return DIRECTIVE_FOUND;
2504 tline->next = expand_smacro(tline->next);
2505 tline = tline->next;
2506 skip_white_(tline);
2507 t = tline ? tline->next : NULL;
2508 skip_white_(t);
2509 if (tok_type_(tline, TOK_STRING) && !t) {
2510 /* The line contains only a quoted string */
2511 p = tline->text;
2512 nasm_unquote(p, NULL); /* Ignore NUL character truncation */
2513 error(severity, "%s", p);
2514 } else {
2515 /* Not a quoted string, or more than a quoted string */
2516 p = detoken(tline, false);
2517 error(severity, "%s", p);
2518 nasm_free(p);
2520 free_tlist(origline);
2521 return DIRECTIVE_FOUND;
2524 CASE_PP_IF:
2525 if (istk->conds && !emitting(istk->conds->state))
2526 j = COND_NEVER;
2527 else {
2528 j = if_condition(tline->next, i);
2529 tline->next = NULL; /* it got freed */
2530 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2532 cond = nasm_malloc(sizeof(Cond));
2533 cond->next = istk->conds;
2534 cond->state = j;
2535 istk->conds = cond;
2536 free_tlist(origline);
2537 return DIRECTIVE_FOUND;
2539 CASE_PP_ELIF:
2540 if (!istk->conds)
2541 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2542 switch(istk->conds->state) {
2543 case COND_IF_TRUE:
2544 istk->conds->state = COND_DONE;
2545 break;
2547 case COND_DONE:
2548 case COND_NEVER:
2549 break;
2551 case COND_ELSE_TRUE:
2552 case COND_ELSE_FALSE:
2553 error_precond(ERR_WARNING|ERR_PASS1,
2554 "`%%elif' after `%%else' ignored");
2555 istk->conds->state = COND_NEVER;
2556 break;
2558 case COND_IF_FALSE:
2560 * IMPORTANT: In the case of %if, we will already have
2561 * called expand_mmac_params(); however, if we're
2562 * processing an %elif we must have been in a
2563 * non-emitting mode, which would have inhibited
2564 * the normal invocation of expand_mmac_params().
2565 * Therefore, we have to do it explicitly here.
2567 j = if_condition(expand_mmac_params(tline->next), i);
2568 tline->next = NULL; /* it got freed */
2569 istk->conds->state =
2570 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2571 break;
2573 free_tlist(origline);
2574 return DIRECTIVE_FOUND;
2576 case PP_ELSE:
2577 if (tline->next)
2578 error_precond(ERR_WARNING|ERR_PASS1,
2579 "trailing garbage after `%%else' ignored");
2580 if (!istk->conds)
2581 error(ERR_FATAL, "`%%else': no matching `%%if'");
2582 switch(istk->conds->state) {
2583 case COND_IF_TRUE:
2584 case COND_DONE:
2585 istk->conds->state = COND_ELSE_FALSE;
2586 break;
2588 case COND_NEVER:
2589 break;
2591 case COND_IF_FALSE:
2592 istk->conds->state = COND_ELSE_TRUE;
2593 break;
2595 case COND_ELSE_TRUE:
2596 case COND_ELSE_FALSE:
2597 error_precond(ERR_WARNING|ERR_PASS1,
2598 "`%%else' after `%%else' ignored.");
2599 istk->conds->state = COND_NEVER;
2600 break;
2602 free_tlist(origline);
2603 return DIRECTIVE_FOUND;
2605 case PP_ENDIF:
2606 if (tline->next)
2607 error_precond(ERR_WARNING|ERR_PASS1,
2608 "trailing garbage after `%%endif' ignored");
2609 if (!istk->conds)
2610 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2611 cond = istk->conds;
2612 istk->conds = cond->next;
2613 nasm_free(cond);
2614 free_tlist(origline);
2615 return DIRECTIVE_FOUND;
2617 case PP_RMACRO:
2618 case PP_RIMACRO:
2619 case PP_MACRO:
2620 case PP_IMACRO:
2621 if (defining) {
2622 error(ERR_FATAL,
2623 "`%%%smacro': already defining a macro",
2624 (i == PP_IMACRO ? "i" :
2625 i == PP_RMACRO ? "r" :
2626 i == PP_RIMACRO ? "ri" : ""));
2627 return DIRECTIVE_FOUND;
2629 defining = nasm_malloc(sizeof(MMacro));
2630 defining->max_depth = (((i == PP_RMACRO) || (i == PP_RIMACRO))
2631 ? (DEADMAN_LIMIT) : 0);
2632 defining->casesense = ((i == PP_MACRO) || (i == PP_RMACRO));
2633 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2634 nasm_free(defining);
2635 defining = NULL;
2636 return DIRECTIVE_FOUND;
2639 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2640 while (mmac) {
2641 if (!strcmp(mmac->name, defining->name) &&
2642 (mmac->nparam_min <= defining->nparam_max
2643 || defining->plus)
2644 && (defining->nparam_min <= mmac->nparam_max
2645 || mmac->plus)) {
2646 error(ERR_WARNING|ERR_PASS1,
2647 "redefining multi-line macro `%s'", defining->name);
2648 return DIRECTIVE_FOUND;
2650 mmac = mmac->next;
2652 free_tlist(origline);
2653 return DIRECTIVE_FOUND;
2655 case PP_ENDM:
2656 case PP_ENDMACRO:
2657 if (! (defining && defining->name)) {
2658 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2659 return DIRECTIVE_FOUND;
2661 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2662 defining->next = *mmhead;
2663 *mmhead = defining;
2664 defining = NULL;
2665 free_tlist(origline);
2666 return DIRECTIVE_FOUND;
2668 case PP_EXITMACRO:
2670 * We must search along istk->expansion until we hit a
2671 * macro-end marker for a macro with a name. Then we set
2672 * its `in_progress' flag to 0.
2674 for (l = istk->expansion; l; l = l->next)
2675 if (l->finishes && l->finishes->name)
2676 break;
2678 if (l) {
2679 l->finishes->in_progress = 0;
2680 } else {
2681 error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2683 free_tlist(origline);
2684 return DIRECTIVE_FOUND;
2686 case PP_UNMACRO:
2687 case PP_UNIMACRO:
2689 MMacro **mmac_p;
2690 MMacro spec;
2692 spec.casesense = (i == PP_UNMACRO);
2693 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2694 return DIRECTIVE_FOUND;
2696 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2697 while (mmac_p && *mmac_p) {
2698 mmac = *mmac_p;
2699 if (mmac->casesense == spec.casesense &&
2700 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2701 mmac->nparam_min == spec.nparam_min &&
2702 mmac->nparam_max == spec.nparam_max &&
2703 mmac->plus == spec.plus) {
2704 *mmac_p = mmac->next;
2705 free_mmacro(mmac);
2706 } else {
2707 mmac_p = &mmac->next;
2710 free_tlist(origline);
2711 free_tlist(spec.dlist);
2712 return DIRECTIVE_FOUND;
2715 case PP_ROTATE:
2716 if (tline->next && tline->next->type == TOK_WHITESPACE)
2717 tline = tline->next;
2718 if (tline->next == NULL) {
2719 free_tlist(origline);
2720 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2721 return DIRECTIVE_FOUND;
2723 t = expand_smacro(tline->next);
2724 tline->next = NULL;
2725 free_tlist(origline);
2726 tline = t;
2727 tptr = &t;
2728 tokval.t_type = TOKEN_INVALID;
2729 evalresult =
2730 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2731 free_tlist(tline);
2732 if (!evalresult)
2733 return DIRECTIVE_FOUND;
2734 if (tokval.t_type)
2735 error(ERR_WARNING|ERR_PASS1,
2736 "trailing garbage after expression ignored");
2737 if (!is_simple(evalresult)) {
2738 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2739 return DIRECTIVE_FOUND;
2741 mmac = istk->mstk;
2742 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2743 mmac = mmac->next_active;
2744 if (!mmac) {
2745 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2746 } else if (mmac->nparam == 0) {
2747 error(ERR_NONFATAL,
2748 "`%%rotate' invoked within macro without parameters");
2749 } else {
2750 int rotate = mmac->rotate + reloc_value(evalresult);
2752 rotate %= (int)mmac->nparam;
2753 if (rotate < 0)
2754 rotate += mmac->nparam;
2756 mmac->rotate = rotate;
2758 return DIRECTIVE_FOUND;
2760 case PP_REP:
2761 nolist = false;
2762 do {
2763 tline = tline->next;
2764 } while (tok_type_(tline, TOK_WHITESPACE));
2766 if (tok_type_(tline, TOK_ID) &&
2767 nasm_stricmp(tline->text, ".nolist") == 0) {
2768 nolist = true;
2769 do {
2770 tline = tline->next;
2771 } while (tok_type_(tline, TOK_WHITESPACE));
2774 if (tline) {
2775 t = expand_smacro(tline);
2776 tptr = &t;
2777 tokval.t_type = TOKEN_INVALID;
2778 evalresult =
2779 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2780 if (!evalresult) {
2781 free_tlist(origline);
2782 return DIRECTIVE_FOUND;
2784 if (tokval.t_type)
2785 error(ERR_WARNING|ERR_PASS1,
2786 "trailing garbage after expression ignored");
2787 if (!is_simple(evalresult)) {
2788 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2789 return DIRECTIVE_FOUND;
2791 count = reloc_value(evalresult) + 1;
2792 } else {
2793 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2794 count = 0;
2796 free_tlist(origline);
2798 tmp_defining = defining;
2799 defining = nasm_malloc(sizeof(MMacro));
2800 defining->prev = NULL;
2801 defining->name = NULL; /* flags this macro as a %rep block */
2802 defining->casesense = false;
2803 defining->plus = false;
2804 defining->nolist = nolist;
2805 defining->in_progress = count;
2806 defining->max_depth = 0;
2807 defining->nparam_min = defining->nparam_max = 0;
2808 defining->defaults = NULL;
2809 defining->dlist = NULL;
2810 defining->expansion = NULL;
2811 defining->next_active = istk->mstk;
2812 defining->rep_nest = tmp_defining;
2813 return DIRECTIVE_FOUND;
2815 case PP_ENDREP:
2816 if (!defining || defining->name) {
2817 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2818 return DIRECTIVE_FOUND;
2822 * Now we have a "macro" defined - although it has no name
2823 * and we won't be entering it in the hash tables - we must
2824 * push a macro-end marker for it on to istk->expansion.
2825 * After that, it will take care of propagating itself (a
2826 * macro-end marker line for a macro which is really a %rep
2827 * block will cause the macro to be re-expanded, complete
2828 * with another macro-end marker to ensure the process
2829 * continues) until the whole expansion is forcibly removed
2830 * from istk->expansion by a %exitrep.
2832 l = nasm_malloc(sizeof(Line));
2833 l->next = istk->expansion;
2834 l->finishes = defining;
2835 l->first = NULL;
2836 istk->expansion = l;
2838 istk->mstk = defining;
2840 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2841 tmp_defining = defining;
2842 defining = defining->rep_nest;
2843 free_tlist(origline);
2844 return DIRECTIVE_FOUND;
2846 case PP_EXITREP:
2848 * We must search along istk->expansion until we hit a
2849 * macro-end marker for a macro with no name. Then we set
2850 * its `in_progress' flag to 0.
2852 for (l = istk->expansion; l; l = l->next)
2853 if (l->finishes && !l->finishes->name)
2854 break;
2856 if (l)
2857 l->finishes->in_progress = 1;
2858 else
2859 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2860 free_tlist(origline);
2861 return DIRECTIVE_FOUND;
2863 case PP_XDEFINE:
2864 case PP_IXDEFINE:
2865 case PP_DEFINE:
2866 case PP_IDEFINE:
2867 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2869 tline = tline->next;
2870 skip_white_(tline);
2871 tline = expand_id(tline);
2872 if (!tline || (tline->type != TOK_ID &&
2873 (tline->type != TOK_PREPROC_ID ||
2874 tline->text[1] != '$'))) {
2875 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2876 pp_directives[i]);
2877 free_tlist(origline);
2878 return DIRECTIVE_FOUND;
2881 ctx = get_ctx(tline->text, &mname, false);
2882 last = tline;
2883 param_start = tline = tline->next;
2884 nparam = 0;
2886 /* Expand the macro definition now for %xdefine and %ixdefine */
2887 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2888 tline = expand_smacro(tline);
2890 if (tok_is_(tline, "(")) {
2892 * This macro has parameters.
2895 tline = tline->next;
2896 while (1) {
2897 skip_white_(tline);
2898 if (!tline) {
2899 error(ERR_NONFATAL, "parameter identifier expected");
2900 free_tlist(origline);
2901 return DIRECTIVE_FOUND;
2903 if (tline->type != TOK_ID) {
2904 error(ERR_NONFATAL,
2905 "`%s': parameter identifier expected",
2906 tline->text);
2907 free_tlist(origline);
2908 return DIRECTIVE_FOUND;
2910 tline->type = TOK_SMAC_PARAM + nparam++;
2911 tline = tline->next;
2912 skip_white_(tline);
2913 if (tok_is_(tline, ",")) {
2914 tline = tline->next;
2915 } else {
2916 if (!tok_is_(tline, ")")) {
2917 error(ERR_NONFATAL,
2918 "`)' expected to terminate macro template");
2919 free_tlist(origline);
2920 return DIRECTIVE_FOUND;
2922 break;
2925 last = tline;
2926 tline = tline->next;
2928 if (tok_type_(tline, TOK_WHITESPACE))
2929 last = tline, tline = tline->next;
2930 macro_start = NULL;
2931 last->next = NULL;
2932 t = tline;
2933 while (t) {
2934 if (t->type == TOK_ID) {
2935 for (tt = param_start; tt; tt = tt->next)
2936 if (tt->type >= TOK_SMAC_PARAM &&
2937 !strcmp(tt->text, t->text))
2938 t->type = tt->type;
2940 tt = t->next;
2941 t->next = macro_start;
2942 macro_start = t;
2943 t = tt;
2946 * Good. We now have a macro name, a parameter count, and a
2947 * token list (in reverse order) for an expansion. We ought
2948 * to be OK just to create an SMacro, store it, and let
2949 * free_tlist have the rest of the line (which we have
2950 * carefully re-terminated after chopping off the expansion
2951 * from the end).
2953 define_smacro(ctx, mname, casesense, nparam, macro_start);
2954 free_tlist(origline);
2955 return DIRECTIVE_FOUND;
2957 case PP_UNDEF:
2958 tline = tline->next;
2959 skip_white_(tline);
2960 tline = expand_id(tline);
2961 if (!tline || (tline->type != TOK_ID &&
2962 (tline->type != TOK_PREPROC_ID ||
2963 tline->text[1] != '$'))) {
2964 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2965 free_tlist(origline);
2966 return DIRECTIVE_FOUND;
2968 if (tline->next) {
2969 error(ERR_WARNING|ERR_PASS1,
2970 "trailing garbage after macro name ignored");
2973 /* Find the context that symbol belongs to */
2974 ctx = get_ctx(tline->text, &mname, false);
2975 undef_smacro(ctx, mname);
2976 free_tlist(origline);
2977 return DIRECTIVE_FOUND;
2979 case PP_DEFSTR:
2980 case PP_IDEFSTR:
2981 casesense = (i == PP_DEFSTR);
2983 tline = tline->next;
2984 skip_white_(tline);
2985 tline = expand_id(tline);
2986 if (!tline || (tline->type != TOK_ID &&
2987 (tline->type != TOK_PREPROC_ID ||
2988 tline->text[1] != '$'))) {
2989 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2990 pp_directives[i]);
2991 free_tlist(origline);
2992 return DIRECTIVE_FOUND;
2995 ctx = get_ctx(tline->text, &mname, false);
2996 last = tline;
2997 tline = expand_smacro(tline->next);
2998 last->next = NULL;
3000 while (tok_type_(tline, TOK_WHITESPACE))
3001 tline = delete_Token(tline);
3003 p = detoken(tline, false);
3004 macro_start = nasm_malloc(sizeof(*macro_start));
3005 macro_start->next = NULL;
3006 macro_start->text = nasm_quote(p, strlen(p));
3007 macro_start->type = TOK_STRING;
3008 macro_start->a.mac = NULL;
3009 nasm_free(p);
3012 * We now have a macro name, an implicit parameter count of
3013 * zero, and a string token to use as an expansion. Create
3014 * and store an SMacro.
3016 define_smacro(ctx, mname, casesense, 0, macro_start);
3017 free_tlist(origline);
3018 return DIRECTIVE_FOUND;
3020 case PP_DEFTOK:
3021 case PP_IDEFTOK:
3022 casesense = (i == PP_DEFTOK);
3024 tline = tline->next;
3025 skip_white_(tline);
3026 tline = expand_id(tline);
3027 if (!tline || (tline->type != TOK_ID &&
3028 (tline->type != TOK_PREPROC_ID ||
3029 tline->text[1] != '$'))) {
3030 error(ERR_NONFATAL,
3031 "`%s' expects a macro identifier as first parameter",
3032 pp_directives[i]);
3033 free_tlist(origline);
3034 return DIRECTIVE_FOUND;
3036 ctx = get_ctx(tline->text, &mname, false);
3037 last = tline;
3038 tline = expand_smacro(tline->next);
3039 last->next = NULL;
3041 t = tline;
3042 while (tok_type_(t, TOK_WHITESPACE))
3043 t = t->next;
3044 /* t should now point to the string */
3045 if (t->type != TOK_STRING) {
3046 error(ERR_NONFATAL,
3047 "`%s` requires string as second parameter",
3048 pp_directives[i]);
3049 free_tlist(tline);
3050 free_tlist(origline);
3051 return DIRECTIVE_FOUND;
3054 nasm_unquote_cstr(t->text, i);
3055 macro_start = tokenize(t->text);
3058 * We now have a macro name, an implicit parameter count of
3059 * zero, and a numeric token to use as an expansion. Create
3060 * and store an SMacro.
3062 define_smacro(ctx, mname, casesense, 0, macro_start);
3063 free_tlist(tline);
3064 free_tlist(origline);
3065 return DIRECTIVE_FOUND;
3067 case PP_PATHSEARCH:
3069 FILE *fp;
3070 StrList *xsl = NULL;
3071 StrList **xst = &xsl;
3073 casesense = true;
3075 tline = tline->next;
3076 skip_white_(tline);
3077 tline = expand_id(tline);
3078 if (!tline || (tline->type != TOK_ID &&
3079 (tline->type != TOK_PREPROC_ID ||
3080 tline->text[1] != '$'))) {
3081 error(ERR_NONFATAL,
3082 "`%%pathsearch' expects a macro identifier as first parameter");
3083 free_tlist(origline);
3084 return DIRECTIVE_FOUND;
3086 ctx = get_ctx(tline->text, &mname, false);
3087 last = tline;
3088 tline = expand_smacro(tline->next);
3089 last->next = NULL;
3091 t = tline;
3092 while (tok_type_(t, TOK_WHITESPACE))
3093 t = t->next;
3095 if (!t || (t->type != TOK_STRING &&
3096 t->type != TOK_INTERNAL_STRING)) {
3097 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3098 free_tlist(tline);
3099 free_tlist(origline);
3100 return DIRECTIVE_FOUND; /* but we did _something_ */
3102 if (t->next)
3103 error(ERR_WARNING|ERR_PASS1,
3104 "trailing garbage after `%%pathsearch' ignored");
3105 p = t->text;
3106 if (t->type != TOK_INTERNAL_STRING)
3107 nasm_unquote(p, NULL);
3109 fp = inc_fopen(p, &xsl, &xst, true);
3110 if (fp) {
3111 p = xsl->str;
3112 fclose(fp); /* Don't actually care about the file */
3114 macro_start = nasm_malloc(sizeof(*macro_start));
3115 macro_start->next = NULL;
3116 macro_start->text = nasm_quote(p, strlen(p));
3117 macro_start->type = TOK_STRING;
3118 macro_start->a.mac = NULL;
3119 if (xsl)
3120 nasm_free(xsl);
3123 * We now have a macro name, an implicit parameter count of
3124 * zero, and a string token to use as an expansion. Create
3125 * and store an SMacro.
3127 define_smacro(ctx, mname, casesense, 0, macro_start);
3128 free_tlist(tline);
3129 free_tlist(origline);
3130 return DIRECTIVE_FOUND;
3133 case PP_STRLEN:
3134 casesense = true;
3136 tline = tline->next;
3137 skip_white_(tline);
3138 tline = expand_id(tline);
3139 if (!tline || (tline->type != TOK_ID &&
3140 (tline->type != TOK_PREPROC_ID ||
3141 tline->text[1] != '$'))) {
3142 error(ERR_NONFATAL,
3143 "`%%strlen' expects a macro identifier as first parameter");
3144 free_tlist(origline);
3145 return DIRECTIVE_FOUND;
3147 ctx = get_ctx(tline->text, &mname, false);
3148 last = tline;
3149 tline = expand_smacro(tline->next);
3150 last->next = NULL;
3152 t = tline;
3153 while (tok_type_(t, TOK_WHITESPACE))
3154 t = t->next;
3155 /* t should now point to the string */
3156 if (t->type != TOK_STRING) {
3157 error(ERR_NONFATAL,
3158 "`%%strlen` requires string as second parameter");
3159 free_tlist(tline);
3160 free_tlist(origline);
3161 return DIRECTIVE_FOUND;
3164 macro_start = nasm_malloc(sizeof(*macro_start));
3165 macro_start->next = NULL;
3166 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3167 macro_start->a.mac = NULL;
3170 * We now have a macro name, an implicit parameter count of
3171 * zero, and a numeric token to use as an expansion. Create
3172 * and store an SMacro.
3174 define_smacro(ctx, mname, casesense, 0, macro_start);
3175 free_tlist(tline);
3176 free_tlist(origline);
3177 return DIRECTIVE_FOUND;
3179 case PP_STRCAT:
3180 casesense = true;
3182 tline = tline->next;
3183 skip_white_(tline);
3184 tline = expand_id(tline);
3185 if (!tline || (tline->type != TOK_ID &&
3186 (tline->type != TOK_PREPROC_ID ||
3187 tline->text[1] != '$'))) {
3188 error(ERR_NONFATAL,
3189 "`%%strcat' expects a macro identifier as first parameter");
3190 free_tlist(origline);
3191 return DIRECTIVE_FOUND;
3193 ctx = get_ctx(tline->text, &mname, false);
3194 last = tline;
3195 tline = expand_smacro(tline->next);
3196 last->next = NULL;
3198 len = 0;
3199 for (t = tline; t; t = t->next) {
3200 switch (t->type) {
3201 case TOK_WHITESPACE:
3202 break;
3203 case TOK_STRING:
3204 len += t->a.len = nasm_unquote(t->text, NULL);
3205 break;
3206 case TOK_OTHER:
3207 if (!strcmp(t->text, ",")) /* permit comma separators */
3208 break;
3209 /* else fall through */
3210 default:
3211 error(ERR_NONFATAL,
3212 "non-string passed to `%%strcat' (%d)", t->type);
3213 free_tlist(tline);
3214 free_tlist(origline);
3215 return DIRECTIVE_FOUND;
3219 p = pp = nasm_malloc(len);
3220 t = tline;
3221 for (t = tline; t; t = t->next) {
3222 if (t->type == TOK_STRING) {
3223 memcpy(p, t->text, t->a.len);
3224 p += t->a.len;
3229 * We now have a macro name, an implicit parameter count of
3230 * zero, and a numeric token to use as an expansion. Create
3231 * and store an SMacro.
3233 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3234 macro_start->text = nasm_quote(pp, len);
3235 nasm_free(pp);
3236 define_smacro(ctx, mname, casesense, 0, macro_start);
3237 free_tlist(tline);
3238 free_tlist(origline);
3239 return DIRECTIVE_FOUND;
3241 case PP_SUBSTR:
3243 int64_t a1, a2;
3244 size_t len;
3246 casesense = true;
3248 tline = tline->next;
3249 skip_white_(tline);
3250 tline = expand_id(tline);
3251 if (!tline || (tline->type != TOK_ID &&
3252 (tline->type != TOK_PREPROC_ID ||
3253 tline->text[1] != '$'))) {
3254 error(ERR_NONFATAL,
3255 "`%%substr' expects a macro identifier as first parameter");
3256 free_tlist(origline);
3257 return DIRECTIVE_FOUND;
3259 ctx = get_ctx(tline->text, &mname, false);
3260 last = tline;
3261 tline = expand_smacro(tline->next);
3262 last->next = NULL;
3264 t = tline->next;
3265 while (tok_type_(t, TOK_WHITESPACE))
3266 t = t->next;
3268 /* t should now point to the string */
3269 if (t->type != TOK_STRING) {
3270 error(ERR_NONFATAL,
3271 "`%%substr` requires string as second parameter");
3272 free_tlist(tline);
3273 free_tlist(origline);
3274 return DIRECTIVE_FOUND;
3277 tt = t->next;
3278 tptr = &tt;
3279 tokval.t_type = TOKEN_INVALID;
3280 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3281 pass, error, NULL);
3282 if (!evalresult) {
3283 free_tlist(tline);
3284 free_tlist(origline);
3285 return DIRECTIVE_FOUND;
3286 } else if (!is_simple(evalresult)) {
3287 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3288 free_tlist(tline);
3289 free_tlist(origline);
3290 return DIRECTIVE_FOUND;
3292 a1 = evalresult->value-1;
3294 while (tok_type_(tt, TOK_WHITESPACE))
3295 tt = tt->next;
3296 if (!tt) {
3297 a2 = 1; /* Backwards compatibility: one character */
3298 } else {
3299 tokval.t_type = TOKEN_INVALID;
3300 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3301 pass, error, NULL);
3302 if (!evalresult) {
3303 free_tlist(tline);
3304 free_tlist(origline);
3305 return DIRECTIVE_FOUND;
3306 } else if (!is_simple(evalresult)) {
3307 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3308 free_tlist(tline);
3309 free_tlist(origline);
3310 return DIRECTIVE_FOUND;
3312 a2 = evalresult->value;
3315 len = nasm_unquote(t->text, NULL);
3316 if (a2 < 0)
3317 a2 = a2+1+len-a1;
3318 if (a1+a2 > (int64_t)len)
3319 a2 = len-a1;
3321 macro_start = nasm_malloc(sizeof(*macro_start));
3322 macro_start->next = NULL;
3323 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3324 macro_start->type = TOK_STRING;
3325 macro_start->a.mac = NULL;
3328 * We now have a macro name, an implicit parameter count of
3329 * zero, and a numeric token to use as an expansion. Create
3330 * and store an SMacro.
3332 define_smacro(ctx, mname, casesense, 0, macro_start);
3333 free_tlist(tline);
3334 free_tlist(origline);
3335 return DIRECTIVE_FOUND;
3338 case PP_ASSIGN:
3339 case PP_IASSIGN:
3340 casesense = (i == PP_ASSIGN);
3342 tline = tline->next;
3343 skip_white_(tline);
3344 tline = expand_id(tline);
3345 if (!tline || (tline->type != TOK_ID &&
3346 (tline->type != TOK_PREPROC_ID ||
3347 tline->text[1] != '$'))) {
3348 error(ERR_NONFATAL,
3349 "`%%%sassign' expects a macro identifier",
3350 (i == PP_IASSIGN ? "i" : ""));
3351 free_tlist(origline);
3352 return DIRECTIVE_FOUND;
3354 ctx = get_ctx(tline->text, &mname, false);
3355 last = tline;
3356 tline = expand_smacro(tline->next);
3357 last->next = NULL;
3359 t = tline;
3360 tptr = &t;
3361 tokval.t_type = TOKEN_INVALID;
3362 evalresult =
3363 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3364 free_tlist(tline);
3365 if (!evalresult) {
3366 free_tlist(origline);
3367 return DIRECTIVE_FOUND;
3370 if (tokval.t_type)
3371 error(ERR_WARNING|ERR_PASS1,
3372 "trailing garbage after expression ignored");
3374 if (!is_simple(evalresult)) {
3375 error(ERR_NONFATAL,
3376 "non-constant value given to `%%%sassign'",
3377 (i == PP_IASSIGN ? "i" : ""));
3378 free_tlist(origline);
3379 return DIRECTIVE_FOUND;
3382 macro_start = nasm_malloc(sizeof(*macro_start));
3383 macro_start->next = NULL;
3384 make_tok_num(macro_start, reloc_value(evalresult));
3385 macro_start->a.mac = NULL;
3388 * We now have a macro name, an implicit parameter count of
3389 * zero, and a numeric token to use as an expansion. Create
3390 * and store an SMacro.
3392 define_smacro(ctx, mname, casesense, 0, macro_start);
3393 free_tlist(origline);
3394 return DIRECTIVE_FOUND;
3396 case PP_LINE:
3398 * Syntax is `%line nnn[+mmm] [filename]'
3400 tline = tline->next;
3401 skip_white_(tline);
3402 if (!tok_type_(tline, TOK_NUMBER)) {
3403 error(ERR_NONFATAL, "`%%line' expects line number");
3404 free_tlist(origline);
3405 return DIRECTIVE_FOUND;
3407 k = readnum(tline->text, &err);
3408 m = 1;
3409 tline = tline->next;
3410 if (tok_is_(tline, "+")) {
3411 tline = tline->next;
3412 if (!tok_type_(tline, TOK_NUMBER)) {
3413 error(ERR_NONFATAL, "`%%line' expects line increment");
3414 free_tlist(origline);
3415 return DIRECTIVE_FOUND;
3417 m = readnum(tline->text, &err);
3418 tline = tline->next;
3420 skip_white_(tline);
3421 src_set_linnum(k);
3422 istk->lineinc = m;
3423 if (tline) {
3424 nasm_free(src_set_fname(detoken(tline, false)));
3426 free_tlist(origline);
3427 return DIRECTIVE_FOUND;
3429 default:
3430 error(ERR_FATAL,
3431 "preprocessor directive `%s' not yet implemented",
3432 pp_directives[i]);
3433 return DIRECTIVE_FOUND;
3438 * Ensure that a macro parameter contains a condition code and
3439 * nothing else. Return the condition code index if so, or -1
3440 * otherwise.
3442 static int find_cc(Token * t)
3444 Token *tt;
3445 int i, j, k, m;
3447 if (!t)
3448 return -1; /* Probably a %+ without a space */
3450 skip_white_(t);
3451 if (t->type != TOK_ID)
3452 return -1;
3453 tt = t->next;
3454 skip_white_(tt);
3455 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3456 return -1;
3458 i = -1;
3459 j = elements(conditions);
3460 while (j - i > 1) {
3461 k = (j + i) / 2;
3462 m = nasm_stricmp(t->text, conditions[k]);
3463 if (m == 0) {
3464 i = k;
3465 j = -2;
3466 break;
3467 } else if (m < 0) {
3468 j = k;
3469 } else
3470 i = k;
3472 if (j != -2)
3473 return -1;
3474 return i;
3477 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3479 Token **tail, *t, *tt;
3480 Token **paste_head;
3481 bool did_paste = false;
3482 char *tmp;
3484 /* Now handle token pasting... */
3485 paste_head = NULL;
3486 tail = head;
3487 while ((t = *tail) && (tt = t->next)) {
3488 switch (t->type) {
3489 case TOK_WHITESPACE:
3490 if (tt->type == TOK_WHITESPACE) {
3491 /* Zap adjacent whitespace tokens */
3492 t->next = delete_Token(tt);
3493 } else {
3494 /* Do not advance paste_head here */
3495 tail = &t->next;
3497 break;
3498 case TOK_ID:
3499 case TOK_PREPROC_ID:
3500 case TOK_NUMBER:
3501 case TOK_FLOAT:
3503 size_t len = 0;
3504 char *tmp, *p;
3506 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3507 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3508 tt->type == TOK_OTHER)) {
3509 len += strlen(tt->text);
3510 tt = tt->next;
3513 /* Now tt points to the first token after the potential
3514 paste area... */
3515 if (tt != t->next) {
3516 /* We have at least two tokens... */
3517 len += strlen(t->text);
3518 p = tmp = nasm_malloc(len+1);
3520 while (t != tt) {
3521 strcpy(p, t->text);
3522 p = strchr(p, '\0');
3523 t = delete_Token(t);
3526 t = *tail = tokenize(tmp);
3527 nasm_free(tmp);
3529 while (t->next) {
3530 tail = &t->next;
3531 t = t->next;
3533 t->next = tt; /* Attach the remaining token chain */
3535 did_paste = true;
3537 paste_head = tail;
3538 tail = &t->next;
3539 break;
3541 case TOK_PASTE: /* %+ */
3542 if (handle_paste_tokens) {
3543 /* Zap %+ and whitespace tokens to the right */
3544 while (t && (t->type == TOK_WHITESPACE ||
3545 t->type == TOK_PASTE))
3546 t = *tail = delete_Token(t);
3547 if (!paste_head || !t)
3548 break; /* Nothing to paste with */
3549 tail = paste_head;
3550 t = *tail;
3551 tt = t->next;
3552 while (tok_type_(tt, TOK_WHITESPACE))
3553 tt = t->next = delete_Token(tt);
3555 if (tt) {
3556 tmp = nasm_strcat(t->text, tt->text);
3557 delete_Token(t);
3558 tt = delete_Token(tt);
3559 t = *tail = tokenize(tmp);
3560 nasm_free(tmp);
3561 while (t->next) {
3562 tail = &t->next;
3563 t = t->next;
3565 t->next = tt; /* Attach the remaining token chain */
3566 did_paste = true;
3568 paste_head = tail;
3569 tail = &t->next;
3570 break;
3572 /* else fall through */
3573 default:
3574 tail = paste_head = &t->next;
3575 break;
3578 return did_paste;
3581 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3582 * %-n) and MMacro-local identifiers (%%foo) as well as
3583 * macro indirection (%[...]).
3585 static Token *expand_mmac_params(Token * tline)
3587 Token *t, *tt, **tail, *thead;
3588 bool changed = false;
3590 tail = &thead;
3591 thead = NULL;
3593 while (tline) {
3594 if (tline->type == TOK_PREPROC_ID &&
3595 (((tline->text[1] == '+' || tline->text[1] == '-')
3596 && tline->text[2]) || tline->text[1] == '%'
3597 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
3598 char *text = NULL;
3599 int type = 0, cc; /* type = 0 to placate optimisers */
3600 char tmpbuf[30];
3601 unsigned int n;
3602 int i;
3603 MMacro *mac;
3605 t = tline;
3606 tline = tline->next;
3608 mac = istk->mstk;
3609 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3610 mac = mac->next_active;
3611 if (!mac)
3612 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3613 else
3614 switch (t->text[1]) {
3616 * We have to make a substitution of one of the
3617 * forms %1, %-1, %+1, %%foo, %0.
3619 case '0':
3620 type = TOK_NUMBER;
3621 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3622 text = nasm_strdup(tmpbuf);
3623 break;
3624 case '%':
3625 type = TOK_ID;
3626 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3627 mac->unique);
3628 text = nasm_strcat(tmpbuf, t->text + 2);
3629 break;
3630 case '-':
3631 n = atoi(t->text + 2) - 1;
3632 if (n >= mac->nparam)
3633 tt = NULL;
3634 else {
3635 if (mac->nparam > 1)
3636 n = (n + mac->rotate) % mac->nparam;
3637 tt = mac->params[n];
3639 cc = find_cc(tt);
3640 if (cc == -1) {
3641 error(ERR_NONFATAL,
3642 "macro parameter %d is not a condition code",
3643 n + 1);
3644 text = NULL;
3645 } else {
3646 type = TOK_ID;
3647 if (inverse_ccs[cc] == -1) {
3648 error(ERR_NONFATAL,
3649 "condition code `%s' is not invertible",
3650 conditions[cc]);
3651 text = NULL;
3652 } else
3653 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3655 break;
3656 case '+':
3657 n = atoi(t->text + 2) - 1;
3658 if (n >= mac->nparam)
3659 tt = NULL;
3660 else {
3661 if (mac->nparam > 1)
3662 n = (n + mac->rotate) % mac->nparam;
3663 tt = mac->params[n];
3665 cc = find_cc(tt);
3666 if (cc == -1) {
3667 error(ERR_NONFATAL,
3668 "macro parameter %d is not a condition code",
3669 n + 1);
3670 text = NULL;
3671 } else {
3672 type = TOK_ID;
3673 text = nasm_strdup(conditions[cc]);
3675 break;
3676 default:
3677 n = atoi(t->text + 1) - 1;
3678 if (n >= mac->nparam)
3679 tt = NULL;
3680 else {
3681 if (mac->nparam > 1)
3682 n = (n + mac->rotate) % mac->nparam;
3683 tt = mac->params[n];
3685 if (tt) {
3686 for (i = 0; i < mac->paramlen[n]; i++) {
3687 *tail = new_Token(NULL, tt->type, tt->text, 0);
3688 tail = &(*tail)->next;
3689 tt = tt->next;
3692 text = NULL; /* we've done it here */
3693 break;
3695 if (!text) {
3696 delete_Token(t);
3697 } else {
3698 *tail = t;
3699 tail = &t->next;
3700 t->type = type;
3701 nasm_free(t->text);
3702 t->text = text;
3703 t->a.mac = NULL;
3705 changed = true;
3706 continue;
3707 } else if (tline->type == TOK_INDIRECT) {
3708 t = tline;
3709 tline = tline->next;
3710 tt = tokenize(t->text);
3711 tt = expand_mmac_params(tt);
3712 tt = expand_smacro(tt);
3713 *tail = tt;
3714 while (tt) {
3715 tt->a.mac = NULL; /* Necessary? */
3716 tail = &tt->next;
3717 tt = tt->next;
3719 delete_Token(t);
3720 changed = true;
3721 } else {
3722 t = *tail = tline;
3723 tline = tline->next;
3724 t->a.mac = NULL;
3725 tail = &t->next;
3728 *tail = NULL;
3730 if (changed)
3731 paste_tokens(&thead, false);
3733 return thead;
3737 * Expand all single-line macro calls made in the given line.
3738 * Return the expanded version of the line. The original is deemed
3739 * to be destroyed in the process. (In reality we'll just move
3740 * Tokens from input to output a lot of the time, rather than
3741 * actually bothering to destroy and replicate.)
3744 static Token *expand_smacro(Token * tline)
3746 Token *t, *tt, *mstart, **tail, *thead;
3747 struct hash_table *smtbl;
3748 SMacro *head = NULL, *m;
3749 Token **params;
3750 int *paramsize;
3751 unsigned int nparam, sparam;
3752 int brackets;
3753 Token *org_tline = tline;
3754 Context *ctx;
3755 const char *mname;
3756 int deadman = DEADMAN_LIMIT;
3757 bool expanded;
3760 * Trick: we should avoid changing the start token pointer since it can
3761 * be contained in "next" field of other token. Because of this
3762 * we allocate a copy of first token and work with it; at the end of
3763 * routine we copy it back
3765 if (org_tline) {
3766 tline =
3767 new_Token(org_tline->next, org_tline->type, org_tline->text,
3769 tline->a.mac = org_tline->a.mac;
3770 nasm_free(org_tline->text);
3771 org_tline->text = NULL;
3774 expanded = true; /* Always expand %+ at least once */
3776 again:
3777 tail = &thead;
3778 thead = NULL;
3780 while (tline) { /* main token loop */
3781 if (!--deadman) {
3782 error(ERR_NONFATAL, "interminable macro recursion");
3783 break;
3786 if ((mname = tline->text)) {
3787 /* if this token is a local macro, look in local context */
3788 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3789 ctx = get_ctx(mname, &mname, true);
3790 else
3791 ctx = NULL;
3792 smtbl = ctx ? &ctx->localmac : &smacros;
3793 head = (SMacro *) hash_findix(smtbl, mname);
3796 * We've hit an identifier. As in is_mmacro below, we first
3797 * check whether the identifier is a single-line macro at
3798 * all, then think about checking for parameters if
3799 * necessary.
3801 for (m = head; m; m = m->next)
3802 if (!mstrcmp(m->name, mname, m->casesense))
3803 break;
3804 if (m) {
3805 mstart = tline;
3806 params = NULL;
3807 paramsize = NULL;
3808 if (m->nparam == 0) {
3810 * Simple case: the macro is parameterless. Discard the
3811 * one token that the macro call took, and push the
3812 * expansion back on the to-do stack.
3814 if (!m->expansion) {
3815 if (!strcmp("__FILE__", m->name)) {
3816 int32_t num = 0;
3817 char *file = NULL;
3818 src_get(&num, &file);
3819 tline->text = nasm_quote(file, strlen(file));
3820 tline->type = TOK_STRING;
3821 nasm_free(file);
3822 continue;
3824 if (!strcmp("__LINE__", m->name)) {
3825 nasm_free(tline->text);
3826 make_tok_num(tline, src_get_linnum());
3827 continue;
3829 if (!strcmp("__BITS__", m->name)) {
3830 nasm_free(tline->text);
3831 make_tok_num(tline, globalbits);
3832 continue;
3834 tline = delete_Token(tline);
3835 continue;
3837 } else {
3839 * Complicated case: at least one macro with this name
3840 * exists and takes parameters. We must find the
3841 * parameters in the call, count them, find the SMacro
3842 * that corresponds to that form of the macro call, and
3843 * substitute for the parameters when we expand. What a
3844 * pain.
3846 /*tline = tline->next;
3847 skip_white_(tline); */
3848 do {
3849 t = tline->next;
3850 while (tok_type_(t, TOK_SMAC_END)) {
3851 t->a.mac->in_progress = false;
3852 t->text = NULL;
3853 t = tline->next = delete_Token(t);
3855 tline = t;
3856 } while (tok_type_(tline, TOK_WHITESPACE));
3857 if (!tok_is_(tline, "(")) {
3859 * This macro wasn't called with parameters: ignore
3860 * the call. (Behaviour borrowed from gnu cpp.)
3862 tline = mstart;
3863 m = NULL;
3864 } else {
3865 int paren = 0;
3866 int white = 0;
3867 brackets = 0;
3868 nparam = 0;
3869 sparam = PARAM_DELTA;
3870 params = nasm_malloc(sparam * sizeof(Token *));
3871 params[0] = tline->next;
3872 paramsize = nasm_malloc(sparam * sizeof(int));
3873 paramsize[0] = 0;
3874 while (true) { /* parameter loop */
3876 * For some unusual expansions
3877 * which concatenates function call
3879 t = tline->next;
3880 while (tok_type_(t, TOK_SMAC_END)) {
3881 t->a.mac->in_progress = false;
3882 t->text = NULL;
3883 t = tline->next = delete_Token(t);
3885 tline = t;
3887 if (!tline) {
3888 error(ERR_NONFATAL,
3889 "macro call expects terminating `)'");
3890 break;
3892 if (tline->type == TOK_WHITESPACE
3893 && brackets <= 0) {
3894 if (paramsize[nparam])
3895 white++;
3896 else
3897 params[nparam] = tline->next;
3898 continue; /* parameter loop */
3900 if (tline->type == TOK_OTHER
3901 && tline->text[1] == 0) {
3902 char ch = tline->text[0];
3903 if (ch == ',' && !paren && brackets <= 0) {
3904 if (++nparam >= sparam) {
3905 sparam += PARAM_DELTA;
3906 params = nasm_realloc(params,
3907 sparam *
3908 sizeof(Token
3909 *));
3910 paramsize =
3911 nasm_realloc(paramsize,
3912 sparam *
3913 sizeof(int));
3915 params[nparam] = tline->next;
3916 paramsize[nparam] = 0;
3917 white = 0;
3918 continue; /* parameter loop */
3920 if (ch == '{' &&
3921 (brackets > 0 || (brackets == 0 &&
3922 !paramsize[nparam])))
3924 if (!(brackets++)) {
3925 params[nparam] = tline->next;
3926 continue; /* parameter loop */
3929 if (ch == '}' && brackets > 0)
3930 if (--brackets == 0) {
3931 brackets = -1;
3932 continue; /* parameter loop */
3934 if (ch == '(' && !brackets)
3935 paren++;
3936 if (ch == ')' && brackets <= 0)
3937 if (--paren < 0)
3938 break;
3940 if (brackets < 0) {
3941 brackets = 0;
3942 error(ERR_NONFATAL, "braces do not "
3943 "enclose all of macro parameter");
3945 paramsize[nparam] += white + 1;
3946 white = 0;
3947 } /* parameter loop */
3948 nparam++;
3949 while (m && (m->nparam != nparam ||
3950 mstrcmp(m->name, mname,
3951 m->casesense)))
3952 m = m->next;
3953 if (!m)
3954 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
3955 "macro `%s' exists, "
3956 "but not taking %d parameters",
3957 mstart->text, nparam);
3960 if (m && m->in_progress)
3961 m = NULL;
3962 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3964 * Design question: should we handle !tline, which
3965 * indicates missing ')' here, or expand those
3966 * macros anyway, which requires the (t) test a few
3967 * lines down?
3969 nasm_free(params);
3970 nasm_free(paramsize);
3971 tline = mstart;
3972 } else {
3974 * Expand the macro: we are placed on the last token of the
3975 * call, so that we can easily split the call from the
3976 * following tokens. We also start by pushing an SMAC_END
3977 * token for the cycle removal.
3979 t = tline;
3980 if (t) {
3981 tline = t->next;
3982 t->next = NULL;
3984 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3985 tt->a.mac = m;
3986 m->in_progress = true;
3987 tline = tt;
3988 for (t = m->expansion; t; t = t->next) {
3989 if (t->type >= TOK_SMAC_PARAM) {
3990 Token *pcopy = tline, **ptail = &pcopy;
3991 Token *ttt, *pt;
3992 int i;
3994 ttt = params[t->type - TOK_SMAC_PARAM];
3995 for (i = paramsize[t->type - TOK_SMAC_PARAM];
3996 --i >= 0;) {
3997 pt = *ptail =
3998 new_Token(tline, ttt->type, ttt->text,
4000 ptail = &pt->next;
4001 ttt = ttt->next;
4003 tline = pcopy;
4004 } else if (t->type == TOK_PREPROC_Q) {
4005 tt = new_Token(tline, TOK_ID, mname, 0);
4006 tline = tt;
4007 } else if (t->type == TOK_PREPROC_QQ) {
4008 tt = new_Token(tline, TOK_ID, m->name, 0);
4009 tline = tt;
4010 } else {
4011 tt = new_Token(tline, t->type, t->text, 0);
4012 tline = tt;
4017 * Having done that, get rid of the macro call, and clean
4018 * up the parameters.
4020 nasm_free(params);
4021 nasm_free(paramsize);
4022 free_tlist(mstart);
4023 expanded = true;
4024 continue; /* main token loop */
4029 if (tline->type == TOK_SMAC_END) {
4030 tline->a.mac->in_progress = false;
4031 tline = delete_Token(tline);
4032 } else {
4033 t = *tail = tline;
4034 tline = tline->next;
4035 t->a.mac = NULL;
4036 t->next = NULL;
4037 tail = &t->next;
4042 * Now scan the entire line and look for successive TOK_IDs that resulted
4043 * after expansion (they can't be produced by tokenize()). The successive
4044 * TOK_IDs should be concatenated.
4045 * Also we look for %+ tokens and concatenate the tokens before and after
4046 * them (without white spaces in between).
4048 if (expanded && paste_tokens(&thead, true)) {
4050 * If we concatenated something, *and* we had previously expanded
4051 * an actual macro, scan the lines again for macros...
4053 tline = thead;
4054 expanded = false;
4055 goto again;
4058 if (org_tline) {
4059 if (thead) {
4060 *org_tline = *thead;
4061 /* since we just gave text to org_line, don't free it */
4062 thead->text = NULL;
4063 delete_Token(thead);
4064 } else {
4065 /* the expression expanded to empty line;
4066 we can't return NULL for some reasons
4067 we just set the line to a single WHITESPACE token. */
4068 memset(org_tline, 0, sizeof(*org_tline));
4069 org_tline->text = NULL;
4070 org_tline->type = TOK_WHITESPACE;
4072 thead = org_tline;
4075 return thead;
4079 * Similar to expand_smacro but used exclusively with macro identifiers
4080 * right before they are fetched in. The reason is that there can be
4081 * identifiers consisting of several subparts. We consider that if there
4082 * are more than one element forming the name, user wants a expansion,
4083 * otherwise it will be left as-is. Example:
4085 * %define %$abc cde
4087 * the identifier %$abc will be left as-is so that the handler for %define
4088 * will suck it and define the corresponding value. Other case:
4090 * %define _%$abc cde
4092 * In this case user wants name to be expanded *before* %define starts
4093 * working, so we'll expand %$abc into something (if it has a value;
4094 * otherwise it will be left as-is) then concatenate all successive
4095 * PP_IDs into one.
4097 static Token *expand_id(Token * tline)
4099 Token *cur, *oldnext = NULL;
4101 if (!tline || !tline->next)
4102 return tline;
4104 cur = tline;
4105 while (cur->next &&
4106 (cur->next->type == TOK_ID ||
4107 cur->next->type == TOK_PREPROC_ID
4108 || cur->next->type == TOK_NUMBER))
4109 cur = cur->next;
4111 /* If identifier consists of just one token, don't expand */
4112 if (cur == tline)
4113 return tline;
4115 if (cur) {
4116 oldnext = cur->next; /* Detach the tail past identifier */
4117 cur->next = NULL; /* so that expand_smacro stops here */
4120 tline = expand_smacro(tline);
4122 if (cur) {
4123 /* expand_smacro possibly changhed tline; re-scan for EOL */
4124 cur = tline;
4125 while (cur && cur->next)
4126 cur = cur->next;
4127 if (cur)
4128 cur->next = oldnext;
4131 return tline;
4135 * Determine whether the given line constitutes a multi-line macro
4136 * call, and return the MMacro structure called if so. Doesn't have
4137 * to check for an initial label - that's taken care of in
4138 * expand_mmacro - but must check numbers of parameters. Guaranteed
4139 * to be called with tline->type == TOK_ID, so the putative macro
4140 * name is easy to find.
4142 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4144 MMacro *head, *m;
4145 Token **params;
4146 int nparam;
4148 head = (MMacro *) hash_findix(&mmacros, tline->text);
4151 * Efficiency: first we see if any macro exists with the given
4152 * name. If not, we can return NULL immediately. _Then_ we
4153 * count the parameters, and then we look further along the
4154 * list if necessary to find the proper MMacro.
4156 for (m = head; m; m = m->next)
4157 if (!mstrcmp(m->name, tline->text, m->casesense))
4158 break;
4159 if (!m)
4160 return NULL;
4163 * OK, we have a potential macro. Count and demarcate the
4164 * parameters.
4166 count_mmac_params(tline->next, &nparam, &params);
4169 * So we know how many parameters we've got. Find the MMacro
4170 * structure that handles this number.
4172 while (m) {
4173 if (m->nparam_min <= nparam
4174 && (m->plus || nparam <= m->nparam_max)) {
4176 * This one is right. Just check if cycle removal
4177 * prohibits us using it before we actually celebrate...
4179 if (m->in_progress > m->max_depth) {
4180 if (m->max_depth > 0) {
4181 error(ERR_WARNING,
4182 "reached maximum recursion depth of %i",
4183 m->max_depth);
4185 nasm_free(params);
4186 return NULL;
4189 * It's right, and we can use it. Add its default
4190 * parameters to the end of our list if necessary.
4192 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4193 params =
4194 nasm_realloc(params,
4195 ((m->nparam_min + m->ndefs +
4196 1) * sizeof(*params)));
4197 while (nparam < m->nparam_min + m->ndefs) {
4198 params[nparam] = m->defaults[nparam - m->nparam_min];
4199 nparam++;
4203 * If we've gone over the maximum parameter count (and
4204 * we're in Plus mode), ignore parameters beyond
4205 * nparam_max.
4207 if (m->plus && nparam > m->nparam_max)
4208 nparam = m->nparam_max;
4210 * Then terminate the parameter list, and leave.
4212 if (!params) { /* need this special case */
4213 params = nasm_malloc(sizeof(*params));
4214 nparam = 0;
4216 params[nparam] = NULL;
4217 *params_array = params;
4218 return m;
4221 * This one wasn't right: look for the next one with the
4222 * same name.
4224 for (m = m->next; m; m = m->next)
4225 if (!mstrcmp(m->name, tline->text, m->casesense))
4226 break;
4230 * After all that, we didn't find one with the right number of
4231 * parameters. Issue a warning, and fail to expand the macro.
4233 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4234 "macro `%s' exists, but not taking %d parameters",
4235 tline->text, nparam);
4236 nasm_free(params);
4237 return NULL;
4242 * Save MMacro invocation specific fields in
4243 * preparation for a recursive macro expansion
4245 static void push_mmacro(MMacro *m)
4247 MMacroInvocation *i;
4249 i = nasm_malloc(sizeof(MMacroInvocation));
4250 i->prev = m->prev;
4251 i->params = m->params;
4252 i->iline = m->iline;
4253 i->nparam = m->nparam;
4254 i->rotate = m->rotate;
4255 i->paramlen = m->paramlen;
4256 i->unique = m->unique;
4257 m->prev = i;
4262 * Restore MMacro invocation specific fields that were
4263 * saved during a previous recursive macro expansion
4265 static void pop_mmacro(MMacro *m)
4267 MMacroInvocation *i;
4269 if(m->prev != NULL){
4270 i = m->prev;
4271 m->prev = i->prev;
4272 m->params = i->params;
4273 m->iline = i->iline;
4274 m->nparam = i->nparam;
4275 m->rotate = i->rotate;
4276 m->paramlen = i->paramlen;
4277 m->unique = i->unique;
4278 nasm_free(i);
4284 * Expand the multi-line macro call made by the given line, if
4285 * there is one to be expanded. If there is, push the expansion on
4286 * istk->expansion and return 1. Otherwise return 0.
4288 static int expand_mmacro(Token * tline)
4290 Token *startline = tline;
4291 Token *label = NULL;
4292 int dont_prepend = 0;
4293 Token **params, *t, *mtok, *tt;
4294 MMacro *m;
4295 Line *l, *ll;
4296 int i, nparam, *paramlen;
4297 const char *mname;
4299 t = tline;
4300 skip_white_(t);
4301 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4302 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4303 return 0;
4304 mtok = t;
4305 m = is_mmacro(t, &params);
4306 if (m) {
4307 mname = t->text;
4308 } else {
4309 Token *last;
4311 * We have an id which isn't a macro call. We'll assume
4312 * it might be a label; we'll also check to see if a
4313 * colon follows it. Then, if there's another id after
4314 * that lot, we'll check it again for macro-hood.
4316 label = last = t;
4317 t = t->next;
4318 if (tok_type_(t, TOK_WHITESPACE))
4319 last = t, t = t->next;
4320 if (tok_is_(t, ":")) {
4321 dont_prepend = 1;
4322 last = t, t = t->next;
4323 if (tok_type_(t, TOK_WHITESPACE))
4324 last = t, t = t->next;
4326 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
4327 return 0;
4328 last->next = NULL;
4329 mname = t->text;
4330 tline = t;
4334 * Fix up the parameters: this involves stripping leading and
4335 * trailing whitespace, then stripping braces if they are
4336 * present.
4338 for (nparam = 0; params[nparam]; nparam++) ;
4339 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4341 for (i = 0; params[i]; i++) {
4342 int brace = false;
4343 int comma = (!m->plus || i < nparam - 1);
4345 t = params[i];
4346 skip_white_(t);
4347 if (tok_is_(t, "{"))
4348 t = t->next, brace = true, comma = false;
4349 params[i] = t;
4350 paramlen[i] = 0;
4351 while (t) {
4352 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4353 break; /* ... because we have hit a comma */
4354 if (comma && t->type == TOK_WHITESPACE
4355 && tok_is_(t->next, ","))
4356 break; /* ... or a space then a comma */
4357 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4358 break; /* ... or a brace */
4359 t = t->next;
4360 paramlen[i]++;
4365 * OK, we have a MMacro structure together with a set of
4366 * parameters. We must now go through the expansion and push
4367 * copies of each Line on to istk->expansion. Substitution of
4368 * parameter tokens and macro-local tokens doesn't get done
4369 * until the single-line macro substitution process; this is
4370 * because delaying them allows us to change the semantics
4371 * later through %rotate.
4373 * First, push an end marker on to istk->expansion, mark this
4374 * macro as in progress, and set up its invocation-specific
4375 * variables.
4377 ll = nasm_malloc(sizeof(Line));
4378 ll->next = istk->expansion;
4379 ll->finishes = m;
4380 ll->first = NULL;
4381 istk->expansion = ll;
4384 * Save the previous MMacro expansion in the case of
4385 * macro recursion
4387 if (m->max_depth && m->in_progress)
4388 push_mmacro(m);
4390 m->in_progress ++;
4391 m->params = params;
4392 m->iline = tline;
4393 m->nparam = nparam;
4394 m->rotate = 0;
4395 m->paramlen = paramlen;
4396 m->unique = unique++;
4397 m->lineno = 0;
4399 m->next_active = istk->mstk;
4400 istk->mstk = m;
4402 for (l = m->expansion; l; l = l->next) {
4403 Token **tail;
4405 ll = nasm_malloc(sizeof(Line));
4406 ll->finishes = NULL;
4407 ll->next = istk->expansion;
4408 istk->expansion = ll;
4409 tail = &ll->first;
4411 for (t = l->first; t; t = t->next) {
4412 Token *x = t;
4413 switch (t->type) {
4414 case TOK_PREPROC_Q:
4415 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4416 break;
4417 case TOK_PREPROC_QQ:
4418 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4419 break;
4420 case TOK_PREPROC_ID:
4421 if (t->text[1] == '0' && t->text[2] == '0') {
4422 dont_prepend = -1;
4423 x = label;
4424 if (!x)
4425 continue;
4427 /* fall through */
4428 default:
4429 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4430 break;
4432 tail = &tt->next;
4434 *tail = NULL;
4438 * If we had a label, push it on as the first line of
4439 * the macro expansion.
4441 if (label) {
4442 if (dont_prepend < 0)
4443 free_tlist(startline);
4444 else {
4445 ll = nasm_malloc(sizeof(Line));
4446 ll->finishes = NULL;
4447 ll->next = istk->expansion;
4448 istk->expansion = ll;
4449 ll->first = startline;
4450 if (!dont_prepend) {
4451 while (label->next)
4452 label = label->next;
4453 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4458 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4460 return 1;
4463 /* The function that actually does the error reporting */
4464 static void verror(int severity, const char *fmt, va_list arg)
4466 char buff[1024];
4468 vsnprintf(buff, sizeof(buff), fmt, arg);
4470 if (istk && istk->mstk && istk->mstk->name)
4471 _error(severity, "(%s:%d) %s", istk->mstk->name,
4472 istk->mstk->lineno, buff);
4473 else
4474 _error(severity, "%s", buff);
4478 * Since preprocessor always operate only on the line that didn't
4479 * arrived yet, we should always use ERR_OFFBY1.
4481 static void error(int severity, const char *fmt, ...)
4483 va_list arg;
4485 /* If we're in a dead branch of IF or something like it, ignore the error */
4486 if (istk && istk->conds && !emitting(istk->conds->state))
4487 return;
4489 va_start(arg, fmt);
4490 verror(severity, fmt, arg);
4491 va_end(arg);
4495 * Because %else etc are evaluated in the state context
4496 * of the previous branch, errors might get lost with error():
4497 * %if 0 ... %else trailing garbage ... %endif
4498 * So %else etc should report errors with this function.
4500 static void error_precond(int severity, const char *fmt, ...)
4502 va_list arg;
4504 /* Only ignore the error if it's really in a dead branch */
4505 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4506 return;
4508 va_start(arg, fmt);
4509 verror(severity, fmt, arg);
4510 va_end(arg);
4513 static void
4514 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
4515 ListGen * listgen, StrList **deplist)
4517 Token *t;
4519 _error = errfunc;
4520 cstk = NULL;
4521 istk = nasm_malloc(sizeof(Include));
4522 istk->next = NULL;
4523 istk->conds = NULL;
4524 istk->expansion = NULL;
4525 istk->mstk = NULL;
4526 istk->fp = fopen(file, "r");
4527 istk->fname = NULL;
4528 src_set_fname(nasm_strdup(file));
4529 src_set_linnum(0);
4530 istk->lineinc = 1;
4531 if (!istk->fp)
4532 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4533 file);
4534 defining = NULL;
4535 nested_mac_count = 0;
4536 nested_rep_count = 0;
4537 init_macros();
4538 unique = 0;
4539 if (tasm_compatible_mode) {
4540 stdmacpos = nasm_stdmac;
4541 } else {
4542 stdmacpos = nasm_stdmac_after_tasm;
4544 any_extrastdmac = extrastdmac && *extrastdmac;
4545 do_predef = true;
4546 list = listgen;
4547 evaluate = eval;
4550 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4551 * The caller, however, will also pass in 3 for preprocess-only so
4552 * we can set __PASS__ accordingly.
4554 pass = apass > 2 ? 2 : apass;
4556 dephead = deptail = deplist;
4557 if (deplist) {
4558 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4559 sl->next = NULL;
4560 strcpy(sl->str, file);
4561 *deptail = sl;
4562 deptail = &sl->next;
4566 * Define the __PASS__ macro. This is defined here unlike
4567 * all the other builtins, because it is special -- it varies between
4568 * passes.
4570 t = nasm_malloc(sizeof(*t));
4571 t->next = NULL;
4572 make_tok_num(t, apass);
4573 t->a.mac = NULL;
4574 define_smacro(NULL, "__PASS__", true, 0, t);
4577 static char *pp_getline(void)
4579 char *line;
4580 Token *tline;
4582 while (1) {
4584 * Fetch a tokenized line, either from the macro-expansion
4585 * buffer or from the input file.
4587 tline = NULL;
4588 while (istk->expansion && istk->expansion->finishes) {
4589 Line *l = istk->expansion;
4590 if (!l->finishes->name && l->finishes->in_progress > 1) {
4591 Line *ll;
4594 * This is a macro-end marker for a macro with no
4595 * name, which means it's not really a macro at all
4596 * but a %rep block, and the `in_progress' field is
4597 * more than 1, meaning that we still need to
4598 * repeat. (1 means the natural last repetition; 0
4599 * means termination by %exitrep.) We have
4600 * therefore expanded up to the %endrep, and must
4601 * push the whole block on to the expansion buffer
4602 * again. We don't bother to remove the macro-end
4603 * marker: we'd only have to generate another one
4604 * if we did.
4606 l->finishes->in_progress--;
4607 for (l = l->finishes->expansion; l; l = l->next) {
4608 Token *t, *tt, **tail;
4610 ll = nasm_malloc(sizeof(Line));
4611 ll->next = istk->expansion;
4612 ll->finishes = NULL;
4613 ll->first = NULL;
4614 tail = &ll->first;
4616 for (t = l->first; t; t = t->next) {
4617 if (t->text || t->type == TOK_WHITESPACE) {
4618 tt = *tail =
4619 new_Token(NULL, t->type, t->text, 0);
4620 tail = &tt->next;
4624 istk->expansion = ll;
4626 } else {
4628 * Check whether a `%rep' was started and not ended
4629 * within this macro expansion. This can happen and
4630 * should be detected. It's a fatal error because
4631 * I'm too confused to work out how to recover
4632 * sensibly from it.
4634 if (defining) {
4635 if (defining->name)
4636 error(ERR_PANIC,
4637 "defining with name in expansion");
4638 else if (istk->mstk->name)
4639 error(ERR_FATAL,
4640 "`%%rep' without `%%endrep' within"
4641 " expansion of macro `%s'",
4642 istk->mstk->name);
4646 * FIXME: investigate the relationship at this point between
4647 * istk->mstk and l->finishes
4650 MMacro *m = istk->mstk;
4651 istk->mstk = m->next_active;
4652 if (m->name) {
4654 * This was a real macro call, not a %rep, and
4655 * therefore the parameter information needs to
4656 * be freed.
4658 if (m->prev != NULL) {
4659 pop_mmacro(m);
4660 l->finishes->in_progress --;
4661 } else {
4662 nasm_free(m->params);
4663 free_tlist(m->iline);
4664 nasm_free(m->paramlen);
4665 l->finishes->in_progress = 0;
4667 } else
4668 free_mmacro(m);
4670 istk->expansion = l->next;
4671 nasm_free(l);
4672 list->downlevel(LIST_MACRO);
4675 while (1) { /* until we get a line we can use */
4677 if (istk->expansion) { /* from a macro expansion */
4678 char *p;
4679 Line *l = istk->expansion;
4680 if (istk->mstk)
4681 istk->mstk->lineno++;
4682 tline = l->first;
4683 istk->expansion = l->next;
4684 nasm_free(l);
4685 p = detoken(tline, false);
4686 list->line(LIST_MACRO, p);
4687 nasm_free(p);
4688 break;
4690 line = read_line();
4691 if (line) { /* from the current input file */
4692 line = prepreproc(line);
4693 tline = tokenize(line);
4694 nasm_free(line);
4695 break;
4698 * The current file has ended; work down the istk
4701 Include *i = istk;
4702 fclose(i->fp);
4703 if (i->conds)
4704 error(ERR_FATAL,
4705 "expected `%%endif' before end of file");
4706 /* only set line and file name if there's a next node */
4707 if (i->next) {
4708 src_set_linnum(i->lineno);
4709 nasm_free(src_set_fname(i->fname));
4711 istk = i->next;
4712 list->downlevel(LIST_INCLUDE);
4713 nasm_free(i);
4714 if (!istk)
4715 return NULL;
4716 if (istk->expansion && istk->expansion->finishes)
4717 break;
4722 * We must expand MMacro parameters and MMacro-local labels
4723 * _before_ we plunge into directive processing, to cope
4724 * with things like `%define something %1' such as STRUC
4725 * uses. Unless we're _defining_ a MMacro, in which case
4726 * those tokens should be left alone to go into the
4727 * definition; and unless we're in a non-emitting
4728 * condition, in which case we don't want to meddle with
4729 * anything.
4731 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4732 && !(istk->mstk && !istk->mstk->in_progress)) {
4733 tline = expand_mmac_params(tline);
4737 * Check the line to see if it's a preprocessor directive.
4739 if (do_directive(tline) == DIRECTIVE_FOUND) {
4740 continue;
4741 } else if (defining) {
4743 * We're defining a multi-line macro. We emit nothing
4744 * at all, and just
4745 * shove the tokenized line on to the macro definition.
4747 Line *l = nasm_malloc(sizeof(Line));
4748 l->next = defining->expansion;
4749 l->first = tline;
4750 l->finishes = NULL;
4751 defining->expansion = l;
4752 continue;
4753 } else if (istk->conds && !emitting(istk->conds->state)) {
4755 * We're in a non-emitting branch of a condition block.
4756 * Emit nothing at all, not even a blank line: when we
4757 * emerge from the condition we'll give a line-number
4758 * directive so we keep our place correctly.
4760 free_tlist(tline);
4761 continue;
4762 } else if (istk->mstk && !istk->mstk->in_progress) {
4764 * We're in a %rep block which has been terminated, so
4765 * we're walking through to the %endrep without
4766 * emitting anything. Emit nothing at all, not even a
4767 * blank line: when we emerge from the %rep block we'll
4768 * give a line-number directive so we keep our place
4769 * correctly.
4771 free_tlist(tline);
4772 continue;
4773 } else {
4774 tline = expand_smacro(tline);
4775 if (!expand_mmacro(tline)) {
4777 * De-tokenize the line again, and emit it.
4779 line = detoken(tline, true);
4780 free_tlist(tline);
4781 break;
4782 } else {
4783 continue; /* expand_mmacro calls free_tlist */
4788 return line;
4791 static void pp_cleanup(int pass)
4793 if (defining) {
4794 if(defining->name) {
4795 error(ERR_NONFATAL,
4796 "end of file while still defining macro `%s'",
4797 defining->name);
4798 } else {
4799 error(ERR_NONFATAL, "end of file while still in %%rep");
4802 free_mmacro(defining);
4804 while (cstk)
4805 ctx_pop();
4806 free_macros();
4807 while (istk) {
4808 Include *i = istk;
4809 istk = istk->next;
4810 fclose(i->fp);
4811 nasm_free(i->fname);
4812 nasm_free(i);
4814 while (cstk)
4815 ctx_pop();
4816 nasm_free(src_set_fname(NULL));
4817 if (pass == 0) {
4818 IncPath *i;
4819 free_llist(predef);
4820 delete_Blocks();
4821 while ((i = ipath)) {
4822 ipath = i->next;
4823 if (i->path)
4824 nasm_free(i->path);
4825 nasm_free(i);
4830 void pp_include_path(char *path)
4832 IncPath *i;
4834 i = nasm_malloc(sizeof(IncPath));
4835 i->path = path ? nasm_strdup(path) : NULL;
4836 i->next = NULL;
4838 if (ipath != NULL) {
4839 IncPath *j = ipath;
4840 while (j->next != NULL)
4841 j = j->next;
4842 j->next = i;
4843 } else {
4844 ipath = i;
4848 void pp_pre_include(char *fname)
4850 Token *inc, *space, *name;
4851 Line *l;
4853 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4854 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4855 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4857 l = nasm_malloc(sizeof(Line));
4858 l->next = predef;
4859 l->first = inc;
4860 l->finishes = NULL;
4861 predef = l;
4864 void pp_pre_define(char *definition)
4866 Token *def, *space;
4867 Line *l;
4868 char *equals;
4870 equals = strchr(definition, '=');
4871 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4872 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4873 if (equals)
4874 *equals = ' ';
4875 space->next = tokenize(definition);
4876 if (equals)
4877 *equals = '=';
4879 l = nasm_malloc(sizeof(Line));
4880 l->next = predef;
4881 l->first = def;
4882 l->finishes = NULL;
4883 predef = l;
4886 void pp_pre_undefine(char *definition)
4888 Token *def, *space;
4889 Line *l;
4891 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4892 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4893 space->next = tokenize(definition);
4895 l = nasm_malloc(sizeof(Line));
4896 l->next = predef;
4897 l->first = def;
4898 l->finishes = NULL;
4899 predef = l;
4903 * Added by Keith Kanios:
4905 * This function is used to assist with "runtime" preprocessor
4906 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4908 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4909 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4912 void pp_runtime(char *definition)
4914 Token *def;
4916 def = tokenize(definition);
4917 if(do_directive(def) == NO_DIRECTIVE_FOUND)
4918 free_tlist(def);
4922 void pp_extra_stdmac(macros_t *macros)
4924 extrastdmac = macros;
4927 static void make_tok_num(Token * tok, int64_t val)
4929 char numbuf[20];
4930 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4931 tok->text = nasm_strdup(numbuf);
4932 tok->type = TOK_NUMBER;
4935 Preproc nasmpp = {
4936 pp_reset,
4937 pp_getline,
4938 pp_cleanup