preproc: refine appropriate handling of PP_RMACRO/PP_RIMACRO/PP_MACRO/PP_IMACRO
[nasm.git] / preproc.c
blob9fcebfa48d75a9db7fba6f84610e721d90e1ab3f
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 int64_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 * Condition codes. Note that we use c_ prefix not C_ because C_ is
322 * used in nasm.h for the "real" condition codes. At _this_ level,
323 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
324 * ones, so we need a different enum...
326 static const char * const conditions[] = {
327 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
328 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
329 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
331 enum pp_conds {
332 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
333 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
334 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
335 c_none = -1
337 static const enum pp_conds inverse_ccs[] = {
338 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
339 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,
340 c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
344 * Directive names.
346 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
347 static int is_condition(enum preproc_token arg)
349 return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
352 /* For TASM compatibility we need to be able to recognise TASM compatible
353 * conditional compilation directives. Using the NASM pre-processor does
354 * not work, so we look for them specifically from the following list and
355 * then jam in the equivalent NASM directive into the input stream.
358 enum {
359 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
360 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
363 static const char * const tasm_directives[] = {
364 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
365 "ifndef", "include", "local"
368 static int StackSize = 4;
369 static char *StackPointer = "ebp";
370 static int ArgOffset = 8;
371 static int LocalOffset = 0;
373 static Context *cstk;
374 static Include *istk;
375 static IncPath *ipath = NULL;
377 static efunc _error; /* Pointer to client-provided error reporting function */
378 static evalfunc evaluate;
380 static int pass; /* HACK: pass 0 = generate dependencies only */
381 static StrList **dephead, **deptail; /* Dependency list */
383 static uint64_t unique; /* unique identifier numbers */
385 static Line *predef = NULL;
386 static bool do_predef;
388 static ListGen *list;
391 * The current set of multi-line macros we have defined.
393 static struct hash_table mmacros;
396 * The current set of single-line macros we have defined.
398 static struct hash_table smacros;
401 * The multi-line macro we are currently defining, or the %rep
402 * block we are currently reading, if any.
404 static MMacro *defining;
406 static uint64_t nested_mac_count;
407 static uint64_t nested_rep_count;
410 * The number of macro parameters to allocate space for at a time.
412 #define PARAM_DELTA 16
415 * The standard macro set: defined in macros.c in the array nasm_stdmac.
416 * This gives our position in the macro set, when we're processing it.
418 static macros_t *stdmacpos;
421 * The extra standard macros that come from the object format, if
422 * any.
424 static macros_t *extrastdmac = NULL;
425 static bool any_extrastdmac;
428 * Tokens are allocated in blocks to improve speed
430 #define TOKEN_BLOCKSIZE 4096
431 static Token *freeTokens = NULL;
432 struct Blocks {
433 Blocks *next;
434 void *chunk;
437 static Blocks blocks = { NULL, NULL };
440 * Forward declarations.
442 static Token *expand_mmac_params(Token * tline);
443 static Token *expand_smacro(Token * tline);
444 static Token *expand_id(Token * tline);
445 static Context *get_ctx(const char *name, const char **namep,
446 bool all_contexts);
447 static void make_tok_num(Token * tok, int64_t val);
448 static void error(int severity, const char *fmt, ...);
449 static void error_precond(int severity, const char *fmt, ...);
450 static void *new_Block(size_t size);
451 static void delete_Blocks(void);
452 static Token *new_Token(Token * next, enum pp_token_type type,
453 const char *text, int txtlen);
454 static Token *delete_Token(Token * t);
457 * Macros for safe checking of token pointers, avoid *(NULL)
459 #define tok_type_(x,t) ((x) && (x)->type == (t))
460 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
461 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
462 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
464 /* Handle TASM specific directives, which do not contain a % in
465 * front of them. We do it here because I could not find any other
466 * place to do it for the moment, and it is a hack (ideally it would
467 * be nice to be able to use the NASM pre-processor to do it).
469 static char *check_tasm_directive(char *line)
471 int32_t i, j, k, m, len;
472 char *p = line, *oldline, oldchar;
474 /* Skip whitespace */
475 while (nasm_isspace(*p) && *p != 0)
476 p++;
478 /* Binary search for the directive name */
479 i = -1;
480 j = elements(tasm_directives);
481 len = 0;
482 while (!nasm_isspace(p[len]) && p[len] != 0)
483 len++;
484 if (len) {
485 oldchar = p[len];
486 p[len] = 0;
487 while (j - i > 1) {
488 k = (j + i) / 2;
489 m = nasm_stricmp(p, tasm_directives[k]);
490 if (m == 0) {
491 /* We have found a directive, so jam a % in front of it
492 * so that NASM will then recognise it as one if it's own.
494 p[len] = oldchar;
495 len = strlen(p);
496 oldline = line;
497 line = nasm_malloc(len + 2);
498 line[0] = '%';
499 if (k == TM_IFDIFI) {
501 * NASM does not recognise IFDIFI, so we convert
502 * it to %if 0. This is not used in NASM
503 * compatible code, but does need to parse for the
504 * TASM macro package.
506 strcpy(line + 1, "if 0");
507 } else {
508 memcpy(line + 1, p, len + 1);
510 nasm_free(oldline);
511 return line;
512 } else if (m < 0) {
513 j = k;
514 } else
515 i = k;
517 p[len] = oldchar;
519 return line;
523 * The pre-preprocessing stage... This function translates line
524 * number indications as they emerge from GNU cpp (`# lineno "file"
525 * flags') into NASM preprocessor line number indications (`%line
526 * lineno file').
528 static char *prepreproc(char *line)
530 int lineno, fnlen;
531 char *fname, *oldline;
533 if (line[0] == '#' && line[1] == ' ') {
534 oldline = line;
535 fname = oldline + 2;
536 lineno = atoi(fname);
537 fname += strspn(fname, "0123456789 ");
538 if (*fname == '"')
539 fname++;
540 fnlen = strcspn(fname, "\"");
541 line = nasm_malloc(20 + fnlen);
542 snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
543 nasm_free(oldline);
545 if (tasm_compatible_mode)
546 return check_tasm_directive(line);
547 return line;
551 * Free a linked list of tokens.
553 static void free_tlist(Token * list)
555 while (list) {
556 list = delete_Token(list);
561 * Free a linked list of lines.
563 static void free_llist(Line * list)
565 Line *l;
566 while (list) {
567 l = list;
568 list = list->next;
569 free_tlist(l->first);
570 nasm_free(l);
575 * Free an MMacro
577 static void free_mmacro(MMacro * m)
579 nasm_free(m->name);
580 free_tlist(m->dlist);
581 nasm_free(m->defaults);
582 free_llist(m->expansion);
583 nasm_free(m);
587 * Free all currently defined macros, and free the hash tables
589 static void free_smacro_table(struct hash_table *smt)
591 SMacro *s;
592 const char *key;
593 struct hash_tbl_node *it = NULL;
595 while ((s = hash_iterate(smt, &it, &key)) != NULL) {
596 nasm_free((void *)key);
597 while (s) {
598 SMacro *ns = s->next;
599 nasm_free(s->name);
600 free_tlist(s->expansion);
601 nasm_free(s);
602 s = ns;
605 hash_free(smt);
608 static void free_mmacro_table(struct hash_table *mmt)
610 MMacro *m;
611 const char *key;
612 struct hash_tbl_node *it = NULL;
614 it = NULL;
615 while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
616 nasm_free((void *)key);
617 while (m) {
618 MMacro *nm = m->next;
619 free_mmacro(m);
620 m = nm;
623 hash_free(mmt);
626 static void free_macros(void)
628 free_smacro_table(&smacros);
629 free_mmacro_table(&mmacros);
633 * Initialize the hash tables
635 static void init_macros(void)
637 hash_init(&smacros, HASH_LARGE);
638 hash_init(&mmacros, HASH_LARGE);
642 * Pop the context stack.
644 static void ctx_pop(void)
646 Context *c = cstk;
648 cstk = cstk->next;
649 free_smacro_table(&c->localmac);
650 nasm_free(c->name);
651 nasm_free(c);
655 * Search for a key in the hash index; adding it if necessary
656 * (in which case we initialize the data pointer to NULL.)
658 static void **
659 hash_findi_add(struct hash_table *hash, const char *str)
661 struct hash_insert hi;
662 void **r;
663 char *strx;
665 r = hash_findi(hash, str, &hi);
666 if (r)
667 return r;
669 strx = nasm_strdup(str); /* Use a more efficient allocator here? */
670 return hash_add(&hi, strx, NULL);
674 * Like hash_findi, but returns the data element rather than a pointer
675 * to it. Used only when not adding a new element, hence no third
676 * argument.
678 static void *
679 hash_findix(struct hash_table *hash, const char *str)
681 void **p;
683 p = hash_findi(hash, str, NULL);
684 return p ? *p : NULL;
687 #define BUF_DELTA 512
689 * Read a line from the top file in istk, handling multiple CR/LFs
690 * at the end of the line read, and handling spurious ^Zs. Will
691 * return lines from the standard macro set if this has not already
692 * been done.
694 static char *read_line(void)
696 char *buffer, *p, *q;
697 int bufsize, continued_count;
699 if (stdmacpos) {
700 unsigned char c;
701 const unsigned char *p = stdmacpos;
702 char *ret, *q;
703 size_t len = 0;
704 while ((c = *p++)) {
705 if (c >= 0x80)
706 len += pp_directives_len[c-0x80]+1;
707 else
708 len++;
710 ret = nasm_malloc(len+1);
711 q = ret;
712 while ((c = *stdmacpos++)) {
713 if (c >= 0x80) {
714 memcpy(q, pp_directives[c-0x80], pp_directives_len[c-0x80]);
715 q += pp_directives_len[c-0x80];
716 *q++ = ' ';
717 } else {
718 *q++ = c;
721 stdmacpos = p;
722 *q = '\0';
724 if (!*stdmacpos) {
725 /* This was the last of the standard macro chain... */
726 stdmacpos = NULL;
727 if (any_extrastdmac) {
728 stdmacpos = extrastdmac;
729 any_extrastdmac = false;
730 } else if (do_predef) {
731 Line *pd, *l;
732 Token *head, **tail, *t;
735 * Nasty hack: here we push the contents of
736 * `predef' on to the top-level expansion stack,
737 * since this is the most convenient way to
738 * implement the pre-include and pre-define
739 * features.
741 for (pd = predef; pd; pd = pd->next) {
742 head = NULL;
743 tail = &head;
744 for (t = pd->first; t; t = t->next) {
745 *tail = new_Token(NULL, t->type, t->text, 0);
746 tail = &(*tail)->next;
748 l = nasm_malloc(sizeof(Line));
749 l->next = istk->expansion;
750 l->first = head;
751 l->finishes = NULL;
752 istk->expansion = l;
754 do_predef = false;
757 return ret;
760 bufsize = BUF_DELTA;
761 buffer = nasm_malloc(BUF_DELTA);
762 p = buffer;
763 continued_count = 0;
764 while (1) {
765 q = fgets(p, bufsize - (p - buffer), istk->fp);
766 if (!q)
767 break;
768 p += strlen(p);
769 if (p > buffer && p[-1] == '\n') {
770 /* Convert backslash-CRLF line continuation sequences into
771 nothing at all (for DOS and Windows) */
772 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
773 p -= 3;
774 *p = 0;
775 continued_count++;
777 /* Also convert backslash-LF line continuation sequences into
778 nothing at all (for Unix) */
779 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
780 p -= 2;
781 *p = 0;
782 continued_count++;
783 } else {
784 break;
787 if (p - buffer > bufsize - 10) {
788 int32_t offset = p - buffer;
789 bufsize += BUF_DELTA;
790 buffer = nasm_realloc(buffer, bufsize);
791 p = buffer + offset; /* prevent stale-pointer problems */
795 if (!q && p == buffer) {
796 nasm_free(buffer);
797 return NULL;
800 src_set_linnum(src_get_linnum() + istk->lineinc +
801 (continued_count * istk->lineinc));
804 * Play safe: remove CRs as well as LFs, if any of either are
805 * present at the end of the line.
807 while (--p >= buffer && (*p == '\n' || *p == '\r'))
808 *p = '\0';
811 * Handle spurious ^Z, which may be inserted into source files
812 * by some file transfer utilities.
814 buffer[strcspn(buffer, "\032")] = '\0';
816 list->line(LIST_READ, buffer);
818 return buffer;
822 * Tokenize a line of text. This is a very simple process since we
823 * don't need to parse the value out of e.g. numeric tokens: we
824 * simply split one string into many.
826 static Token *tokenize(char *line)
828 char c, *p = line;
829 enum pp_token_type type;
830 Token *list = NULL;
831 Token *t, **tail = &list;
833 while (*line) {
834 p = line;
835 if (*p == '%') {
836 p++;
837 if (*p == '+' && !nasm_isdigit(p[1])) {
838 p++;
839 type = TOK_PASTE;
840 } else if (nasm_isdigit(*p) ||
841 ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
842 do {
843 p++;
845 while (nasm_isdigit(*p));
846 type = TOK_PREPROC_ID;
847 } else if (*p == '{') {
848 p++;
849 while (*p && *p != '}') {
850 p[-1] = *p;
851 p++;
853 p[-1] = '\0';
854 if (*p)
855 p++;
856 type = TOK_PREPROC_ID;
857 } else if (*p == '[') {
858 int lvl = 1;
859 line += 2; /* Skip the leading %[ */
860 p++;
861 while (lvl && (c = *p++)) {
862 switch (c) {
863 case ']':
864 lvl--;
865 break;
866 case '%':
867 if (*p == '[')
868 lvl++;
869 break;
870 case '\'':
871 case '\"':
872 case '`':
873 p = nasm_skip_string(p)+1;
874 break;
875 default:
876 break;
879 p--;
880 if (*p)
881 *p++ = '\0';
882 if (lvl)
883 error(ERR_NONFATAL, "unterminated %[ construct");
884 type = TOK_INDIRECT;
885 } else if (*p == '?') {
886 type = TOK_PREPROC_Q; /* %? */
887 p++;
888 if (*p == '?') {
889 type = TOK_PREPROC_QQ; /* %?? */
890 p++;
892 } else if (isidchar(*p) ||
893 ((*p == '!' || *p == '%' || *p == '$') &&
894 isidchar(p[1]))) {
895 do {
896 p++;
898 while (isidchar(*p));
899 type = TOK_PREPROC_ID;
900 } else {
901 type = TOK_OTHER;
902 if (*p == '%')
903 p++;
905 } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
906 type = TOK_ID;
907 p++;
908 while (*p && isidchar(*p))
909 p++;
910 } else if (*p == '\'' || *p == '"' || *p == '`') {
912 * A string token.
914 type = TOK_STRING;
915 p = nasm_skip_string(p);
917 if (*p) {
918 p++;
919 } else {
920 error(ERR_WARNING|ERR_PASS1, "unterminated string");
921 /* Handling unterminated strings by UNV */
922 /* type = -1; */
924 } else if (p[0] == '$' && p[1] == '$') {
925 type = TOK_OTHER; /* TOKEN_BASE */
926 p += 2;
927 } else if (isnumstart(*p)) {
928 bool is_hex = false;
929 bool is_float = false;
930 bool has_e = false;
931 char c, *r;
934 * A numeric token.
937 if (*p == '$') {
938 p++;
939 is_hex = true;
942 for (;;) {
943 c = *p++;
945 if (!is_hex && (c == 'e' || c == 'E')) {
946 has_e = true;
947 if (*p == '+' || *p == '-') {
948 /* e can only be followed by +/- if it is either a
949 prefixed hex number or a floating-point number */
950 p++;
951 is_float = true;
953 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
954 is_hex = true;
955 } else if (c == 'P' || c == 'p') {
956 is_float = true;
957 if (*p == '+' || *p == '-')
958 p++;
959 } else if (isnumchar(c) || c == '_')
960 ; /* just advance */
961 else if (c == '.') {
962 /* we need to deal with consequences of the legacy
963 parser, like "1.nolist" being two tokens
964 (TOK_NUMBER, TOK_ID) here; at least give it
965 a shot for now. In the future, we probably need
966 a flex-based scanner with proper pattern matching
967 to do it as well as it can be done. Nothing in
968 the world is going to help the person who wants
969 0x123.p16 interpreted as two tokens, though. */
970 r = p;
971 while (*r == '_')
972 r++;
974 if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
975 (!is_hex && (*r == 'e' || *r == 'E')) ||
976 (*r == 'p' || *r == 'P')) {
977 p = r;
978 is_float = true;
979 } else
980 break; /* Terminate the token */
981 } else
982 break;
984 p--; /* Point to first character beyond number */
986 if (p == line+1 && *line == '$') {
987 type = TOK_OTHER; /* TOKEN_HERE */
988 } else {
989 if (has_e && !is_hex) {
990 /* 1e13 is floating-point, but 1e13h is not */
991 is_float = true;
994 type = is_float ? TOK_FLOAT : TOK_NUMBER;
996 } else if (nasm_isspace(*p)) {
997 type = TOK_WHITESPACE;
998 p++;
999 while (*p && nasm_isspace(*p))
1000 p++;
1002 * Whitespace just before end-of-line is discarded by
1003 * pretending it's a comment; whitespace just before a
1004 * comment gets lumped into the comment.
1006 if (!*p || *p == ';') {
1007 type = TOK_COMMENT;
1008 while (*p)
1009 p++;
1011 } else if (*p == ';') {
1012 type = TOK_COMMENT;
1013 while (*p)
1014 p++;
1015 } else {
1017 * Anything else is an operator of some kind. We check
1018 * for all the double-character operators (>>, <<, //,
1019 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1020 * else is a single-character operator.
1022 type = TOK_OTHER;
1023 if ((p[0] == '>' && p[1] == '>') ||
1024 (p[0] == '<' && p[1] == '<') ||
1025 (p[0] == '/' && p[1] == '/') ||
1026 (p[0] == '<' && p[1] == '=') ||
1027 (p[0] == '>' && p[1] == '=') ||
1028 (p[0] == '=' && p[1] == '=') ||
1029 (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++;
1036 p++;
1039 /* Handling unterminated string by UNV */
1040 /*if (type == -1)
1042 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1043 t->text[p-line] = *line;
1044 tail = &t->next;
1046 else */
1047 if (type != TOK_COMMENT) {
1048 *tail = t = new_Token(NULL, type, line, p - line);
1049 tail = &t->next;
1051 line = p;
1053 return list;
1057 * this function allocates a new managed block of memory and
1058 * returns a pointer to the block. The managed blocks are
1059 * deleted only all at once by the delete_Blocks function.
1061 static void *new_Block(size_t size)
1063 Blocks *b = &blocks;
1065 /* first, get to the end of the linked list */
1066 while (b->next)
1067 b = b->next;
1068 /* now allocate the requested chunk */
1069 b->chunk = nasm_malloc(size);
1071 /* now allocate a new block for the next request */
1072 b->next = nasm_malloc(sizeof(Blocks));
1073 /* and initialize the contents of the new block */
1074 b->next->next = NULL;
1075 b->next->chunk = NULL;
1076 return b->chunk;
1080 * this function deletes all managed blocks of memory
1082 static void delete_Blocks(void)
1084 Blocks *a, *b = &blocks;
1087 * keep in mind that the first block, pointed to by blocks
1088 * is a static and not dynamically allocated, so we don't
1089 * free it.
1091 while (b) {
1092 if (b->chunk)
1093 nasm_free(b->chunk);
1094 a = b;
1095 b = b->next;
1096 if (a != &blocks)
1097 nasm_free(a);
1102 * this function creates a new Token and passes a pointer to it
1103 * back to the caller. It sets the type and text elements, and
1104 * also the a.mac and next elements to NULL.
1106 static Token *new_Token(Token * next, enum pp_token_type type,
1107 const char *text, int txtlen)
1109 Token *t;
1110 int i;
1112 if (freeTokens == NULL) {
1113 freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1114 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1115 freeTokens[i].next = &freeTokens[i + 1];
1116 freeTokens[i].next = NULL;
1118 t = freeTokens;
1119 freeTokens = t->next;
1120 t->next = next;
1121 t->a.mac = NULL;
1122 t->type = type;
1123 if (type == TOK_WHITESPACE || text == NULL) {
1124 t->text = NULL;
1125 } else {
1126 if (txtlen == 0)
1127 txtlen = strlen(text);
1128 t->text = nasm_malloc(txtlen+1);
1129 memcpy(t->text, text, txtlen);
1130 t->text[txtlen] = '\0';
1132 return t;
1135 static Token *delete_Token(Token * t)
1137 Token *next = t->next;
1138 nasm_free(t->text);
1139 t->next = freeTokens;
1140 freeTokens = t;
1141 return next;
1145 * Convert a line of tokens back into text.
1146 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1147 * will be transformed into ..@ctxnum.xxx
1149 static char *detoken(Token * tlist, bool expand_locals)
1151 Token *t;
1152 int len;
1153 char *line, *p;
1154 const char *q;
1156 len = 0;
1157 for (t = tlist; t; t = t->next) {
1158 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1159 char *p = getenv(t->text + 2);
1160 nasm_free(t->text);
1161 if (p)
1162 t->text = nasm_strdup(p);
1163 else
1164 t->text = NULL;
1166 /* Expand local macros here and not during preprocessing */
1167 if (expand_locals &&
1168 t->type == TOK_PREPROC_ID && t->text &&
1169 t->text[0] == '%' && t->text[1] == '$') {
1170 const char *q;
1171 char *p;
1172 Context *ctx = get_ctx(t->text, &q, false);
1173 if (ctx) {
1174 char buffer[40];
1175 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1176 p = nasm_strcat(buffer, q);
1177 nasm_free(t->text);
1178 t->text = p;
1181 if (t->type == TOK_WHITESPACE) {
1182 len++;
1183 } else if (t->text) {
1184 len += strlen(t->text);
1187 p = line = nasm_malloc(len + 1);
1188 for (t = tlist; t; t = t->next) {
1189 if (t->type == TOK_WHITESPACE) {
1190 *p++ = ' ';
1191 } else if (t->text) {
1192 q = t->text;
1193 while (*q)
1194 *p++ = *q++;
1197 *p = '\0';
1198 return line;
1202 * A scanner, suitable for use by the expression evaluator, which
1203 * operates on a line of Tokens. Expects a pointer to a pointer to
1204 * the first token in the line to be passed in as its private_data
1205 * field.
1207 * FIX: This really needs to be unified with stdscan.
1209 static int ppscan(void *private_data, struct tokenval *tokval)
1211 Token **tlineptr = private_data;
1212 Token *tline;
1213 char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1215 do {
1216 tline = *tlineptr;
1217 *tlineptr = tline ? tline->next : NULL;
1219 while (tline && (tline->type == TOK_WHITESPACE ||
1220 tline->type == TOK_COMMENT));
1222 if (!tline)
1223 return tokval->t_type = TOKEN_EOS;
1225 tokval->t_charptr = tline->text;
1227 if (tline->text[0] == '$' && !tline->text[1])
1228 return tokval->t_type = TOKEN_HERE;
1229 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1230 return tokval->t_type = TOKEN_BASE;
1232 if (tline->type == TOK_ID) {
1233 p = tokval->t_charptr = tline->text;
1234 if (p[0] == '$') {
1235 tokval->t_charptr++;
1236 return tokval->t_type = TOKEN_ID;
1239 for (r = p, s = ourcopy; *r; r++) {
1240 if (r >= p+MAX_KEYWORD)
1241 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1242 *s++ = nasm_tolower(*r);
1244 *s = '\0';
1245 /* right, so we have an identifier sitting in temp storage. now,
1246 * is it actually a register or instruction name, or what? */
1247 return nasm_token_hash(ourcopy, tokval);
1250 if (tline->type == TOK_NUMBER) {
1251 bool rn_error;
1252 tokval->t_integer = readnum(tline->text, &rn_error);
1253 tokval->t_charptr = tline->text;
1254 if (rn_error)
1255 return tokval->t_type = TOKEN_ERRNUM;
1256 else
1257 return tokval->t_type = TOKEN_NUM;
1260 if (tline->type == TOK_FLOAT) {
1261 return tokval->t_type = TOKEN_FLOAT;
1264 if (tline->type == TOK_STRING) {
1265 char bq, *ep;
1267 bq = tline->text[0];
1268 tokval->t_charptr = tline->text;
1269 tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1271 if (ep[0] != bq || ep[1] != '\0')
1272 return tokval->t_type = TOKEN_ERRSTR;
1273 else
1274 return tokval->t_type = TOKEN_STR;
1277 if (tline->type == TOK_OTHER) {
1278 if (!strcmp(tline->text, "<<"))
1279 return tokval->t_type = TOKEN_SHL;
1280 if (!strcmp(tline->text, ">>"))
1281 return tokval->t_type = TOKEN_SHR;
1282 if (!strcmp(tline->text, "//"))
1283 return tokval->t_type = TOKEN_SDIV;
1284 if (!strcmp(tline->text, "%%"))
1285 return tokval->t_type = TOKEN_SMOD;
1286 if (!strcmp(tline->text, "=="))
1287 return tokval->t_type = TOKEN_EQ;
1288 if (!strcmp(tline->text, "<>"))
1289 return tokval->t_type = TOKEN_NE;
1290 if (!strcmp(tline->text, "!="))
1291 return tokval->t_type = TOKEN_NE;
1292 if (!strcmp(tline->text, "<="))
1293 return tokval->t_type = TOKEN_LE;
1294 if (!strcmp(tline->text, ">="))
1295 return tokval->t_type = TOKEN_GE;
1296 if (!strcmp(tline->text, "&&"))
1297 return tokval->t_type = TOKEN_DBL_AND;
1298 if (!strcmp(tline->text, "^^"))
1299 return tokval->t_type = TOKEN_DBL_XOR;
1300 if (!strcmp(tline->text, "||"))
1301 return tokval->t_type = TOKEN_DBL_OR;
1305 * We have no other options: just return the first character of
1306 * the token text.
1308 return tokval->t_type = tline->text[0];
1312 * Compare a string to the name of an existing macro; this is a
1313 * simple wrapper which calls either strcmp or nasm_stricmp
1314 * depending on the value of the `casesense' parameter.
1316 static int mstrcmp(const char *p, const char *q, bool casesense)
1318 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1322 * Compare a string to the name of an existing macro; this is a
1323 * simple wrapper which calls either strcmp or nasm_stricmp
1324 * depending on the value of the `casesense' parameter.
1326 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1328 return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1332 * Return the Context structure associated with a %$ token. Return
1333 * NULL, having _already_ reported an error condition, if the
1334 * context stack isn't deep enough for the supplied number of $
1335 * signs.
1336 * If all_contexts == true, contexts that enclose current are
1337 * also scanned for such smacro, until it is found; if not -
1338 * only the context that directly results from the number of $'s
1339 * in variable's name.
1341 * If "namep" is non-NULL, set it to the pointer to the macro name
1342 * tail, i.e. the part beyond %$...
1344 static Context *get_ctx(const char *name, const char **namep,
1345 bool all_contexts)
1347 Context *ctx;
1348 SMacro *m;
1349 int i;
1351 if (namep)
1352 *namep = name;
1354 if (!name || name[0] != '%' || name[1] != '$')
1355 return NULL;
1357 if (!cstk) {
1358 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1359 return NULL;
1362 name += 2;
1363 ctx = cstk;
1364 i = 0;
1365 while (ctx && *name == '$') {
1366 name++;
1367 i++;
1368 ctx = ctx->next;
1370 if (!ctx) {
1371 error(ERR_NONFATAL, "`%s': context stack is only"
1372 " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1373 return NULL;
1376 if (namep)
1377 *namep = name;
1379 if (!all_contexts)
1380 return ctx;
1382 do {
1383 /* Search for this smacro in found context */
1384 m = hash_findix(&ctx->localmac, name);
1385 while (m) {
1386 if (!mstrcmp(m->name, name, m->casesense))
1387 return ctx;
1388 m = m->next;
1390 ctx = ctx->next;
1392 while (ctx);
1393 return NULL;
1397 * Check to see if a file is already in a string list
1399 static bool in_list(const StrList *list, const char *str)
1401 while (list) {
1402 if (!strcmp(list->str, str))
1403 return true;
1404 list = list->next;
1406 return false;
1410 * Open an include file. This routine must always return a valid
1411 * file pointer if it returns - it's responsible for throwing an
1412 * ERR_FATAL and bombing out completely if not. It should also try
1413 * the include path one by one until it finds the file or reaches
1414 * the end of the path.
1416 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1417 bool missing_ok)
1419 FILE *fp;
1420 char *prefix = "";
1421 IncPath *ip = ipath;
1422 int len = strlen(file);
1423 size_t prefix_len = 0;
1424 StrList *sl;
1426 while (1) {
1427 sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1428 memcpy(sl->str, prefix, prefix_len);
1429 memcpy(sl->str+prefix_len, file, len+1);
1430 fp = fopen(sl->str, "r");
1431 if (fp && dhead && !in_list(*dhead, sl->str)) {
1432 sl->next = NULL;
1433 **dtail = sl;
1434 *dtail = &sl->next;
1435 } else {
1436 nasm_free(sl);
1438 if (fp)
1439 return fp;
1440 if (!ip) {
1441 if (!missing_ok)
1442 break;
1443 prefix = NULL;
1444 } else {
1445 prefix = ip->path;
1446 ip = ip->next;
1448 if (prefix) {
1449 prefix_len = strlen(prefix);
1450 } else {
1451 /* -MG given and file not found */
1452 if (dhead && !in_list(*dhead, file)) {
1453 sl = nasm_malloc(len+1+sizeof sl->next);
1454 sl->next = NULL;
1455 strcpy(sl->str, file);
1456 **dtail = sl;
1457 *dtail = &sl->next;
1459 return NULL;
1463 error(ERR_FATAL, "unable to open include file `%s'", file);
1464 return NULL; /* never reached - placate compilers */
1468 * Determine if we should warn on defining a single-line macro of
1469 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1470 * return true if _any_ single-line macro of that name is defined.
1471 * Otherwise, will return true if a single-line macro with either
1472 * `nparam' or no parameters is defined.
1474 * If a macro with precisely the right number of parameters is
1475 * defined, or nparam is -1, the address of the definition structure
1476 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1477 * is NULL, no action will be taken regarding its contents, and no
1478 * error will occur.
1480 * Note that this is also called with nparam zero to resolve
1481 * `ifdef'.
1483 * If you already know which context macro belongs to, you can pass
1484 * the context pointer as first parameter; if you won't but name begins
1485 * with %$ the context will be automatically computed. If all_contexts
1486 * is true, macro will be searched in outer contexts as well.
1488 static bool
1489 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1490 bool nocase)
1492 struct hash_table *smtbl;
1493 SMacro *m;
1495 if (ctx) {
1496 smtbl = &ctx->localmac;
1497 } else if (name[0] == '%' && name[1] == '$') {
1498 if (cstk)
1499 ctx = get_ctx(name, &name, false);
1500 if (!ctx)
1501 return false; /* got to return _something_ */
1502 smtbl = &ctx->localmac;
1503 } else {
1504 smtbl = &smacros;
1506 m = (SMacro *) hash_findix(smtbl, name);
1508 while (m) {
1509 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1510 (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1511 if (defn) {
1512 if (nparam == (int) m->nparam || nparam == -1)
1513 *defn = m;
1514 else
1515 *defn = NULL;
1517 return true;
1519 m = m->next;
1522 return false;
1526 * Count and mark off the parameters in a multi-line macro call.
1527 * This is called both from within the multi-line macro expansion
1528 * code, and also to mark off the default parameters when provided
1529 * in a %macro definition line.
1531 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1533 int paramsize, brace;
1535 *nparam = paramsize = 0;
1536 *params = NULL;
1537 while (t) {
1538 /* +1: we need space for the final NULL */
1539 if (*nparam+1 >= paramsize) {
1540 paramsize += PARAM_DELTA;
1541 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1543 skip_white_(t);
1544 brace = false;
1545 if (tok_is_(t, "{"))
1546 brace = true;
1547 (*params)[(*nparam)++] = t;
1548 while (tok_isnt_(t, brace ? "}" : ","))
1549 t = t->next;
1550 if (t) { /* got a comma/brace */
1551 t = t->next;
1552 if (brace) {
1554 * Now we've found the closing brace, look further
1555 * for the comma.
1557 skip_white_(t);
1558 if (tok_isnt_(t, ",")) {
1559 error(ERR_NONFATAL,
1560 "braces do not enclose all of macro parameter");
1561 while (tok_isnt_(t, ","))
1562 t = t->next;
1564 if (t)
1565 t = t->next; /* eat the comma */
1572 * Determine whether one of the various `if' conditions is true or
1573 * not.
1575 * We must free the tline we get passed.
1577 static bool if_condition(Token * tline, enum preproc_token ct)
1579 enum pp_conditional i = PP_COND(ct);
1580 bool j;
1581 Token *t, *tt, **tptr, *origline;
1582 struct tokenval tokval;
1583 expr *evalresult;
1584 enum pp_token_type needtype;
1586 origline = tline;
1588 switch (i) {
1589 case PPC_IFCTX:
1590 j = false; /* have we matched yet? */
1591 while (true) {
1592 skip_white_(tline);
1593 if (!tline)
1594 break;
1595 if (tline->type != TOK_ID) {
1596 error(ERR_NONFATAL,
1597 "`%s' expects context identifiers", pp_directives[ct]);
1598 free_tlist(origline);
1599 return -1;
1601 if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1602 j = true;
1603 tline = tline->next;
1605 break;
1607 case PPC_IFDEF:
1608 j = false; /* have we matched yet? */
1609 while (tline) {
1610 skip_white_(tline);
1611 if (!tline || (tline->type != TOK_ID &&
1612 (tline->type != TOK_PREPROC_ID ||
1613 tline->text[1] != '$'))) {
1614 error(ERR_NONFATAL,
1615 "`%s' expects macro identifiers", pp_directives[ct]);
1616 goto fail;
1618 if (smacro_defined(NULL, tline->text, 0, NULL, true))
1619 j = true;
1620 tline = tline->next;
1622 break;
1624 case PPC_IFIDN:
1625 case PPC_IFIDNI:
1626 tline = expand_smacro(tline);
1627 t = tt = tline;
1628 while (tok_isnt_(tt, ","))
1629 tt = tt->next;
1630 if (!tt) {
1631 error(ERR_NONFATAL,
1632 "`%s' expects two comma-separated arguments",
1633 pp_directives[ct]);
1634 goto fail;
1636 tt = tt->next;
1637 j = true; /* assume equality unless proved not */
1638 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1639 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1640 error(ERR_NONFATAL, "`%s': more than one comma on line",
1641 pp_directives[ct]);
1642 goto fail;
1644 if (t->type == TOK_WHITESPACE) {
1645 t = t->next;
1646 continue;
1648 if (tt->type == TOK_WHITESPACE) {
1649 tt = tt->next;
1650 continue;
1652 if (tt->type != t->type) {
1653 j = false; /* found mismatching tokens */
1654 break;
1656 /* When comparing strings, need to unquote them first */
1657 if (t->type == TOK_STRING) {
1658 size_t l1 = nasm_unquote(t->text, NULL);
1659 size_t l2 = nasm_unquote(tt->text, NULL);
1661 if (l1 != l2) {
1662 j = false;
1663 break;
1665 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1666 j = false;
1667 break;
1669 } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1670 j = false; /* found mismatching tokens */
1671 break;
1674 t = t->next;
1675 tt = tt->next;
1677 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1678 j = false; /* trailing gunk on one end or other */
1679 break;
1681 case PPC_IFMACRO:
1683 bool found = false;
1684 MMacro searching, *mmac;
1686 skip_white_(tline);
1687 tline = expand_id(tline);
1688 if (!tok_type_(tline, TOK_ID)) {
1689 error(ERR_NONFATAL,
1690 "`%s' expects a macro name", pp_directives[ct]);
1691 goto fail;
1693 searching.name = nasm_strdup(tline->text);
1694 searching.casesense = true;
1695 searching.plus = false;
1696 searching.nolist = false;
1697 searching.in_progress = 0;
1698 searching.max_depth = 0;
1699 searching.rep_nest = NULL;
1700 searching.nparam_min = 0;
1701 searching.nparam_max = INT_MAX;
1702 tline = expand_smacro(tline->next);
1703 skip_white_(tline);
1704 if (!tline) {
1705 } else if (!tok_type_(tline, TOK_NUMBER)) {
1706 error(ERR_NONFATAL,
1707 "`%s' expects a parameter count or nothing",
1708 pp_directives[ct]);
1709 } else {
1710 searching.nparam_min = searching.nparam_max =
1711 readnum(tline->text, &j);
1712 if (j)
1713 error(ERR_NONFATAL,
1714 "unable to parse parameter count `%s'",
1715 tline->text);
1717 if (tline && tok_is_(tline->next, "-")) {
1718 tline = tline->next->next;
1719 if (tok_is_(tline, "*"))
1720 searching.nparam_max = INT_MAX;
1721 else if (!tok_type_(tline, TOK_NUMBER))
1722 error(ERR_NONFATAL,
1723 "`%s' expects a parameter count after `-'",
1724 pp_directives[ct]);
1725 else {
1726 searching.nparam_max = readnum(tline->text, &j);
1727 if (j)
1728 error(ERR_NONFATAL,
1729 "unable to parse parameter count `%s'",
1730 tline->text);
1731 if (searching.nparam_min > searching.nparam_max)
1732 error(ERR_NONFATAL,
1733 "minimum parameter count exceeds maximum");
1736 if (tline && tok_is_(tline->next, "+")) {
1737 tline = tline->next;
1738 searching.plus = true;
1740 mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1741 while (mmac) {
1742 if (!strcmp(mmac->name, searching.name) &&
1743 (mmac->nparam_min <= searching.nparam_max
1744 || searching.plus)
1745 && (searching.nparam_min <= mmac->nparam_max
1746 || mmac->plus)) {
1747 found = true;
1748 break;
1750 mmac = mmac->next;
1752 if(tline && tline->next)
1753 error(ERR_WARNING|ERR_PASS1,
1754 "trailing garbage after %%ifmacro ignored");
1755 nasm_free(searching.name);
1756 j = found;
1757 break;
1760 case PPC_IFID:
1761 needtype = TOK_ID;
1762 goto iftype;
1763 case PPC_IFNUM:
1764 needtype = TOK_NUMBER;
1765 goto iftype;
1766 case PPC_IFSTR:
1767 needtype = TOK_STRING;
1768 goto iftype;
1770 iftype:
1771 t = tline = expand_smacro(tline);
1773 while (tok_type_(t, TOK_WHITESPACE) ||
1774 (needtype == TOK_NUMBER &&
1775 tok_type_(t, TOK_OTHER) &&
1776 (t->text[0] == '-' || t->text[0] == '+') &&
1777 !t->text[1]))
1778 t = t->next;
1780 j = tok_type_(t, needtype);
1781 break;
1783 case PPC_IFTOKEN:
1784 t = tline = expand_smacro(tline);
1785 while (tok_type_(t, TOK_WHITESPACE))
1786 t = t->next;
1788 j = false;
1789 if (t) {
1790 t = t->next; /* Skip the actual token */
1791 while (tok_type_(t, TOK_WHITESPACE))
1792 t = t->next;
1793 j = !t; /* Should be nothing left */
1795 break;
1797 case PPC_IFEMPTY:
1798 t = tline = expand_smacro(tline);
1799 while (tok_type_(t, TOK_WHITESPACE))
1800 t = t->next;
1802 j = !t; /* Should be empty */
1803 break;
1805 case PPC_IF:
1806 t = tline = expand_smacro(tline);
1807 tptr = &t;
1808 tokval.t_type = TOKEN_INVALID;
1809 evalresult = evaluate(ppscan, tptr, &tokval,
1810 NULL, pass | CRITICAL, error, NULL);
1811 if (!evalresult)
1812 return -1;
1813 if (tokval.t_type)
1814 error(ERR_WARNING|ERR_PASS1,
1815 "trailing garbage after expression ignored");
1816 if (!is_simple(evalresult)) {
1817 error(ERR_NONFATAL,
1818 "non-constant value given to `%s'", pp_directives[ct]);
1819 goto fail;
1821 j = reloc_value(evalresult) != 0;
1822 break;
1824 default:
1825 error(ERR_FATAL,
1826 "preprocessor directive `%s' not yet implemented",
1827 pp_directives[ct]);
1828 goto fail;
1831 free_tlist(origline);
1832 return j ^ PP_NEGATIVE(ct);
1834 fail:
1835 free_tlist(origline);
1836 return -1;
1840 * Common code for defining an smacro
1842 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1843 int nparam, Token *expansion)
1845 SMacro *smac, **smhead;
1846 struct hash_table *smtbl;
1848 if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1849 if (!smac) {
1850 error(ERR_WARNING|ERR_PASS1,
1851 "single-line macro `%s' defined both with and"
1852 " without parameters", mname);
1854 /* Some instances of the old code considered this a failure,
1855 some others didn't. What is the right thing to do here? */
1856 free_tlist(expansion);
1857 return false; /* Failure */
1858 } else {
1860 * We're redefining, so we have to take over an
1861 * existing SMacro structure. This means freeing
1862 * what was already in it.
1864 nasm_free(smac->name);
1865 free_tlist(smac->expansion);
1867 } else {
1868 smtbl = ctx ? &ctx->localmac : &smacros;
1869 smhead = (SMacro **) hash_findi_add(smtbl, mname);
1870 smac = nasm_malloc(sizeof(SMacro));
1871 smac->next = *smhead;
1872 *smhead = smac;
1874 smac->name = nasm_strdup(mname);
1875 smac->casesense = casesense;
1876 smac->nparam = nparam;
1877 smac->expansion = expansion;
1878 smac->in_progress = false;
1879 return true; /* Success */
1883 * Undefine an smacro
1885 static void undef_smacro(Context *ctx, const char *mname)
1887 SMacro **smhead, *s, **sp;
1888 struct hash_table *smtbl;
1890 smtbl = ctx ? &ctx->localmac : &smacros;
1891 smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
1893 if (smhead) {
1895 * We now have a macro name... go hunt for it.
1897 sp = smhead;
1898 while ((s = *sp) != NULL) {
1899 if (!mstrcmp(s->name, mname, s->casesense)) {
1900 *sp = s->next;
1901 nasm_free(s->name);
1902 free_tlist(s->expansion);
1903 nasm_free(s);
1904 } else {
1905 sp = &s->next;
1912 * Parse a mmacro specification.
1914 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
1916 bool err;
1918 tline = tline->next;
1919 skip_white_(tline);
1920 tline = expand_id(tline);
1921 if (!tok_type_(tline, TOK_ID)) {
1922 error(ERR_NONFATAL, "`%s' expects a macro name", directive);
1923 return false;
1926 def->prev = NULL;
1927 def->name = nasm_strdup(tline->text);
1928 def->plus = false;
1929 def->nolist = false;
1930 def->in_progress = 0;
1931 def->rep_nest = NULL;
1932 def->nparam_min = 0;
1933 def->nparam_max = 0;
1935 tline = expand_smacro(tline->next);
1936 skip_white_(tline);
1937 if (!tok_type_(tline, TOK_NUMBER)) {
1938 error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
1939 } else {
1940 def->nparam_min = def->nparam_max =
1941 readnum(tline->text, &err);
1942 if (err)
1943 error(ERR_NONFATAL,
1944 "unable to parse parameter count `%s'", tline->text);
1946 if (tline && tok_is_(tline->next, "-")) {
1947 tline = tline->next->next;
1948 if (tok_is_(tline, "*")) {
1949 def->nparam_max = INT_MAX;
1950 } else if (!tok_type_(tline, TOK_NUMBER)) {
1951 error(ERR_NONFATAL,
1952 "`%s' expects a parameter count after `-'", directive);
1953 } else {
1954 def->nparam_max = readnum(tline->text, &err);
1955 if (err) {
1956 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
1957 tline->text);
1959 if (def->nparam_min > def->nparam_max) {
1960 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
1964 if (tline && tok_is_(tline->next, "+")) {
1965 tline = tline->next;
1966 def->plus = true;
1968 if (tline && tok_type_(tline->next, TOK_ID) &&
1969 !nasm_stricmp(tline->next->text, ".nolist")) {
1970 tline = tline->next;
1971 def->nolist = true;
1975 * Handle default parameters.
1977 if (tline && tline->next) {
1978 def->dlist = tline->next;
1979 tline->next = NULL;
1980 count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
1981 } else {
1982 def->dlist = NULL;
1983 def->defaults = NULL;
1985 def->expansion = NULL;
1987 if(def->defaults &&
1988 def->ndefs > def->nparam_max - def->nparam_min &&
1989 !def->plus)
1990 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
1991 "too many default macro parameters");
1993 return true;
1998 * Decode a size directive
2000 static int parse_size(const char *str) {
2001 static const char *size_names[] =
2002 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2003 static const int sizes[] =
2004 { 0, 1, 4, 16, 8, 10, 2, 32 };
2006 return sizes[bsii(str, size_names, elements(size_names))+1];
2010 * find and process preprocessor directive in passed line
2011 * Find out if a line contains a preprocessor directive, and deal
2012 * with it if so.
2014 * If a directive _is_ found, it is the responsibility of this routine
2015 * (and not the caller) to free_tlist() the line.
2017 * @param tline a pointer to the current tokeninzed line linked list
2018 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2021 static int do_directive(Token * tline)
2023 enum preproc_token i;
2024 int j;
2025 bool err;
2026 int nparam;
2027 bool nolist;
2028 bool casesense;
2029 int k, m;
2030 int offset;
2031 char *p, *pp;
2032 const char *mname;
2033 Include *inc;
2034 Context *ctx;
2035 Cond *cond;
2036 MMacro *mmac, **mmhead;
2037 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2038 Line *l;
2039 struct tokenval tokval;
2040 expr *evalresult;
2041 MMacro *tmp_defining; /* Used when manipulating rep_nest */
2042 int64_t count;
2043 size_t len;
2044 int severity;
2046 origline = tline;
2048 skip_white_(tline);
2049 if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2050 (tline->text[1] == '%' || tline->text[1] == '$'
2051 || tline->text[1] == '!'))
2052 return NO_DIRECTIVE_FOUND;
2054 i = pp_token_hash(tline->text);
2057 * If we're in a non-emitting branch of a condition construct,
2058 * or walking to the end of an already terminated %rep block,
2059 * we should ignore all directives except for condition
2060 * directives.
2062 if (((istk->conds && !emitting(istk->conds->state)) ||
2063 (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2064 return NO_DIRECTIVE_FOUND;
2068 * If we're defining a macro or reading a %rep block, we should
2069 * ignore all directives except for %macro/%imacro (which nest),
2070 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2071 * If we're in a %rep block, another %rep nests, so should be let through.
2073 if (defining && i != PP_MACRO && i != PP_IMACRO &&
2074 i != PP_ENDMACRO && i != PP_ENDM &&
2075 (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2076 return NO_DIRECTIVE_FOUND;
2079 if (defining) {
2080 if (i == PP_MACRO || i == PP_IMACRO) {
2081 nested_mac_count++;
2082 return NO_DIRECTIVE_FOUND;
2083 } else if (nested_mac_count > 0) {
2084 if (i == PP_ENDMACRO) {
2085 nested_mac_count--;
2086 return NO_DIRECTIVE_FOUND;
2089 if (!defining->name) {
2090 if (i == PP_REP) {
2091 nested_rep_count++;
2092 return NO_DIRECTIVE_FOUND;
2093 } else if (nested_rep_count > 0) {
2094 if (i == PP_ENDREP) {
2095 nested_rep_count--;
2096 return NO_DIRECTIVE_FOUND;
2102 switch (i) {
2103 case PP_INVALID:
2104 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2105 tline->text);
2106 return NO_DIRECTIVE_FOUND; /* didn't get it */
2108 case PP_STACKSIZE:
2109 /* Directive to tell NASM what the default stack size is. The
2110 * default is for a 16-bit stack, and this can be overriden with
2111 * %stacksize large.
2112 * the following form:
2114 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2116 tline = tline->next;
2117 if (tline && tline->type == TOK_WHITESPACE)
2118 tline = tline->next;
2119 if (!tline || tline->type != TOK_ID) {
2120 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2121 free_tlist(origline);
2122 return DIRECTIVE_FOUND;
2124 if (nasm_stricmp(tline->text, "flat") == 0) {
2125 /* All subsequent ARG directives are for a 32-bit stack */
2126 StackSize = 4;
2127 StackPointer = "ebp";
2128 ArgOffset = 8;
2129 LocalOffset = 0;
2130 } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2131 /* All subsequent ARG directives are for a 64-bit stack */
2132 StackSize = 8;
2133 StackPointer = "rbp";
2134 ArgOffset = 8;
2135 LocalOffset = 0;
2136 } else if (nasm_stricmp(tline->text, "large") == 0) {
2137 /* All subsequent ARG directives are for a 16-bit stack,
2138 * far function call.
2140 StackSize = 2;
2141 StackPointer = "bp";
2142 ArgOffset = 4;
2143 LocalOffset = 0;
2144 } else if (nasm_stricmp(tline->text, "small") == 0) {
2145 /* All subsequent ARG directives are for a 16-bit stack,
2146 * far function call. We don't support near functions.
2148 StackSize = 2;
2149 StackPointer = "bp";
2150 ArgOffset = 6;
2151 LocalOffset = 0;
2152 } else {
2153 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2154 free_tlist(origline);
2155 return DIRECTIVE_FOUND;
2157 free_tlist(origline);
2158 return DIRECTIVE_FOUND;
2160 case PP_ARG:
2161 /* TASM like ARG directive to define arguments to functions, in
2162 * the following form:
2164 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2166 offset = ArgOffset;
2167 do {
2168 char *arg, directive[256];
2169 int size = StackSize;
2171 /* Find the argument name */
2172 tline = tline->next;
2173 if (tline && tline->type == TOK_WHITESPACE)
2174 tline = tline->next;
2175 if (!tline || tline->type != TOK_ID) {
2176 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2177 free_tlist(origline);
2178 return DIRECTIVE_FOUND;
2180 arg = tline->text;
2182 /* Find the argument size type */
2183 tline = tline->next;
2184 if (!tline || tline->type != TOK_OTHER
2185 || tline->text[0] != ':') {
2186 error(ERR_NONFATAL,
2187 "Syntax error processing `%%arg' directive");
2188 free_tlist(origline);
2189 return DIRECTIVE_FOUND;
2191 tline = tline->next;
2192 if (!tline || tline->type != TOK_ID) {
2193 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2194 free_tlist(origline);
2195 return DIRECTIVE_FOUND;
2198 /* Allow macro expansion of type parameter */
2199 tt = tokenize(tline->text);
2200 tt = expand_smacro(tt);
2201 size = parse_size(tt->text);
2202 if (!size) {
2203 error(ERR_NONFATAL,
2204 "Invalid size type for `%%arg' missing directive");
2205 free_tlist(tt);
2206 free_tlist(origline);
2207 return DIRECTIVE_FOUND;
2209 free_tlist(tt);
2211 /* Round up to even stack slots */
2212 size = (size+StackSize-1) & ~(StackSize-1);
2214 /* Now define the macro for the argument */
2215 snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2216 arg, StackPointer, offset);
2217 do_directive(tokenize(directive));
2218 offset += size;
2220 /* Move to the next argument in the list */
2221 tline = tline->next;
2222 if (tline && tline->type == TOK_WHITESPACE)
2223 tline = tline->next;
2224 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2225 ArgOffset = offset;
2226 free_tlist(origline);
2227 return DIRECTIVE_FOUND;
2229 case PP_LOCAL:
2230 /* TASM like LOCAL directive to define local variables for a
2231 * function, in the following form:
2233 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2235 * The '= LocalSize' at the end is ignored by NASM, but is
2236 * required by TASM to define the local parameter size (and used
2237 * by the TASM macro package).
2239 offset = LocalOffset;
2240 do {
2241 char *local, directive[256];
2242 int size = StackSize;
2244 /* Find the argument name */
2245 tline = tline->next;
2246 if (tline && tline->type == TOK_WHITESPACE)
2247 tline = tline->next;
2248 if (!tline || tline->type != TOK_ID) {
2249 error(ERR_NONFATAL,
2250 "`%%local' missing argument parameter");
2251 free_tlist(origline);
2252 return DIRECTIVE_FOUND;
2254 local = tline->text;
2256 /* Find the argument size type */
2257 tline = tline->next;
2258 if (!tline || tline->type != TOK_OTHER
2259 || tline->text[0] != ':') {
2260 error(ERR_NONFATAL,
2261 "Syntax error processing `%%local' directive");
2262 free_tlist(origline);
2263 return DIRECTIVE_FOUND;
2265 tline = tline->next;
2266 if (!tline || tline->type != TOK_ID) {
2267 error(ERR_NONFATAL,
2268 "`%%local' missing size type parameter");
2269 free_tlist(origline);
2270 return DIRECTIVE_FOUND;
2273 /* Allow macro expansion of type parameter */
2274 tt = tokenize(tline->text);
2275 tt = expand_smacro(tt);
2276 size = parse_size(tt->text);
2277 if (!size) {
2278 error(ERR_NONFATAL,
2279 "Invalid size type for `%%local' missing directive");
2280 free_tlist(tt);
2281 free_tlist(origline);
2282 return DIRECTIVE_FOUND;
2284 free_tlist(tt);
2286 /* Round up to even stack slots */
2287 size = (size+StackSize-1) & ~(StackSize-1);
2289 offset += size; /* Negative offset, increment before */
2291 /* Now define the macro for the argument */
2292 snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2293 local, StackPointer, offset);
2294 do_directive(tokenize(directive));
2296 /* Now define the assign to setup the enter_c macro correctly */
2297 snprintf(directive, sizeof(directive),
2298 "%%assign %%$localsize %%$localsize+%d", size);
2299 do_directive(tokenize(directive));
2301 /* Move to the next argument in the list */
2302 tline = tline->next;
2303 if (tline && tline->type == TOK_WHITESPACE)
2304 tline = tline->next;
2305 } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2306 LocalOffset = offset;
2307 free_tlist(origline);
2308 return DIRECTIVE_FOUND;
2310 case PP_CLEAR:
2311 if (tline->next)
2312 error(ERR_WARNING|ERR_PASS1,
2313 "trailing garbage after `%%clear' ignored");
2314 free_macros();
2315 init_macros();
2316 free_tlist(origline);
2317 return DIRECTIVE_FOUND;
2319 case PP_DEPEND:
2320 t = tline->next = expand_smacro(tline->next);
2321 skip_white_(t);
2322 if (!t || (t->type != TOK_STRING &&
2323 t->type != TOK_INTERNAL_STRING)) {
2324 error(ERR_NONFATAL, "`%%depend' expects a file name");
2325 free_tlist(origline);
2326 return DIRECTIVE_FOUND; /* but we did _something_ */
2328 if (t->next)
2329 error(ERR_WARNING|ERR_PASS1,
2330 "trailing garbage after `%%depend' ignored");
2331 p = t->text;
2332 if (t->type != TOK_INTERNAL_STRING)
2333 nasm_unquote(p, NULL);
2334 if (dephead && !in_list(*dephead, p)) {
2335 StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2336 sl->next = NULL;
2337 strcpy(sl->str, p);
2338 *deptail = sl;
2339 deptail = &sl->next;
2341 free_tlist(origline);
2342 return DIRECTIVE_FOUND;
2344 case PP_INCLUDE:
2345 t = tline->next = expand_smacro(tline->next);
2346 skip_white_(t);
2348 if (!t || (t->type != TOK_STRING &&
2349 t->type != TOK_INTERNAL_STRING)) {
2350 error(ERR_NONFATAL, "`%%include' expects a file name");
2351 free_tlist(origline);
2352 return DIRECTIVE_FOUND; /* but we did _something_ */
2354 if (t->next)
2355 error(ERR_WARNING|ERR_PASS1,
2356 "trailing garbage after `%%include' ignored");
2357 p = t->text;
2358 if (t->type != TOK_INTERNAL_STRING)
2359 nasm_unquote(p, NULL);
2360 inc = nasm_malloc(sizeof(Include));
2361 inc->next = istk;
2362 inc->conds = NULL;
2363 inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2364 if (!inc->fp) {
2365 /* -MG given but file not found */
2366 nasm_free(inc);
2367 } else {
2368 inc->fname = src_set_fname(nasm_strdup(p));
2369 inc->lineno = src_set_linnum(0);
2370 inc->lineinc = 1;
2371 inc->expansion = NULL;
2372 inc->mstk = NULL;
2373 istk = inc;
2374 list->uplevel(LIST_INCLUDE);
2376 free_tlist(origline);
2377 return DIRECTIVE_FOUND;
2379 case PP_USE:
2381 static macros_t *use_pkg;
2382 const char *pkg_macro;
2384 tline = tline->next;
2385 skip_white_(tline);
2386 tline = expand_id(tline);
2388 if (!tline || (tline->type != TOK_STRING &&
2389 tline->type != TOK_INTERNAL_STRING &&
2390 tline->type != TOK_ID)) {
2391 error(ERR_NONFATAL, "`%%use' expects a package name");
2392 free_tlist(origline);
2393 return DIRECTIVE_FOUND; /* but we did _something_ */
2395 if (tline->next)
2396 error(ERR_WARNING|ERR_PASS1,
2397 "trailing garbage after `%%use' ignored");
2398 if (tline->type == TOK_STRING)
2399 nasm_unquote(tline->text, NULL);
2400 use_pkg = nasm_stdmac_find_package(tline->text);
2401 if (!use_pkg)
2402 error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2403 /* The first string will be <%define>__USE_*__ */
2404 pkg_macro = (char *)use_pkg + 1;
2405 if (!smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2406 /* Not already included, go ahead and include it */
2407 stdmacpos = use_pkg;
2409 free_tlist(origline);
2410 return DIRECTIVE_FOUND;
2412 case PP_PUSH:
2413 case PP_REPL:
2414 case PP_POP:
2415 tline = tline->next;
2416 skip_white_(tline);
2417 tline = expand_id(tline);
2418 if (tline) {
2419 if (!tok_type_(tline, TOK_ID)) {
2420 error(ERR_NONFATAL, "`%s' expects a context identifier",
2421 pp_directives[i]);
2422 free_tlist(origline);
2423 return DIRECTIVE_FOUND; /* but we did _something_ */
2425 if (tline->next)
2426 error(ERR_WARNING|ERR_PASS1,
2427 "trailing garbage after `%s' ignored",
2428 pp_directives[i]);
2429 p = nasm_strdup(tline->text);
2430 } else {
2431 p = NULL; /* Anonymous */
2434 if (i == PP_PUSH) {
2435 ctx = nasm_malloc(sizeof(Context));
2436 ctx->next = cstk;
2437 hash_init(&ctx->localmac, HASH_SMALL);
2438 ctx->name = p;
2439 ctx->number = unique++;
2440 cstk = ctx;
2441 } else {
2442 /* %pop or %repl */
2443 if (!cstk) {
2444 error(ERR_NONFATAL, "`%s': context stack is empty",
2445 pp_directives[i]);
2446 } else if (i == PP_POP) {
2447 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2448 error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2449 "expected %s",
2450 cstk->name ? cstk->name : "anonymous", p);
2451 else
2452 ctx_pop();
2453 } else {
2454 /* i == PP_REPL */
2455 nasm_free(cstk->name);
2456 cstk->name = p;
2457 p = NULL;
2459 nasm_free(p);
2461 free_tlist(origline);
2462 return DIRECTIVE_FOUND;
2463 case PP_FATAL:
2464 severity = ERR_FATAL;
2465 goto issue_error;
2466 case PP_ERROR:
2467 severity = ERR_NONFATAL;
2468 goto issue_error;
2469 case PP_WARNING:
2470 severity = ERR_WARNING|ERR_WARN_USER;
2471 goto issue_error;
2473 issue_error:
2475 /* Only error out if this is the final pass */
2476 if (pass != 2 && i != PP_FATAL)
2477 return DIRECTIVE_FOUND;
2479 tline->next = expand_smacro(tline->next);
2480 tline = tline->next;
2481 skip_white_(tline);
2482 t = tline ? tline->next : NULL;
2483 skip_white_(t);
2484 if (tok_type_(tline, TOK_STRING) && !t) {
2485 /* The line contains only a quoted string */
2486 p = tline->text;
2487 nasm_unquote(p, NULL);
2488 error(severity, "%s", p);
2489 } else {
2490 /* Not a quoted string, or more than a quoted string */
2491 p = detoken(tline, false);
2492 error(severity, "%s", p);
2493 nasm_free(p);
2495 free_tlist(origline);
2496 return DIRECTIVE_FOUND;
2499 CASE_PP_IF:
2500 if (istk->conds && !emitting(istk->conds->state))
2501 j = COND_NEVER;
2502 else {
2503 j = if_condition(tline->next, i);
2504 tline->next = NULL; /* it got freed */
2505 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2507 cond = nasm_malloc(sizeof(Cond));
2508 cond->next = istk->conds;
2509 cond->state = j;
2510 istk->conds = cond;
2511 free_tlist(origline);
2512 return DIRECTIVE_FOUND;
2514 CASE_PP_ELIF:
2515 if (!istk->conds)
2516 error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2517 switch(istk->conds->state) {
2518 case COND_IF_TRUE:
2519 istk->conds->state = COND_DONE;
2520 break;
2522 case COND_DONE:
2523 case COND_NEVER:
2524 break;
2526 case COND_ELSE_TRUE:
2527 case COND_ELSE_FALSE:
2528 error_precond(ERR_WARNING|ERR_PASS1,
2529 "`%%elif' after `%%else' ignored");
2530 istk->conds->state = COND_NEVER;
2531 break;
2533 case COND_IF_FALSE:
2535 * IMPORTANT: In the case of %if, we will already have
2536 * called expand_mmac_params(); however, if we're
2537 * processing an %elif we must have been in a
2538 * non-emitting mode, which would have inhibited
2539 * the normal invocation of expand_mmac_params().
2540 * Therefore, we have to do it explicitly here.
2542 j = if_condition(expand_mmac_params(tline->next), i);
2543 tline->next = NULL; /* it got freed */
2544 istk->conds->state =
2545 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2546 break;
2548 free_tlist(origline);
2549 return DIRECTIVE_FOUND;
2551 case PP_ELSE:
2552 if (tline->next)
2553 error_precond(ERR_WARNING|ERR_PASS1,
2554 "trailing garbage after `%%else' ignored");
2555 if (!istk->conds)
2556 error(ERR_FATAL, "`%%else': no matching `%%if'");
2557 switch(istk->conds->state) {
2558 case COND_IF_TRUE:
2559 case COND_DONE:
2560 istk->conds->state = COND_ELSE_FALSE;
2561 break;
2563 case COND_NEVER:
2564 break;
2566 case COND_IF_FALSE:
2567 istk->conds->state = COND_ELSE_TRUE;
2568 break;
2570 case COND_ELSE_TRUE:
2571 case COND_ELSE_FALSE:
2572 error_precond(ERR_WARNING|ERR_PASS1,
2573 "`%%else' after `%%else' ignored.");
2574 istk->conds->state = COND_NEVER;
2575 break;
2577 free_tlist(origline);
2578 return DIRECTIVE_FOUND;
2580 case PP_ENDIF:
2581 if (tline->next)
2582 error_precond(ERR_WARNING|ERR_PASS1,
2583 "trailing garbage after `%%endif' ignored");
2584 if (!istk->conds)
2585 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2586 cond = istk->conds;
2587 istk->conds = cond->next;
2588 nasm_free(cond);
2589 free_tlist(origline);
2590 return DIRECTIVE_FOUND;
2592 case PP_RMACRO:
2593 case PP_RIMACRO:
2594 case PP_MACRO:
2595 case PP_IMACRO:
2596 if (defining) {
2597 error(ERR_FATAL,
2598 "`%%%smacro': already defining a macro",
2599 (i == PP_IMACRO ? "i" : ""));
2600 /* todo: change the above as well... */
2601 return DIRECTIVE_FOUND;
2603 defining = nasm_malloc(sizeof(MMacro));
2604 defining->max_depth = (((i == PP_RMACRO) || (i == PP_RIMACRO)) ? 65536 : 0);
2605 defining->casesense = ((i == PP_MACRO) || (i == PP_RMACRO));
2606 if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2607 nasm_free(defining);
2608 defining = NULL;
2609 return DIRECTIVE_FOUND;
2612 mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2613 while (mmac) {
2614 if (!strcmp(mmac->name, defining->name) &&
2615 (mmac->nparam_min <= defining->nparam_max
2616 || defining->plus)
2617 && (defining->nparam_min <= mmac->nparam_max
2618 || mmac->plus)) {
2619 error(ERR_WARNING|ERR_PASS1,
2620 "redefining multi-line macro `%s'", defining->name);
2621 return DIRECTIVE_FOUND;
2623 mmac = mmac->next;
2625 free_tlist(origline);
2626 return DIRECTIVE_FOUND;
2628 case PP_ENDM:
2629 case PP_ENDMACRO:
2630 if (! (defining && defining->name)) {
2631 error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2632 return DIRECTIVE_FOUND;
2634 mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2635 defining->next = *mmhead;
2636 *mmhead = defining;
2637 defining = NULL;
2638 free_tlist(origline);
2639 return DIRECTIVE_FOUND;
2641 case PP_UNMACRO:
2642 case PP_UNIMACRO:
2644 MMacro **mmac_p;
2645 MMacro spec;
2647 spec.casesense = (i == PP_UNMACRO);
2648 if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2649 return DIRECTIVE_FOUND;
2651 mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2652 while (mmac_p && *mmac_p) {
2653 mmac = *mmac_p;
2654 if (mmac->casesense == spec.casesense &&
2655 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2656 mmac->nparam_min == spec.nparam_min &&
2657 mmac->nparam_max == spec.nparam_max &&
2658 mmac->plus == spec.plus) {
2659 *mmac_p = mmac->next;
2660 free_mmacro(mmac);
2661 } else {
2662 mmac_p = &mmac->next;
2665 free_tlist(origline);
2666 free_tlist(spec.dlist);
2667 return DIRECTIVE_FOUND;
2670 case PP_ROTATE:
2671 if (tline->next && tline->next->type == TOK_WHITESPACE)
2672 tline = tline->next;
2673 if (tline->next == NULL) {
2674 free_tlist(origline);
2675 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2676 return DIRECTIVE_FOUND;
2678 t = expand_smacro(tline->next);
2679 tline->next = NULL;
2680 free_tlist(origline);
2681 tline = t;
2682 tptr = &t;
2683 tokval.t_type = TOKEN_INVALID;
2684 evalresult =
2685 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2686 free_tlist(tline);
2687 if (!evalresult)
2688 return DIRECTIVE_FOUND;
2689 if (tokval.t_type)
2690 error(ERR_WARNING|ERR_PASS1,
2691 "trailing garbage after expression ignored");
2692 if (!is_simple(evalresult)) {
2693 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2694 return DIRECTIVE_FOUND;
2696 mmac = istk->mstk;
2697 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2698 mmac = mmac->next_active;
2699 if (!mmac) {
2700 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2701 } else if (mmac->nparam == 0) {
2702 error(ERR_NONFATAL,
2703 "`%%rotate' invoked within macro without parameters");
2704 } else {
2705 int rotate = mmac->rotate + reloc_value(evalresult);
2707 rotate %= (int)mmac->nparam;
2708 if (rotate < 0)
2709 rotate += mmac->nparam;
2711 mmac->rotate = rotate;
2713 return DIRECTIVE_FOUND;
2715 case PP_REP:
2716 nolist = false;
2717 do {
2718 tline = tline->next;
2719 } while (tok_type_(tline, TOK_WHITESPACE));
2721 if (tok_type_(tline, TOK_ID) &&
2722 nasm_stricmp(tline->text, ".nolist") == 0) {
2723 nolist = true;
2724 do {
2725 tline = tline->next;
2726 } while (tok_type_(tline, TOK_WHITESPACE));
2729 if (tline) {
2730 t = expand_smacro(tline);
2731 tptr = &t;
2732 tokval.t_type = TOKEN_INVALID;
2733 evalresult =
2734 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2735 if (!evalresult) {
2736 free_tlist(origline);
2737 return DIRECTIVE_FOUND;
2739 if (tokval.t_type)
2740 error(ERR_WARNING|ERR_PASS1,
2741 "trailing garbage after expression ignored");
2742 if (!is_simple(evalresult)) {
2743 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2744 return DIRECTIVE_FOUND;
2746 count = reloc_value(evalresult) + 1;
2747 } else {
2748 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2749 count = 0;
2751 free_tlist(origline);
2753 tmp_defining = defining;
2754 defining = nasm_malloc(sizeof(MMacro));
2755 defining->prev = NULL;
2756 defining->name = NULL; /* flags this macro as a %rep block */
2757 defining->casesense = false;
2758 defining->plus = false;
2759 defining->nolist = nolist;
2760 defining->in_progress = count;
2761 defining->max_depth = 0;
2762 defining->nparam_min = defining->nparam_max = 0;
2763 defining->defaults = NULL;
2764 defining->dlist = NULL;
2765 defining->expansion = NULL;
2766 defining->next_active = istk->mstk;
2767 defining->rep_nest = tmp_defining;
2768 return DIRECTIVE_FOUND;
2770 case PP_ENDREP:
2771 if (!defining || defining->name) {
2772 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2773 return DIRECTIVE_FOUND;
2777 * Now we have a "macro" defined - although it has no name
2778 * and we won't be entering it in the hash tables - we must
2779 * push a macro-end marker for it on to istk->expansion.
2780 * After that, it will take care of propagating itself (a
2781 * macro-end marker line for a macro which is really a %rep
2782 * block will cause the macro to be re-expanded, complete
2783 * with another macro-end marker to ensure the process
2784 * continues) until the whole expansion is forcibly removed
2785 * from istk->expansion by a %exitrep.
2787 l = nasm_malloc(sizeof(Line));
2788 l->next = istk->expansion;
2789 l->finishes = defining;
2790 l->first = NULL;
2791 istk->expansion = l;
2793 istk->mstk = defining;
2795 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2796 tmp_defining = defining;
2797 defining = defining->rep_nest;
2798 free_tlist(origline);
2799 return DIRECTIVE_FOUND;
2801 case PP_EXITREP:
2803 * We must search along istk->expansion until we hit a
2804 * macro-end marker for a macro with no name. Then we set
2805 * its `in_progress' flag to 0.
2807 for (l = istk->expansion; l; l = l->next)
2808 if (l->finishes && !l->finishes->name)
2809 break;
2811 if (l)
2812 l->finishes->in_progress = 1;
2813 else
2814 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2815 free_tlist(origline);
2816 return DIRECTIVE_FOUND;
2818 case PP_XDEFINE:
2819 case PP_IXDEFINE:
2820 case PP_DEFINE:
2821 case PP_IDEFINE:
2822 casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2824 tline = tline->next;
2825 skip_white_(tline);
2826 tline = expand_id(tline);
2827 if (!tline || (tline->type != TOK_ID &&
2828 (tline->type != TOK_PREPROC_ID ||
2829 tline->text[1] != '$'))) {
2830 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2831 pp_directives[i]);
2832 free_tlist(origline);
2833 return DIRECTIVE_FOUND;
2836 ctx = get_ctx(tline->text, &mname, false);
2837 last = tline;
2838 param_start = tline = tline->next;
2839 nparam = 0;
2841 /* Expand the macro definition now for %xdefine and %ixdefine */
2842 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2843 tline = expand_smacro(tline);
2845 if (tok_is_(tline, "(")) {
2847 * This macro has parameters.
2850 tline = tline->next;
2851 while (1) {
2852 skip_white_(tline);
2853 if (!tline) {
2854 error(ERR_NONFATAL, "parameter identifier expected");
2855 free_tlist(origline);
2856 return DIRECTIVE_FOUND;
2858 if (tline->type != TOK_ID) {
2859 error(ERR_NONFATAL,
2860 "`%s': parameter identifier expected",
2861 tline->text);
2862 free_tlist(origline);
2863 return DIRECTIVE_FOUND;
2865 tline->type = TOK_SMAC_PARAM + nparam++;
2866 tline = tline->next;
2867 skip_white_(tline);
2868 if (tok_is_(tline, ",")) {
2869 tline = tline->next;
2870 } else {
2871 if (!tok_is_(tline, ")")) {
2872 error(ERR_NONFATAL,
2873 "`)' expected to terminate macro template");
2874 free_tlist(origline);
2875 return DIRECTIVE_FOUND;
2877 break;
2880 last = tline;
2881 tline = tline->next;
2883 if (tok_type_(tline, TOK_WHITESPACE))
2884 last = tline, tline = tline->next;
2885 macro_start = NULL;
2886 last->next = NULL;
2887 t = tline;
2888 while (t) {
2889 if (t->type == TOK_ID) {
2890 for (tt = param_start; tt; tt = tt->next)
2891 if (tt->type >= TOK_SMAC_PARAM &&
2892 !strcmp(tt->text, t->text))
2893 t->type = tt->type;
2895 tt = t->next;
2896 t->next = macro_start;
2897 macro_start = t;
2898 t = tt;
2901 * Good. We now have a macro name, a parameter count, and a
2902 * token list (in reverse order) for an expansion. We ought
2903 * to be OK just to create an SMacro, store it, and let
2904 * free_tlist have the rest of the line (which we have
2905 * carefully re-terminated after chopping off the expansion
2906 * from the end).
2908 define_smacro(ctx, mname, casesense, nparam, macro_start);
2909 free_tlist(origline);
2910 return DIRECTIVE_FOUND;
2912 case PP_UNDEF:
2913 tline = tline->next;
2914 skip_white_(tline);
2915 tline = expand_id(tline);
2916 if (!tline || (tline->type != TOK_ID &&
2917 (tline->type != TOK_PREPROC_ID ||
2918 tline->text[1] != '$'))) {
2919 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2920 free_tlist(origline);
2921 return DIRECTIVE_FOUND;
2923 if (tline->next) {
2924 error(ERR_WARNING|ERR_PASS1,
2925 "trailing garbage after macro name ignored");
2928 /* Find the context that symbol belongs to */
2929 ctx = get_ctx(tline->text, &mname, false);
2930 undef_smacro(ctx, mname);
2931 free_tlist(origline);
2932 return DIRECTIVE_FOUND;
2934 case PP_DEFSTR:
2935 case PP_IDEFSTR:
2936 casesense = (i == PP_DEFSTR);
2938 tline = tline->next;
2939 skip_white_(tline);
2940 tline = expand_id(tline);
2941 if (!tline || (tline->type != TOK_ID &&
2942 (tline->type != TOK_PREPROC_ID ||
2943 tline->text[1] != '$'))) {
2944 error(ERR_NONFATAL, "`%s' expects a macro identifier",
2945 pp_directives[i]);
2946 free_tlist(origline);
2947 return DIRECTIVE_FOUND;
2950 ctx = get_ctx(tline->text, &mname, false);
2951 last = tline;
2952 tline = expand_smacro(tline->next);
2953 last->next = NULL;
2955 while (tok_type_(tline, TOK_WHITESPACE))
2956 tline = delete_Token(tline);
2958 p = detoken(tline, false);
2959 macro_start = nasm_malloc(sizeof(*macro_start));
2960 macro_start->next = NULL;
2961 macro_start->text = nasm_quote(p, strlen(p));
2962 macro_start->type = TOK_STRING;
2963 macro_start->a.mac = NULL;
2964 nasm_free(p);
2967 * We now have a macro name, an implicit parameter count of
2968 * zero, and a string token to use as an expansion. Create
2969 * and store an SMacro.
2971 define_smacro(ctx, mname, casesense, 0, macro_start);
2972 free_tlist(origline);
2973 return DIRECTIVE_FOUND;
2975 case PP_PATHSEARCH:
2977 FILE *fp;
2978 StrList *xsl = NULL;
2979 StrList **xst = &xsl;
2981 casesense = true;
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,
2990 "`%%pathsearch' expects a macro identifier as first parameter");
2991 free_tlist(origline);
2992 return DIRECTIVE_FOUND;
2994 ctx = get_ctx(tline->text, &mname, false);
2995 last = tline;
2996 tline = expand_smacro(tline->next);
2997 last->next = NULL;
2999 t = tline;
3000 while (tok_type_(t, TOK_WHITESPACE))
3001 t = t->next;
3003 if (!t || (t->type != TOK_STRING &&
3004 t->type != TOK_INTERNAL_STRING)) {
3005 error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3006 free_tlist(tline);
3007 free_tlist(origline);
3008 return DIRECTIVE_FOUND; /* but we did _something_ */
3010 if (t->next)
3011 error(ERR_WARNING|ERR_PASS1,
3012 "trailing garbage after `%%pathsearch' ignored");
3013 p = t->text;
3014 if (t->type != TOK_INTERNAL_STRING)
3015 nasm_unquote(p, NULL);
3017 fp = inc_fopen(p, &xsl, &xst, true);
3018 if (fp) {
3019 p = xsl->str;
3020 fclose(fp); /* Don't actually care about the file */
3022 macro_start = nasm_malloc(sizeof(*macro_start));
3023 macro_start->next = NULL;
3024 macro_start->text = nasm_quote(p, strlen(p));
3025 macro_start->type = TOK_STRING;
3026 macro_start->a.mac = NULL;
3027 if (xsl)
3028 nasm_free(xsl);
3031 * We now have a macro name, an implicit parameter count of
3032 * zero, and a string token to use as an expansion. Create
3033 * and store an SMacro.
3035 define_smacro(ctx, mname, casesense, 0, macro_start);
3036 free_tlist(tline);
3037 free_tlist(origline);
3038 return DIRECTIVE_FOUND;
3041 case PP_STRLEN:
3042 casesense = true;
3044 tline = tline->next;
3045 skip_white_(tline);
3046 tline = expand_id(tline);
3047 if (!tline || (tline->type != TOK_ID &&
3048 (tline->type != TOK_PREPROC_ID ||
3049 tline->text[1] != '$'))) {
3050 error(ERR_NONFATAL,
3051 "`%%strlen' expects a macro identifier as first parameter");
3052 free_tlist(origline);
3053 return DIRECTIVE_FOUND;
3055 ctx = get_ctx(tline->text, &mname, false);
3056 last = tline;
3057 tline = expand_smacro(tline->next);
3058 last->next = NULL;
3060 t = tline;
3061 while (tok_type_(t, TOK_WHITESPACE))
3062 t = t->next;
3063 /* t should now point to the string */
3064 if (t->type != TOK_STRING) {
3065 error(ERR_NONFATAL,
3066 "`%%strlen` requires string as second parameter");
3067 free_tlist(tline);
3068 free_tlist(origline);
3069 return DIRECTIVE_FOUND;
3072 macro_start = nasm_malloc(sizeof(*macro_start));
3073 macro_start->next = NULL;
3074 make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3075 macro_start->a.mac = NULL;
3078 * We now have a macro name, an implicit parameter count of
3079 * zero, and a numeric token to use as an expansion. Create
3080 * and store an SMacro.
3082 define_smacro(ctx, mname, casesense, 0, macro_start);
3083 free_tlist(tline);
3084 free_tlist(origline);
3085 return DIRECTIVE_FOUND;
3087 case PP_STRCAT:
3088 casesense = true;
3090 tline = tline->next;
3091 skip_white_(tline);
3092 tline = expand_id(tline);
3093 if (!tline || (tline->type != TOK_ID &&
3094 (tline->type != TOK_PREPROC_ID ||
3095 tline->text[1] != '$'))) {
3096 error(ERR_NONFATAL,
3097 "`%%strcat' expects a macro identifier as first parameter");
3098 free_tlist(origline);
3099 return DIRECTIVE_FOUND;
3101 ctx = get_ctx(tline->text, &mname, false);
3102 last = tline;
3103 tline = expand_smacro(tline->next);
3104 last->next = NULL;
3106 len = 0;
3107 for (t = tline; t; t = t->next) {
3108 switch (t->type) {
3109 case TOK_WHITESPACE:
3110 break;
3111 case TOK_STRING:
3112 len += t->a.len = nasm_unquote(t->text, NULL);
3113 break;
3114 case TOK_OTHER:
3115 if (!strcmp(t->text, ",")) /* permit comma separators */
3116 break;
3117 /* else fall through */
3118 default:
3119 error(ERR_NONFATAL,
3120 "non-string passed to `%%strcat' (%d)", t->type);
3121 free_tlist(tline);
3122 free_tlist(origline);
3123 return DIRECTIVE_FOUND;
3127 p = pp = nasm_malloc(len);
3128 t = tline;
3129 for (t = tline; t; t = t->next) {
3130 if (t->type == TOK_STRING) {
3131 memcpy(p, t->text, t->a.len);
3132 p += t->a.len;
3137 * We now have a macro name, an implicit parameter count of
3138 * zero, and a numeric token to use as an expansion. Create
3139 * and store an SMacro.
3141 macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3142 macro_start->text = nasm_quote(pp, len);
3143 nasm_free(pp);
3144 define_smacro(ctx, mname, casesense, 0, macro_start);
3145 free_tlist(tline);
3146 free_tlist(origline);
3147 return DIRECTIVE_FOUND;
3149 case PP_SUBSTR:
3151 int64_t a1, a2;
3152 size_t len;
3154 casesense = true;
3156 tline = tline->next;
3157 skip_white_(tline);
3158 tline = expand_id(tline);
3159 if (!tline || (tline->type != TOK_ID &&
3160 (tline->type != TOK_PREPROC_ID ||
3161 tline->text[1] != '$'))) {
3162 error(ERR_NONFATAL,
3163 "`%%substr' expects a macro identifier as first parameter");
3164 free_tlist(origline);
3165 return DIRECTIVE_FOUND;
3167 ctx = get_ctx(tline->text, &mname, false);
3168 last = tline;
3169 tline = expand_smacro(tline->next);
3170 last->next = NULL;
3172 t = tline->next;
3173 while (tok_type_(t, TOK_WHITESPACE))
3174 t = t->next;
3176 /* t should now point to the string */
3177 if (t->type != TOK_STRING) {
3178 error(ERR_NONFATAL,
3179 "`%%substr` requires string as second parameter");
3180 free_tlist(tline);
3181 free_tlist(origline);
3182 return DIRECTIVE_FOUND;
3185 tt = t->next;
3186 tptr = &tt;
3187 tokval.t_type = TOKEN_INVALID;
3188 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3189 pass, error, NULL);
3190 if (!evalresult) {
3191 free_tlist(tline);
3192 free_tlist(origline);
3193 return DIRECTIVE_FOUND;
3194 } else if (!is_simple(evalresult)) {
3195 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3196 free_tlist(tline);
3197 free_tlist(origline);
3198 return DIRECTIVE_FOUND;
3200 a1 = evalresult->value-1;
3202 while (tok_type_(tt, TOK_WHITESPACE))
3203 tt = tt->next;
3204 if (!tt) {
3205 a2 = 1; /* Backwards compatibility: one character */
3206 } else {
3207 tokval.t_type = TOKEN_INVALID;
3208 evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3209 pass, error, NULL);
3210 if (!evalresult) {
3211 free_tlist(tline);
3212 free_tlist(origline);
3213 return DIRECTIVE_FOUND;
3214 } else if (!is_simple(evalresult)) {
3215 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3216 free_tlist(tline);
3217 free_tlist(origline);
3218 return DIRECTIVE_FOUND;
3220 a2 = evalresult->value;
3223 len = nasm_unquote(t->text, NULL);
3224 if (a2 < 0)
3225 a2 = a2+1+len-a1;
3226 if (a1+a2 > (int64_t)len)
3227 a2 = len-a1;
3229 macro_start = nasm_malloc(sizeof(*macro_start));
3230 macro_start->next = NULL;
3231 macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3232 macro_start->type = TOK_STRING;
3233 macro_start->a.mac = NULL;
3236 * We now have a macro name, an implicit parameter count of
3237 * zero, and a numeric token to use as an expansion. Create
3238 * and store an SMacro.
3240 define_smacro(ctx, mname, casesense, 0, macro_start);
3241 free_tlist(tline);
3242 free_tlist(origline);
3243 return DIRECTIVE_FOUND;
3246 case PP_ASSIGN:
3247 case PP_IASSIGN:
3248 casesense = (i == PP_ASSIGN);
3250 tline = tline->next;
3251 skip_white_(tline);
3252 tline = expand_id(tline);
3253 if (!tline || (tline->type != TOK_ID &&
3254 (tline->type != TOK_PREPROC_ID ||
3255 tline->text[1] != '$'))) {
3256 error(ERR_NONFATAL,
3257 "`%%%sassign' expects a macro identifier",
3258 (i == PP_IASSIGN ? "i" : ""));
3259 free_tlist(origline);
3260 return DIRECTIVE_FOUND;
3262 ctx = get_ctx(tline->text, &mname, false);
3263 last = tline;
3264 tline = expand_smacro(tline->next);
3265 last->next = NULL;
3267 t = tline;
3268 tptr = &t;
3269 tokval.t_type = TOKEN_INVALID;
3270 evalresult =
3271 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3272 free_tlist(tline);
3273 if (!evalresult) {
3274 free_tlist(origline);
3275 return DIRECTIVE_FOUND;
3278 if (tokval.t_type)
3279 error(ERR_WARNING|ERR_PASS1,
3280 "trailing garbage after expression ignored");
3282 if (!is_simple(evalresult)) {
3283 error(ERR_NONFATAL,
3284 "non-constant value given to `%%%sassign'",
3285 (i == PP_IASSIGN ? "i" : ""));
3286 free_tlist(origline);
3287 return DIRECTIVE_FOUND;
3290 macro_start = nasm_malloc(sizeof(*macro_start));
3291 macro_start->next = NULL;
3292 make_tok_num(macro_start, reloc_value(evalresult));
3293 macro_start->a.mac = NULL;
3296 * We now have a macro name, an implicit parameter count of
3297 * zero, and a numeric token to use as an expansion. Create
3298 * and store an SMacro.
3300 define_smacro(ctx, mname, casesense, 0, macro_start);
3301 free_tlist(origline);
3302 return DIRECTIVE_FOUND;
3304 case PP_LINE:
3306 * Syntax is `%line nnn[+mmm] [filename]'
3308 tline = tline->next;
3309 skip_white_(tline);
3310 if (!tok_type_(tline, TOK_NUMBER)) {
3311 error(ERR_NONFATAL, "`%%line' expects line number");
3312 free_tlist(origline);
3313 return DIRECTIVE_FOUND;
3315 k = readnum(tline->text, &err);
3316 m = 1;
3317 tline = tline->next;
3318 if (tok_is_(tline, "+")) {
3319 tline = tline->next;
3320 if (!tok_type_(tline, TOK_NUMBER)) {
3321 error(ERR_NONFATAL, "`%%line' expects line increment");
3322 free_tlist(origline);
3323 return DIRECTIVE_FOUND;
3325 m = readnum(tline->text, &err);
3326 tline = tline->next;
3328 skip_white_(tline);
3329 src_set_linnum(k);
3330 istk->lineinc = m;
3331 if (tline) {
3332 nasm_free(src_set_fname(detoken(tline, false)));
3334 free_tlist(origline);
3335 return DIRECTIVE_FOUND;
3337 default:
3338 error(ERR_FATAL,
3339 "preprocessor directive `%s' not yet implemented",
3340 pp_directives[i]);
3341 return DIRECTIVE_FOUND;
3346 * Ensure that a macro parameter contains a condition code and
3347 * nothing else. Return the condition code index if so, or -1
3348 * otherwise.
3350 static int find_cc(Token * t)
3352 Token *tt;
3353 int i, j, k, m;
3355 if (!t)
3356 return -1; /* Probably a %+ without a space */
3358 skip_white_(t);
3359 if (t->type != TOK_ID)
3360 return -1;
3361 tt = t->next;
3362 skip_white_(tt);
3363 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3364 return -1;
3366 i = -1;
3367 j = elements(conditions);
3368 while (j - i > 1) {
3369 k = (j + i) / 2;
3370 m = nasm_stricmp(t->text, conditions[k]);
3371 if (m == 0) {
3372 i = k;
3373 j = -2;
3374 break;
3375 } else if (m < 0) {
3376 j = k;
3377 } else
3378 i = k;
3380 if (j != -2)
3381 return -1;
3382 return i;
3385 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3387 Token **tail, *t, *tt;
3388 Token **paste_head;
3389 bool did_paste = false;
3390 char *tmp;
3392 /* Now handle token pasting... */
3393 paste_head = NULL;
3394 tail = head;
3395 while ((t = *tail) && (tt = t->next)) {
3396 switch (t->type) {
3397 case TOK_WHITESPACE:
3398 if (tt->type == TOK_WHITESPACE) {
3399 /* Zap adjacent whitespace tokens */
3400 t->next = delete_Token(tt);
3401 } else {
3402 /* Do not advance paste_head here */
3403 tail = &t->next;
3405 break;
3406 case TOK_ID:
3407 case TOK_PREPROC_ID:
3408 case TOK_NUMBER:
3409 case TOK_FLOAT:
3411 size_t len = 0;
3412 char *tmp, *p;
3414 while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3415 tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3416 tt->type == TOK_OTHER)) {
3417 len += strlen(tt->text);
3418 tt = tt->next;
3421 /* Now tt points to the first token after the potential
3422 paste area... */
3423 if (tt != t->next) {
3424 /* We have at least two tokens... */
3425 len += strlen(t->text);
3426 p = tmp = nasm_malloc(len+1);
3428 while (t != tt) {
3429 strcpy(p, t->text);
3430 p = strchr(p, '\0');
3431 t = delete_Token(t);
3434 t = *tail = tokenize(tmp);
3435 nasm_free(tmp);
3437 while (t->next) {
3438 tail = &t->next;
3439 t = t->next;
3441 t->next = tt; /* Attach the remaining token chain */
3443 did_paste = true;
3445 paste_head = tail;
3446 tail = &t->next;
3447 break;
3449 case TOK_PASTE: /* %+ */
3450 if (handle_paste_tokens) {
3451 /* Zap %+ and whitespace tokens to the right */
3452 while (t && (t->type == TOK_WHITESPACE ||
3453 t->type == TOK_PASTE))
3454 t = *tail = delete_Token(t);
3455 if (!paste_head || !t)
3456 break; /* Nothing to paste with */
3457 tail = paste_head;
3458 t = *tail;
3459 tt = t->next;
3460 while (tok_type_(tt, TOK_WHITESPACE))
3461 tt = t->next = delete_Token(tt);
3463 if (tt) {
3464 tmp = nasm_strcat(t->text, tt->text);
3465 delete_Token(t);
3466 tt = delete_Token(tt);
3467 t = *tail = tokenize(tmp);
3468 nasm_free(tmp);
3469 while (t->next) {
3470 tail = &t->next;
3471 t = t->next;
3473 t->next = tt; /* Attach the remaining token chain */
3474 did_paste = true;
3476 paste_head = tail;
3477 tail = &t->next;
3478 break;
3480 /* else fall through */
3481 default:
3482 tail = paste_head = &t->next;
3483 break;
3486 return did_paste;
3489 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3490 * %-n) and MMacro-local identifiers (%%foo) as well as
3491 * macro indirection (%[...]).
3493 static Token *expand_mmac_params(Token * tline)
3495 Token *t, *tt, **tail, *thead;
3496 bool changed = false;
3498 tail = &thead;
3499 thead = NULL;
3501 while (tline) {
3502 if (tline->type == TOK_PREPROC_ID &&
3503 (((tline->text[1] == '+' || tline->text[1] == '-')
3504 && tline->text[2]) || tline->text[1] == '%'
3505 || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
3506 char *text = NULL;
3507 int type = 0, cc; /* type = 0 to placate optimisers */
3508 char tmpbuf[30];
3509 unsigned int n;
3510 int i;
3511 MMacro *mac;
3513 t = tline;
3514 tline = tline->next;
3516 mac = istk->mstk;
3517 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3518 mac = mac->next_active;
3519 if (!mac)
3520 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3521 else
3522 switch (t->text[1]) {
3524 * We have to make a substitution of one of the
3525 * forms %1, %-1, %+1, %%foo, %0.
3527 case '0':
3528 type = TOK_NUMBER;
3529 snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3530 text = nasm_strdup(tmpbuf);
3531 break;
3532 case '%':
3533 type = TOK_ID;
3534 snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3535 mac->unique);
3536 text = nasm_strcat(tmpbuf, t->text + 2);
3537 break;
3538 case '-':
3539 n = atoi(t->text + 2) - 1;
3540 if (n >= mac->nparam)
3541 tt = NULL;
3542 else {
3543 if (mac->nparam > 1)
3544 n = (n + mac->rotate) % mac->nparam;
3545 tt = mac->params[n];
3547 cc = find_cc(tt);
3548 if (cc == -1) {
3549 error(ERR_NONFATAL,
3550 "macro parameter %d is not a condition code",
3551 n + 1);
3552 text = NULL;
3553 } else {
3554 type = TOK_ID;
3555 if (inverse_ccs[cc] == -1) {
3556 error(ERR_NONFATAL,
3557 "condition code `%s' is not invertible",
3558 conditions[cc]);
3559 text = NULL;
3560 } else
3561 text = nasm_strdup(conditions[inverse_ccs[cc]]);
3563 break;
3564 case '+':
3565 n = atoi(t->text + 2) - 1;
3566 if (n >= mac->nparam)
3567 tt = NULL;
3568 else {
3569 if (mac->nparam > 1)
3570 n = (n + mac->rotate) % mac->nparam;
3571 tt = mac->params[n];
3573 cc = find_cc(tt);
3574 if (cc == -1) {
3575 error(ERR_NONFATAL,
3576 "macro parameter %d is not a condition code",
3577 n + 1);
3578 text = NULL;
3579 } else {
3580 type = TOK_ID;
3581 text = nasm_strdup(conditions[cc]);
3583 break;
3584 default:
3585 n = atoi(t->text + 1) - 1;
3586 if (n >= mac->nparam)
3587 tt = NULL;
3588 else {
3589 if (mac->nparam > 1)
3590 n = (n + mac->rotate) % mac->nparam;
3591 tt = mac->params[n];
3593 if (tt) {
3594 for (i = 0; i < mac->paramlen[n]; i++) {
3595 *tail = new_Token(NULL, tt->type, tt->text, 0);
3596 tail = &(*tail)->next;
3597 tt = tt->next;
3600 text = NULL; /* we've done it here */
3601 break;
3603 if (!text) {
3604 delete_Token(t);
3605 } else {
3606 *tail = t;
3607 tail = &t->next;
3608 t->type = type;
3609 nasm_free(t->text);
3610 t->text = text;
3611 t->a.mac = NULL;
3613 changed = true;
3614 continue;
3615 } else if (tline->type == TOK_INDIRECT) {
3616 t = tline;
3617 tline = tline->next;
3618 tt = tokenize(t->text);
3619 tt = expand_mmac_params(tt);
3620 tt = expand_smacro(tt);
3621 *tail = tt;
3622 while (tt) {
3623 tt->a.mac = NULL; /* Necessary? */
3624 tail = &tt->next;
3625 tt = tt->next;
3627 delete_Token(t);
3628 changed = true;
3629 } else {
3630 t = *tail = tline;
3631 tline = tline->next;
3632 t->a.mac = NULL;
3633 tail = &t->next;
3636 *tail = NULL;
3638 if (changed)
3639 paste_tokens(&thead, false);
3641 return thead;
3645 * Expand all single-line macro calls made in the given line.
3646 * Return the expanded version of the line. The original is deemed
3647 * to be destroyed in the process. (In reality we'll just move
3648 * Tokens from input to output a lot of the time, rather than
3649 * actually bothering to destroy and replicate.)
3651 #define DEADMAN_LIMIT (1 << 20)
3653 static Token *expand_smacro(Token * tline)
3655 Token *t, *tt, *mstart, **tail, *thead;
3656 struct hash_table *smtbl;
3657 SMacro *head = NULL, *m;
3658 Token **params;
3659 int *paramsize;
3660 unsigned int nparam, sparam;
3661 int brackets;
3662 Token *org_tline = tline;
3663 Context *ctx;
3664 const char *mname;
3665 int deadman = DEADMAN_LIMIT;
3666 bool expanded;
3669 * Trick: we should avoid changing the start token pointer since it can
3670 * be contained in "next" field of other token. Because of this
3671 * we allocate a copy of first token and work with it; at the end of
3672 * routine we copy it back
3674 if (org_tline) {
3675 tline =
3676 new_Token(org_tline->next, org_tline->type, org_tline->text,
3678 tline->a.mac = org_tline->a.mac;
3679 nasm_free(org_tline->text);
3680 org_tline->text = NULL;
3683 expanded = true; /* Always expand %+ at least once */
3685 again:
3686 tail = &thead;
3687 thead = NULL;
3689 while (tline) { /* main token loop */
3690 if (!--deadman) {
3691 error(ERR_NONFATAL, "interminable macro recursion");
3692 break;
3695 if ((mname = tline->text)) {
3696 /* if this token is a local macro, look in local context */
3697 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3698 ctx = get_ctx(mname, &mname, true);
3699 else
3700 ctx = NULL;
3701 smtbl = ctx ? &ctx->localmac : &smacros;
3702 head = (SMacro *) hash_findix(smtbl, mname);
3705 * We've hit an identifier. As in is_mmacro below, we first
3706 * check whether the identifier is a single-line macro at
3707 * all, then think about checking for parameters if
3708 * necessary.
3710 for (m = head; m; m = m->next)
3711 if (!mstrcmp(m->name, mname, m->casesense))
3712 break;
3713 if (m) {
3714 mstart = tline;
3715 params = NULL;
3716 paramsize = NULL;
3717 if (m->nparam == 0) {
3719 * Simple case: the macro is parameterless. Discard the
3720 * one token that the macro call took, and push the
3721 * expansion back on the to-do stack.
3723 if (!m->expansion) {
3724 if (!strcmp("__FILE__", m->name)) {
3725 int32_t num = 0;
3726 char *file = NULL;
3727 src_get(&num, &file);
3728 tline->text = nasm_quote(file, strlen(file));
3729 tline->type = TOK_STRING;
3730 nasm_free(file);
3731 continue;
3733 if (!strcmp("__LINE__", m->name)) {
3734 nasm_free(tline->text);
3735 make_tok_num(tline, src_get_linnum());
3736 continue;
3738 if (!strcmp("__BITS__", m->name)) {
3739 nasm_free(tline->text);
3740 make_tok_num(tline, globalbits);
3741 continue;
3743 tline = delete_Token(tline);
3744 continue;
3746 } else {
3748 * Complicated case: at least one macro with this name
3749 * exists and takes parameters. We must find the
3750 * parameters in the call, count them, find the SMacro
3751 * that corresponds to that form of the macro call, and
3752 * substitute for the parameters when we expand. What a
3753 * pain.
3755 /*tline = tline->next;
3756 skip_white_(tline); */
3757 do {
3758 t = tline->next;
3759 while (tok_type_(t, TOK_SMAC_END)) {
3760 t->a.mac->in_progress = false;
3761 t->text = NULL;
3762 t = tline->next = delete_Token(t);
3764 tline = t;
3765 } while (tok_type_(tline, TOK_WHITESPACE));
3766 if (!tok_is_(tline, "(")) {
3768 * This macro wasn't called with parameters: ignore
3769 * the call. (Behaviour borrowed from gnu cpp.)
3771 tline = mstart;
3772 m = NULL;
3773 } else {
3774 int paren = 0;
3775 int white = 0;
3776 brackets = 0;
3777 nparam = 0;
3778 sparam = PARAM_DELTA;
3779 params = nasm_malloc(sparam * sizeof(Token *));
3780 params[0] = tline->next;
3781 paramsize = nasm_malloc(sparam * sizeof(int));
3782 paramsize[0] = 0;
3783 while (true) { /* parameter loop */
3785 * For some unusual expansions
3786 * which concatenates function call
3788 t = tline->next;
3789 while (tok_type_(t, TOK_SMAC_END)) {
3790 t->a.mac->in_progress = false;
3791 t->text = NULL;
3792 t = tline->next = delete_Token(t);
3794 tline = t;
3796 if (!tline) {
3797 error(ERR_NONFATAL,
3798 "macro call expects terminating `)'");
3799 break;
3801 if (tline->type == TOK_WHITESPACE
3802 && brackets <= 0) {
3803 if (paramsize[nparam])
3804 white++;
3805 else
3806 params[nparam] = tline->next;
3807 continue; /* parameter loop */
3809 if (tline->type == TOK_OTHER
3810 && tline->text[1] == 0) {
3811 char ch = tline->text[0];
3812 if (ch == ',' && !paren && brackets <= 0) {
3813 if (++nparam >= sparam) {
3814 sparam += PARAM_DELTA;
3815 params = nasm_realloc(params,
3816 sparam *
3817 sizeof(Token
3818 *));
3819 paramsize =
3820 nasm_realloc(paramsize,
3821 sparam *
3822 sizeof(int));
3824 params[nparam] = tline->next;
3825 paramsize[nparam] = 0;
3826 white = 0;
3827 continue; /* parameter loop */
3829 if (ch == '{' &&
3830 (brackets > 0 || (brackets == 0 &&
3831 !paramsize[nparam])))
3833 if (!(brackets++)) {
3834 params[nparam] = tline->next;
3835 continue; /* parameter loop */
3838 if (ch == '}' && brackets > 0)
3839 if (--brackets == 0) {
3840 brackets = -1;
3841 continue; /* parameter loop */
3843 if (ch == '(' && !brackets)
3844 paren++;
3845 if (ch == ')' && brackets <= 0)
3846 if (--paren < 0)
3847 break;
3849 if (brackets < 0) {
3850 brackets = 0;
3851 error(ERR_NONFATAL, "braces do not "
3852 "enclose all of macro parameter");
3854 paramsize[nparam] += white + 1;
3855 white = 0;
3856 } /* parameter loop */
3857 nparam++;
3858 while (m && (m->nparam != nparam ||
3859 mstrcmp(m->name, mname,
3860 m->casesense)))
3861 m = m->next;
3862 if (!m)
3863 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
3864 "macro `%s' exists, "
3865 "but not taking %d parameters",
3866 mstart->text, nparam);
3869 if (m && m->in_progress)
3870 m = NULL;
3871 if (!m) { /* in progess or didn't find '(' or wrong nparam */
3873 * Design question: should we handle !tline, which
3874 * indicates missing ')' here, or expand those
3875 * macros anyway, which requires the (t) test a few
3876 * lines down?
3878 nasm_free(params);
3879 nasm_free(paramsize);
3880 tline = mstart;
3881 } else {
3883 * Expand the macro: we are placed on the last token of the
3884 * call, so that we can easily split the call from the
3885 * following tokens. We also start by pushing an SMAC_END
3886 * token for the cycle removal.
3888 t = tline;
3889 if (t) {
3890 tline = t->next;
3891 t->next = NULL;
3893 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3894 tt->a.mac = m;
3895 m->in_progress = true;
3896 tline = tt;
3897 for (t = m->expansion; t; t = t->next) {
3898 if (t->type >= TOK_SMAC_PARAM) {
3899 Token *pcopy = tline, **ptail = &pcopy;
3900 Token *ttt, *pt;
3901 int i;
3903 ttt = params[t->type - TOK_SMAC_PARAM];
3904 for (i = paramsize[t->type - TOK_SMAC_PARAM];
3905 --i >= 0;) {
3906 pt = *ptail =
3907 new_Token(tline, ttt->type, ttt->text,
3909 ptail = &pt->next;
3910 ttt = ttt->next;
3912 tline = pcopy;
3913 } else if (t->type == TOK_PREPROC_Q) {
3914 tt = new_Token(tline, TOK_ID, mname, 0);
3915 tline = tt;
3916 } else if (t->type == TOK_PREPROC_QQ) {
3917 tt = new_Token(tline, TOK_ID, m->name, 0);
3918 tline = tt;
3919 } else {
3920 tt = new_Token(tline, t->type, t->text, 0);
3921 tline = tt;
3926 * Having done that, get rid of the macro call, and clean
3927 * up the parameters.
3929 nasm_free(params);
3930 nasm_free(paramsize);
3931 free_tlist(mstart);
3932 expanded = true;
3933 continue; /* main token loop */
3938 if (tline->type == TOK_SMAC_END) {
3939 tline->a.mac->in_progress = false;
3940 tline = delete_Token(tline);
3941 } else {
3942 t = *tail = tline;
3943 tline = tline->next;
3944 t->a.mac = NULL;
3945 t->next = NULL;
3946 tail = &t->next;
3951 * Now scan the entire line and look for successive TOK_IDs that resulted
3952 * after expansion (they can't be produced by tokenize()). The successive
3953 * TOK_IDs should be concatenated.
3954 * Also we look for %+ tokens and concatenate the tokens before and after
3955 * them (without white spaces in between).
3957 if (expanded && paste_tokens(&thead, true)) {
3959 * If we concatenated something, *and* we had previously expanded
3960 * an actual macro, scan the lines again for macros...
3962 tline = thead;
3963 expanded = false;
3964 goto again;
3967 if (org_tline) {
3968 if (thead) {
3969 *org_tline = *thead;
3970 /* since we just gave text to org_line, don't free it */
3971 thead->text = NULL;
3972 delete_Token(thead);
3973 } else {
3974 /* the expression expanded to empty line;
3975 we can't return NULL for some reasons
3976 we just set the line to a single WHITESPACE token. */
3977 memset(org_tline, 0, sizeof(*org_tline));
3978 org_tline->text = NULL;
3979 org_tline->type = TOK_WHITESPACE;
3981 thead = org_tline;
3984 return thead;
3988 * Similar to expand_smacro but used exclusively with macro identifiers
3989 * right before they are fetched in. The reason is that there can be
3990 * identifiers consisting of several subparts. We consider that if there
3991 * are more than one element forming the name, user wants a expansion,
3992 * otherwise it will be left as-is. Example:
3994 * %define %$abc cde
3996 * the identifier %$abc will be left as-is so that the handler for %define
3997 * will suck it and define the corresponding value. Other case:
3999 * %define _%$abc cde
4001 * In this case user wants name to be expanded *before* %define starts
4002 * working, so we'll expand %$abc into something (if it has a value;
4003 * otherwise it will be left as-is) then concatenate all successive
4004 * PP_IDs into one.
4006 static Token *expand_id(Token * tline)
4008 Token *cur, *oldnext = NULL;
4010 if (!tline || !tline->next)
4011 return tline;
4013 cur = tline;
4014 while (cur->next &&
4015 (cur->next->type == TOK_ID ||
4016 cur->next->type == TOK_PREPROC_ID
4017 || cur->next->type == TOK_NUMBER))
4018 cur = cur->next;
4020 /* If identifier consists of just one token, don't expand */
4021 if (cur == tline)
4022 return tline;
4024 if (cur) {
4025 oldnext = cur->next; /* Detach the tail past identifier */
4026 cur->next = NULL; /* so that expand_smacro stops here */
4029 tline = expand_smacro(tline);
4031 if (cur) {
4032 /* expand_smacro possibly changhed tline; re-scan for EOL */
4033 cur = tline;
4034 while (cur && cur->next)
4035 cur = cur->next;
4036 if (cur)
4037 cur->next = oldnext;
4040 return tline;
4044 * Determine whether the given line constitutes a multi-line macro
4045 * call, and return the MMacro structure called if so. Doesn't have
4046 * to check for an initial label - that's taken care of in
4047 * expand_mmacro - but must check numbers of parameters. Guaranteed
4048 * to be called with tline->type == TOK_ID, so the putative macro
4049 * name is easy to find.
4051 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4053 MMacro *head, *m;
4054 Token **params;
4055 int nparam;
4057 head = (MMacro *) hash_findix(&mmacros, tline->text);
4060 * Efficiency: first we see if any macro exists with the given
4061 * name. If not, we can return NULL immediately. _Then_ we
4062 * count the parameters, and then we look further along the
4063 * list if necessary to find the proper MMacro.
4065 for (m = head; m; m = m->next)
4066 if (!mstrcmp(m->name, tline->text, m->casesense))
4067 break;
4068 if (!m)
4069 return NULL;
4072 * OK, we have a potential macro. Count and demarcate the
4073 * parameters.
4075 count_mmac_params(tline->next, &nparam, &params);
4078 * So we know how many parameters we've got. Find the MMacro
4079 * structure that handles this number.
4081 while (m) {
4082 if (m->nparam_min <= nparam
4083 && (m->plus || nparam <= m->nparam_max)) {
4085 * This one is right. Just check if cycle removal
4086 * prohibits us using it before we actually celebrate...
4088 if (m->in_progress > m->max_depth) {
4089 if (m->max_depth > 0) {
4090 error(ERR_WARNING,
4091 "reached maximum recursion depth of %i",
4092 m->max_depth);
4094 nasm_free(params);
4095 return NULL;
4098 * It's right, and we can use it. Add its default
4099 * parameters to the end of our list if necessary.
4101 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4102 params =
4103 nasm_realloc(params,
4104 ((m->nparam_min + m->ndefs +
4105 1) * sizeof(*params)));
4106 while (nparam < m->nparam_min + m->ndefs) {
4107 params[nparam] = m->defaults[nparam - m->nparam_min];
4108 nparam++;
4112 * If we've gone over the maximum parameter count (and
4113 * we're in Plus mode), ignore parameters beyond
4114 * nparam_max.
4116 if (m->plus && nparam > m->nparam_max)
4117 nparam = m->nparam_max;
4119 * Then terminate the parameter list, and leave.
4121 if (!params) { /* need this special case */
4122 params = nasm_malloc(sizeof(*params));
4123 nparam = 0;
4125 params[nparam] = NULL;
4126 *params_array = params;
4127 return m;
4130 * This one wasn't right: look for the next one with the
4131 * same name.
4133 for (m = m->next; m; m = m->next)
4134 if (!mstrcmp(m->name, tline->text, m->casesense))
4135 break;
4139 * After all that, we didn't find one with the right number of
4140 * parameters. Issue a warning, and fail to expand the macro.
4142 error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4143 "macro `%s' exists, but not taking %d parameters",
4144 tline->text, nparam);
4145 nasm_free(params);
4146 return NULL;
4151 * Save MMacro invocation specific fields in
4152 * preparation for a recursive macro expansion
4154 static void push_mmacro(MMacro *m)
4156 MMacroInvocation *i;
4158 i = nasm_malloc(sizeof(MMacroInvocation));
4159 i->prev = m->prev;
4160 i->params = m->params;
4161 i->iline = m->iline;
4162 i->nparam = m->nparam;
4163 i->rotate = m->rotate;
4164 i->paramlen = m->paramlen;
4165 i->unique = m->unique;
4166 m->prev = i;
4171 * Restore MMacro invocation specific fields that were
4172 * saved during a previous recursive macro expansion
4174 static void pop_mmacro(MMacro *m)
4176 MMacroInvocation *i;
4178 if(m->prev != NULL){
4179 i = m->prev;
4180 m->prev = i->prev;
4181 m->params = i->params;
4182 m->iline = i->iline;
4183 m->nparam = i->nparam;
4184 m->rotate = i->rotate;
4185 m->paramlen = i->paramlen;
4186 m->unique = i->unique;
4187 nasm_free(i);
4193 * Expand the multi-line macro call made by the given line, if
4194 * there is one to be expanded. If there is, push the expansion on
4195 * istk->expansion and return 1. Otherwise return 0.
4197 static int expand_mmacro(Token * tline)
4199 Token *startline = tline;
4200 Token *label = NULL;
4201 int dont_prepend = 0;
4202 Token **params, *t, *mtok, *tt;
4203 MMacro *m;
4204 Line *l, *ll;
4205 int i, nparam, *paramlen;
4206 const char *mname;
4208 t = tline;
4209 skip_white_(t);
4210 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4211 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4212 return 0;
4213 mtok = t;
4214 m = is_mmacro(t, &params);
4215 if (m) {
4216 mname = t->text;
4217 } else {
4218 Token *last;
4220 * We have an id which isn't a macro call. We'll assume
4221 * it might be a label; we'll also check to see if a
4222 * colon follows it. Then, if there's another id after
4223 * that lot, we'll check it again for macro-hood.
4225 label = last = t;
4226 t = t->next;
4227 if (tok_type_(t, TOK_WHITESPACE))
4228 last = t, t = t->next;
4229 if (tok_is_(t, ":")) {
4230 dont_prepend = 1;
4231 last = t, t = t->next;
4232 if (tok_type_(t, TOK_WHITESPACE))
4233 last = t, t = t->next;
4235 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
4236 return 0;
4237 last->next = NULL;
4238 mname = t->text;
4239 tline = t;
4243 * Fix up the parameters: this involves stripping leading and
4244 * trailing whitespace, then stripping braces if they are
4245 * present.
4247 for (nparam = 0; params[nparam]; nparam++) ;
4248 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4250 for (i = 0; params[i]; i++) {
4251 int brace = false;
4252 int comma = (!m->plus || i < nparam - 1);
4254 t = params[i];
4255 skip_white_(t);
4256 if (tok_is_(t, "{"))
4257 t = t->next, brace = true, comma = false;
4258 params[i] = t;
4259 paramlen[i] = 0;
4260 while (t) {
4261 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4262 break; /* ... because we have hit a comma */
4263 if (comma && t->type == TOK_WHITESPACE
4264 && tok_is_(t->next, ","))
4265 break; /* ... or a space then a comma */
4266 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4267 break; /* ... or a brace */
4268 t = t->next;
4269 paramlen[i]++;
4274 * OK, we have a MMacro structure together with a set of
4275 * parameters. We must now go through the expansion and push
4276 * copies of each Line on to istk->expansion. Substitution of
4277 * parameter tokens and macro-local tokens doesn't get done
4278 * until the single-line macro substitution process; this is
4279 * because delaying them allows us to change the semantics
4280 * later through %rotate.
4282 * First, push an end marker on to istk->expansion, mark this
4283 * macro as in progress, and set up its invocation-specific
4284 * variables.
4286 ll = nasm_malloc(sizeof(Line));
4287 ll->next = istk->expansion;
4288 ll->finishes = m;
4289 ll->first = NULL;
4290 istk->expansion = ll;
4293 * Save the previous MMacro expansion in the case of
4294 * macro recursion
4296 if (m->max_depth && m->in_progress)
4297 push_mmacro(m);
4299 m->in_progress ++;
4300 m->params = params;
4301 m->iline = tline;
4302 m->nparam = nparam;
4303 m->rotate = 0;
4304 m->paramlen = paramlen;
4305 m->unique = unique++;
4306 m->lineno = 0;
4308 m->next_active = istk->mstk;
4309 istk->mstk = m;
4311 for (l = m->expansion; l; l = l->next) {
4312 Token **tail;
4314 ll = nasm_malloc(sizeof(Line));
4315 ll->finishes = NULL;
4316 ll->next = istk->expansion;
4317 istk->expansion = ll;
4318 tail = &ll->first;
4320 for (t = l->first; t; t = t->next) {
4321 Token *x = t;
4322 switch (t->type) {
4323 case TOK_PREPROC_Q:
4324 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4325 break;
4326 case TOK_PREPROC_QQ:
4327 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4328 break;
4329 case TOK_PREPROC_ID:
4330 if (t->text[1] == '0' && t->text[2] == '0') {
4331 dont_prepend = -1;
4332 x = label;
4333 if (!x)
4334 continue;
4336 /* fall through */
4337 default:
4338 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4339 break;
4341 tail = &tt->next;
4343 *tail = NULL;
4347 * If we had a label, push it on as the first line of
4348 * the macro expansion.
4350 if (label) {
4351 if (dont_prepend < 0)
4352 free_tlist(startline);
4353 else {
4354 ll = nasm_malloc(sizeof(Line));
4355 ll->finishes = NULL;
4356 ll->next = istk->expansion;
4357 istk->expansion = ll;
4358 ll->first = startline;
4359 if (!dont_prepend) {
4360 while (label->next)
4361 label = label->next;
4362 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4367 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4369 return 1;
4372 /* The function that actually does the error reporting */
4373 static void verror(int severity, const char *fmt, va_list arg)
4375 char buff[1024];
4377 vsnprintf(buff, sizeof(buff), fmt, arg);
4379 if (istk && istk->mstk && istk->mstk->name)
4380 _error(severity, "(%s:%d) %s", istk->mstk->name,
4381 istk->mstk->lineno, buff);
4382 else
4383 _error(severity, "%s", buff);
4387 * Since preprocessor always operate only on the line that didn't
4388 * arrived yet, we should always use ERR_OFFBY1.
4390 static void error(int severity, const char *fmt, ...)
4392 va_list arg;
4394 /* If we're in a dead branch of IF or something like it, ignore the error */
4395 if (istk && istk->conds && !emitting(istk->conds->state))
4396 return;
4398 va_start(arg, fmt);
4399 verror(severity, fmt, arg);
4400 va_end(arg);
4404 * Because %else etc are evaluated in the state context
4405 * of the previous branch, errors might get lost with error():
4406 * %if 0 ... %else trailing garbage ... %endif
4407 * So %else etc should report errors with this function.
4409 static void error_precond(int severity, const char *fmt, ...)
4411 va_list arg;
4413 /* Only ignore the error if it's really in a dead branch */
4414 if (istk && istk->conds && istk->conds->state == COND_NEVER)
4415 return;
4417 va_start(arg, fmt);
4418 verror(severity, fmt, arg);
4419 va_end(arg);
4422 static void
4423 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
4424 ListGen * listgen, StrList **deplist)
4426 Token *t;
4428 _error = errfunc;
4429 cstk = NULL;
4430 istk = nasm_malloc(sizeof(Include));
4431 istk->next = NULL;
4432 istk->conds = NULL;
4433 istk->expansion = NULL;
4434 istk->mstk = NULL;
4435 istk->fp = fopen(file, "r");
4436 istk->fname = NULL;
4437 src_set_fname(nasm_strdup(file));
4438 src_set_linnum(0);
4439 istk->lineinc = 1;
4440 if (!istk->fp)
4441 error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4442 file);
4443 defining = NULL;
4444 nested_mac_count = 0;
4445 nested_rep_count = 0;
4446 init_macros();
4447 unique = 0;
4448 if (tasm_compatible_mode) {
4449 stdmacpos = nasm_stdmac;
4450 } else {
4451 stdmacpos = nasm_stdmac_after_tasm;
4453 any_extrastdmac = extrastdmac && *extrastdmac;
4454 do_predef = true;
4455 list = listgen;
4456 evaluate = eval;
4459 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4460 * The caller, however, will also pass in 3 for preprocess-only so
4461 * we can set __PASS__ accordingly.
4463 pass = apass > 2 ? 2 : apass;
4465 dephead = deptail = deplist;
4466 if (deplist) {
4467 StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4468 sl->next = NULL;
4469 strcpy(sl->str, file);
4470 *deptail = sl;
4471 deptail = &sl->next;
4475 * Define the __PASS__ macro. This is defined here unlike
4476 * all the other builtins, because it is special -- it varies between
4477 * passes.
4479 t = nasm_malloc(sizeof(*t));
4480 t->next = NULL;
4481 make_tok_num(t, apass);
4482 t->a.mac = NULL;
4483 define_smacro(NULL, "__PASS__", true, 0, t);
4486 static char *pp_getline(void)
4488 char *line;
4489 Token *tline;
4491 while (1) {
4493 * Fetch a tokenized line, either from the macro-expansion
4494 * buffer or from the input file.
4496 tline = NULL;
4497 while (istk->expansion && istk->expansion->finishes) {
4498 Line *l = istk->expansion;
4499 if (!l->finishes->name && l->finishes->in_progress > 1) {
4500 Line *ll;
4503 * This is a macro-end marker for a macro with no
4504 * name, which means it's not really a macro at all
4505 * but a %rep block, and the `in_progress' field is
4506 * more than 1, meaning that we still need to
4507 * repeat. (1 means the natural last repetition; 0
4508 * means termination by %exitrep.) We have
4509 * therefore expanded up to the %endrep, and must
4510 * push the whole block on to the expansion buffer
4511 * again. We don't bother to remove the macro-end
4512 * marker: we'd only have to generate another one
4513 * if we did.
4515 l->finishes->in_progress--;
4516 for (l = l->finishes->expansion; l; l = l->next) {
4517 Token *t, *tt, **tail;
4519 ll = nasm_malloc(sizeof(Line));
4520 ll->next = istk->expansion;
4521 ll->finishes = NULL;
4522 ll->first = NULL;
4523 tail = &ll->first;
4525 for (t = l->first; t; t = t->next) {
4526 if (t->text || t->type == TOK_WHITESPACE) {
4527 tt = *tail =
4528 new_Token(NULL, t->type, t->text, 0);
4529 tail = &tt->next;
4533 istk->expansion = ll;
4535 } else {
4537 * Check whether a `%rep' was started and not ended
4538 * within this macro expansion. This can happen and
4539 * should be detected. It's a fatal error because
4540 * I'm too confused to work out how to recover
4541 * sensibly from it.
4543 if (defining) {
4544 if (defining->name)
4545 error(ERR_PANIC,
4546 "defining with name in expansion");
4547 else if (istk->mstk->name)
4548 error(ERR_FATAL,
4549 "`%%rep' without `%%endrep' within"
4550 " expansion of macro `%s'",
4551 istk->mstk->name);
4555 * FIXME: investigate the relationship at this point between
4556 * istk->mstk and l->finishes
4559 MMacro *m = istk->mstk;
4560 istk->mstk = m->next_active;
4561 if (m->name) {
4563 * This was a real macro call, not a %rep, and
4564 * therefore the parameter information needs to
4565 * be freed.
4567 if (m->prev != NULL) {
4568 pop_mmacro(m);
4569 } else {
4570 nasm_free(m->params);
4571 free_tlist(m->iline);
4572 nasm_free(m->paramlen);
4574 l->finishes->in_progress --;
4575 } else
4576 free_mmacro(m);
4578 istk->expansion = l->next;
4579 nasm_free(l);
4580 list->downlevel(LIST_MACRO);
4583 while (1) { /* until we get a line we can use */
4585 if (istk->expansion) { /* from a macro expansion */
4586 char *p;
4587 Line *l = istk->expansion;
4588 if (istk->mstk)
4589 istk->mstk->lineno++;
4590 tline = l->first;
4591 istk->expansion = l->next;
4592 nasm_free(l);
4593 p = detoken(tline, false);
4594 list->line(LIST_MACRO, p);
4595 nasm_free(p);
4596 break;
4598 line = read_line();
4599 if (line) { /* from the current input file */
4600 line = prepreproc(line);
4601 tline = tokenize(line);
4602 nasm_free(line);
4603 break;
4606 * The current file has ended; work down the istk
4609 Include *i = istk;
4610 fclose(i->fp);
4611 if (i->conds)
4612 error(ERR_FATAL,
4613 "expected `%%endif' before end of file");
4614 /* only set line and file name if there's a next node */
4615 if (i->next) {
4616 src_set_linnum(i->lineno);
4617 nasm_free(src_set_fname(i->fname));
4619 istk = i->next;
4620 list->downlevel(LIST_INCLUDE);
4621 nasm_free(i);
4622 if (!istk)
4623 return NULL;
4624 if (istk->expansion && istk->expansion->finishes)
4625 break;
4630 * We must expand MMacro parameters and MMacro-local labels
4631 * _before_ we plunge into directive processing, to cope
4632 * with things like `%define something %1' such as STRUC
4633 * uses. Unless we're _defining_ a MMacro, in which case
4634 * those tokens should be left alone to go into the
4635 * definition; and unless we're in a non-emitting
4636 * condition, in which case we don't want to meddle with
4637 * anything.
4639 if (!defining && !(istk->conds && !emitting(istk->conds->state))
4640 && !(istk->mstk && !istk->mstk->in_progress)) {
4641 tline = expand_mmac_params(tline);
4645 * Check the line to see if it's a preprocessor directive.
4647 if (do_directive(tline) == DIRECTIVE_FOUND) {
4648 continue;
4649 } else if (defining) {
4651 * We're defining a multi-line macro. We emit nothing
4652 * at all, and just
4653 * shove the tokenized line on to the macro definition.
4655 Line *l = nasm_malloc(sizeof(Line));
4656 l->next = defining->expansion;
4657 l->first = tline;
4658 l->finishes = NULL;
4659 defining->expansion = l;
4660 continue;
4661 } else if (istk->conds && !emitting(istk->conds->state)) {
4663 * We're in a non-emitting branch of a condition block.
4664 * Emit nothing at all, not even a blank line: when we
4665 * emerge from the condition we'll give a line-number
4666 * directive so we keep our place correctly.
4668 free_tlist(tline);
4669 continue;
4670 } else if (istk->mstk && !istk->mstk->in_progress) {
4672 * We're in a %rep block which has been terminated, so
4673 * we're walking through to the %endrep without
4674 * emitting anything. Emit nothing at all, not even a
4675 * blank line: when we emerge from the %rep block we'll
4676 * give a line-number directive so we keep our place
4677 * correctly.
4679 free_tlist(tline);
4680 continue;
4681 } else {
4682 tline = expand_smacro(tline);
4683 if (!expand_mmacro(tline)) {
4685 * De-tokenize the line again, and emit it.
4687 line = detoken(tline, true);
4688 free_tlist(tline);
4689 break;
4690 } else {
4691 continue; /* expand_mmacro calls free_tlist */
4696 return line;
4699 static void pp_cleanup(int pass)
4701 if (defining) {
4702 if(defining->name) {
4703 error(ERR_NONFATAL,
4704 "end of file while still defining macro `%s'",
4705 defining->name);
4706 } else {
4707 error(ERR_NONFATAL, "end of file while still in %%rep");
4710 free_mmacro(defining);
4712 while (cstk)
4713 ctx_pop();
4714 free_macros();
4715 while (istk) {
4716 Include *i = istk;
4717 istk = istk->next;
4718 fclose(i->fp);
4719 nasm_free(i->fname);
4720 nasm_free(i);
4722 while (cstk)
4723 ctx_pop();
4724 nasm_free(src_set_fname(NULL));
4725 if (pass == 0) {
4726 IncPath *i;
4727 free_llist(predef);
4728 delete_Blocks();
4729 while ((i = ipath)) {
4730 ipath = i->next;
4731 if (i->path)
4732 nasm_free(i->path);
4733 nasm_free(i);
4738 void pp_include_path(char *path)
4740 IncPath *i;
4742 i = nasm_malloc(sizeof(IncPath));
4743 i->path = path ? nasm_strdup(path) : NULL;
4744 i->next = NULL;
4746 if (ipath != NULL) {
4747 IncPath *j = ipath;
4748 while (j->next != NULL)
4749 j = j->next;
4750 j->next = i;
4751 } else {
4752 ipath = i;
4756 void pp_pre_include(char *fname)
4758 Token *inc, *space, *name;
4759 Line *l;
4761 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4762 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4763 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4765 l = nasm_malloc(sizeof(Line));
4766 l->next = predef;
4767 l->first = inc;
4768 l->finishes = NULL;
4769 predef = l;
4772 void pp_pre_define(char *definition)
4774 Token *def, *space;
4775 Line *l;
4776 char *equals;
4778 equals = strchr(definition, '=');
4779 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4780 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4781 if (equals)
4782 *equals = ' ';
4783 space->next = tokenize(definition);
4784 if (equals)
4785 *equals = '=';
4787 l = nasm_malloc(sizeof(Line));
4788 l->next = predef;
4789 l->first = def;
4790 l->finishes = NULL;
4791 predef = l;
4794 void pp_pre_undefine(char *definition)
4796 Token *def, *space;
4797 Line *l;
4799 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4800 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4801 space->next = tokenize(definition);
4803 l = nasm_malloc(sizeof(Line));
4804 l->next = predef;
4805 l->first = def;
4806 l->finishes = NULL;
4807 predef = l;
4811 * Added by Keith Kanios:
4813 * This function is used to assist with "runtime" preprocessor
4814 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4816 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4817 * PASS A VALID STRING TO THIS FUNCTION!!!!!
4820 void pp_runtime(char *definition)
4822 Token *def;
4824 def = tokenize(definition);
4825 if(do_directive(def) == NO_DIRECTIVE_FOUND)
4826 free_tlist(def);
4830 void pp_extra_stdmac(macros_t *macros)
4832 extrastdmac = macros;
4835 static void make_tok_num(Token * tok, int64_t val)
4837 char numbuf[20];
4838 snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4839 tok->text = nasm_strdup(numbuf);
4840 tok->type = TOK_NUMBER;
4843 Preproc nasmpp = {
4844 pp_reset,
4845 pp_getline,
4846 pp_cleanup