preproc: add %[i]deftok support
[platform/upstream/nasm.git] / preproc.c
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.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following
9  *   conditions are met:
10  *
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.
17  *     
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.
31  *
32  * ----------------------------------------------------------------------- */
33
34 /*
35  * preproc.c   macro preprocessor for the Netwide Assembler
36  */
37
38 /* Typical flow of text through preproc
39  *
40  * pp_getline gets tokenized lines, either
41  *
42  *   from a macro expansion
43  *
44  * or
45  *   {
46  *   read_line  gets raw text from stdmacpos, or predef, or current input file
47  *   tokenize   converts to tokens
48  *   }
49  *
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
53  *
54  * do_directive checks for directives
55  *
56  * expand_smacro is used to expand single line macros
57  *
58  * expand_mmacro is used to expand multi-line macros
59  *
60  * detoken is used to convert the line back to text
61  */
62
63 #include "compiler.h"
64
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>
73
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"
82
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;
93
94 /*
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.
101  */
102
103 /*
104  * Store the definition of a single-line macro.
105  */
106 struct SMacro {
107     SMacro *next;
108     char *name;
109     bool casesense;
110     bool in_progress;
111     unsigned int nparam;
112     Token *expansion;
113 };
114
115 /*
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.
121  *
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.
125  *
126  * The `next' field is used for storing MMacros in hash tables; the
127  * `next_active' field is for stacking them on istk entries.
128  *
129  * When a MMacro is being expanded, `params', `iline', `nparam',
130  * `paramlen', `rotate' and `unique' are local to the invocation.
131  */
132 struct MMacro {
133     MMacro *next;
134         MMacroInvocation *prev;      /* previous invocation */
135     char *name;
136     int nparam_min, nparam_max;
137     bool casesense;
138     bool plus;                   /* is the last parameter greedy? */
139     bool nolist;                 /* is this macro listing-inhibited? */
140     int64_t in_progress;         /* is this macro currently being expanded? */
141         int32_t max_depth;           /* maximum number of recursive expansions allowed */
142     Token *dlist;               /* All defaults as one list */
143     Token **defaults;           /* Parameter default pointers */
144     int ndefs;                  /* number of default parameters */
145     Line *expansion;
146
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 */
155 };
156
157
158 /* Store the definition of a multi-line macro, as defined in a
159  * previous recursive macro expansion.
160  */
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;
168 };
169
170
171 /*
172  * The context stack is composed of a linked list of these.
173  */
174 struct Context {
175     Context *next;
176     char *name;
177     struct hash_table localmac;
178     uint32_t number;
179 };
180
181 /*
182  * This is the internal form which we break input lines up into.
183  * Typically stored in linked lists.
184  *
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
188  *
189  *     %define a(x,y) ( (x) & ~(y) )
190  *
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.
194  *
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.
199  */
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 */
210 };
211
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;
220 };
221
222 /*
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.
226  *
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...
236  *
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.
243  */
244 struct Line {
245     Line *next;
246     MMacro *finishes;
247     Token *first;
248 };
249
250 /*
251  * To handle an arbitrary level of file inclusion, we maintain a
252  * stack (ie linked list) of these things.
253  */
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 */
262 };
263
264 /*
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.
268  */
269 struct IncPath {
270     IncPath *next;
271     char *path;
272 };
273
274 /*
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.)
280  */
281 struct Cond {
282     Cond *next;
283     int state;
284 };
285 enum {
286     /*
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.)
293      */
294     COND_IF_TRUE, COND_IF_FALSE,
295     /*
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.
299      */
300     COND_ELSE_TRUE, COND_ELSE_FALSE,
301     /*
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.
309      */
310     COND_DONE, COND_NEVER
311 };
312 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
313
314 /*
315  * These defines are used as the possible return values for do_directive
316  */
317 #define NO_DIRECTIVE_FOUND  0
318 #define DIRECTIVE_FOUND     1
319
320 /*
321  * This define sets the upper limit for smacro and recursive mmacro
322  * expansions
323  */
324 #define DEADMAN_LIMIT (1 << 20)
325
326 /*
327  * Condition codes. Note that we use c_ prefix not C_ because C_ is
328  * used in nasm.h for the "real" condition codes. At _this_ level,
329  * we treat CXZ and ECXZ as condition codes, albeit non-invertible
330  * ones, so we need a different enum...
331  */
332 static const char * const conditions[] = {
333     "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
334     "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
335     "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
336 };
337 enum pp_conds {
338     c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
339     c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
340     c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_RCXZ, c_S, c_Z,
341     c_none = -1
342 };
343 static const enum pp_conds inverse_ccs[] = {
344     c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
345     c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
346     c_Z, c_NO, c_NP, c_PO, c_PE, -1, c_NS, c_NZ
347 };
348
349 /*
350  * Directive names.
351  */
352 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
353 static int is_condition(enum preproc_token arg)
354 {
355     return PP_IS_COND(arg) || (arg == PP_ELSE) || (arg == PP_ENDIF);
356 }
357
358 /* For TASM compatibility we need to be able to recognise TASM compatible
359  * conditional compilation directives. Using the NASM pre-processor does
360  * not work, so we look for them specifically from the following list and
361  * then jam in the equivalent NASM directive into the input stream.
362  */
363
364 enum {
365     TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
366     TM_IFNDEF, TM_INCLUDE, TM_LOCAL
367 };
368
369 static const char * const tasm_directives[] = {
370     "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
371     "ifndef", "include", "local"
372 };
373
374 static int StackSize = 4;
375 static char *StackPointer = "ebp";
376 static int ArgOffset = 8;
377 static int LocalOffset = 0;
378
379 static Context *cstk;
380 static Include *istk;
381 static IncPath *ipath = NULL;
382
383 static efunc _error;            /* Pointer to client-provided error reporting function */
384 static evalfunc evaluate;
385
386 static int pass;                /* HACK: pass 0 = generate dependencies only */
387 static StrList **dephead, **deptail; /* Dependency list */
388
389 static uint64_t unique;    /* unique identifier numbers */
390
391 static Line *predef = NULL;
392 static bool do_predef;
393
394 static ListGen *list;
395
396 /*
397  * The current set of multi-line macros we have defined.
398  */
399 static struct hash_table mmacros;
400
401 /*
402  * The current set of single-line macros we have defined.
403  */
404 static struct hash_table smacros;
405
406 /*
407  * The multi-line macro we are currently defining, or the %rep
408  * block we are currently reading, if any.
409  */
410 static MMacro *defining;
411
412 static uint64_t nested_mac_count;
413 static uint64_t nested_rep_count;
414
415 /*
416  * The number of macro parameters to allocate space for at a time.
417  */
418 #define PARAM_DELTA 16
419
420 /*
421  * The standard macro set: defined in macros.c in the array nasm_stdmac.
422  * This gives our position in the macro set, when we're processing it.
423  */
424 static macros_t *stdmacpos;
425
426 /*
427  * The extra standard macros that come from the object format, if
428  * any.
429  */
430 static macros_t *extrastdmac = NULL;
431 static bool any_extrastdmac;
432
433 /*
434  * Tokens are allocated in blocks to improve speed
435  */
436 #define TOKEN_BLOCKSIZE 4096
437 static Token *freeTokens = NULL;
438 struct Blocks {
439     Blocks *next;
440     void *chunk;
441 };
442
443 static Blocks blocks = { NULL, NULL };
444
445 /*
446  * Forward declarations.
447  */
448 static Token *expand_mmac_params(Token * tline);
449 static Token *expand_smacro(Token * tline);
450 static Token *expand_id(Token * tline);
451 static Context *get_ctx(const char *name, const char **namep,
452                         bool all_contexts);
453 static void make_tok_num(Token * tok, int64_t val);
454 static void error(int severity, const char *fmt, ...);
455 static void error_precond(int severity, const char *fmt, ...);
456 static void *new_Block(size_t size);
457 static void delete_Blocks(void);
458 static Token *new_Token(Token * next, enum pp_token_type type,
459                         const char *text, int txtlen);
460 static Token *delete_Token(Token * t);
461
462 /*
463  * Macros for safe checking of token pointers, avoid *(NULL)
464  */
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
469
470 /* Handle TASM specific directives, which do not contain a % in
471  * front of them. We do it here because I could not find any other
472  * place to do it for the moment, and it is a hack (ideally it would
473  * be nice to be able to use the NASM pre-processor to do it).
474  */
475 static char *check_tasm_directive(char *line)
476 {
477     int32_t i, j, k, m, len;
478     char *p = line, *oldline, oldchar;
479
480     /* Skip whitespace */
481     while (nasm_isspace(*p) && *p != 0)
482         p++;
483
484     /* Binary search for the directive name */
485     i = -1;
486     j = elements(tasm_directives);
487     len = 0;
488     while (!nasm_isspace(p[len]) && p[len] != 0)
489         len++;
490     if (len) {
491         oldchar = p[len];
492         p[len] = 0;
493         while (j - i > 1) {
494             k = (j + i) / 2;
495             m = nasm_stricmp(p, tasm_directives[k]);
496             if (m == 0) {
497                 /* We have found a directive, so jam a % in front of it
498                  * so that NASM will then recognise it as one if it's own.
499                  */
500                 p[len] = oldchar;
501                 len = strlen(p);
502                 oldline = line;
503                 line = nasm_malloc(len + 2);
504                 line[0] = '%';
505                 if (k == TM_IFDIFI) {
506                     /*
507                      * NASM does not recognise IFDIFI, so we convert
508                      * it to %if 0. This is not used in NASM
509                      * compatible code, but does need to parse for the
510                      * TASM macro package.
511                      */
512                     strcpy(line + 1, "if 0");
513                 } else {
514                     memcpy(line + 1, p, len + 1);
515                 }
516                 nasm_free(oldline);
517                 return line;
518             } else if (m < 0) {
519                 j = k;
520             } else
521                 i = k;
522         }
523         p[len] = oldchar;
524     }
525     return line;
526 }
527
528 /*
529  * The pre-preprocessing stage... This function translates line
530  * number indications as they emerge from GNU cpp (`# lineno "file"
531  * flags') into NASM preprocessor line number indications (`%line
532  * lineno file').
533  */
534 static char *prepreproc(char *line)
535 {
536     int lineno, fnlen;
537     char *fname, *oldline;
538
539     if (line[0] == '#' && line[1] == ' ') {
540         oldline = line;
541         fname = oldline + 2;
542         lineno = atoi(fname);
543         fname += strspn(fname, "0123456789 ");
544         if (*fname == '"')
545             fname++;
546         fnlen = strcspn(fname, "\"");
547         line = nasm_malloc(20 + fnlen);
548         snprintf(line, 20 + fnlen, "%%line %d %.*s", lineno, fnlen, fname);
549         nasm_free(oldline);
550     }
551     if (tasm_compatible_mode)
552         return check_tasm_directive(line);
553     return line;
554 }
555
556 /*
557  * Free a linked list of tokens.
558  */
559 static void free_tlist(Token * list)
560 {
561     while (list) {
562         list = delete_Token(list);
563     }
564 }
565
566 /*
567  * Free a linked list of lines.
568  */
569 static void free_llist(Line * list)
570 {
571     Line *l;
572     while (list) {
573         l = list;
574         list = list->next;
575         free_tlist(l->first);
576         nasm_free(l);
577     }
578 }
579
580 /*
581  * Free an MMacro
582  */
583 static void free_mmacro(MMacro * m)
584 {
585     nasm_free(m->name);
586     free_tlist(m->dlist);
587     nasm_free(m->defaults);
588     free_llist(m->expansion);
589     nasm_free(m);
590 }
591
592 /*
593  * Free all currently defined macros, and free the hash tables
594  */
595 static void free_smacro_table(struct hash_table *smt)
596 {
597     SMacro *s;
598     const char *key;
599     struct hash_tbl_node *it = NULL;
600
601     while ((s = hash_iterate(smt, &it, &key)) != NULL) {
602         nasm_free((void *)key);
603         while (s) {
604             SMacro *ns = s->next;
605             nasm_free(s->name);
606             free_tlist(s->expansion);
607             nasm_free(s);
608             s = ns;
609         }
610     }
611     hash_free(smt);
612 }
613
614 static void free_mmacro_table(struct hash_table *mmt)
615 {
616     MMacro *m;
617     const char *key;
618     struct hash_tbl_node *it = NULL;
619
620     it = NULL;
621     while ((m = hash_iterate(mmt, &it, &key)) != NULL) {
622         nasm_free((void *)key);
623         while (m) {
624             MMacro *nm = m->next;
625             free_mmacro(m);
626             m = nm;
627         }
628     }
629     hash_free(mmt);
630 }
631
632 static void free_macros(void)
633 {
634     free_smacro_table(&smacros);
635     free_mmacro_table(&mmacros);
636 }
637
638 /*
639  * Initialize the hash tables
640  */
641 static void init_macros(void)
642 {
643     hash_init(&smacros, HASH_LARGE);
644     hash_init(&mmacros, HASH_LARGE);
645 }
646
647 /*
648  * Pop the context stack.
649  */
650 static void ctx_pop(void)
651 {
652     Context *c = cstk;
653
654     cstk = cstk->next;
655     free_smacro_table(&c->localmac);
656     nasm_free(c->name);
657     nasm_free(c);
658 }
659
660 /*
661  * Search for a key in the hash index; adding it if necessary
662  * (in which case we initialize the data pointer to NULL.)
663  */
664 static void **
665 hash_findi_add(struct hash_table *hash, const char *str)
666 {
667     struct hash_insert hi;
668     void **r;
669     char *strx;
670
671     r = hash_findi(hash, str, &hi);
672     if (r)
673         return r;
674
675     strx = nasm_strdup(str);    /* Use a more efficient allocator here? */
676     return hash_add(&hi, strx, NULL);
677 }
678
679 /*
680  * Like hash_findi, but returns the data element rather than a pointer
681  * to it.  Used only when not adding a new element, hence no third
682  * argument.
683  */
684 static void *
685 hash_findix(struct hash_table *hash, const char *str)
686 {
687     void **p;
688
689     p = hash_findi(hash, str, NULL);
690     return p ? *p : NULL;
691 }
692
693 #define BUF_DELTA 512
694 /*
695  * Read a line from the top file in istk, handling multiple CR/LFs
696  * at the end of the line read, and handling spurious ^Zs. Will
697  * return lines from the standard macro set if this has not already
698  * been done.
699  */
700 static char *read_line(void)
701 {
702     char *buffer, *p, *q;
703     int bufsize, continued_count;
704
705     if (stdmacpos) {
706         unsigned char c;
707         const unsigned char *p = stdmacpos;
708         char *ret, *q;
709         size_t len = 0;
710         while ((c = *p++)) {
711             if (c >= 0x80)
712                 len += pp_directives_len[c-0x80]+1;
713             else
714                 len++;
715         }
716         ret = nasm_malloc(len+1);
717         q = ret;
718         while ((c = *stdmacpos++)) {
719             if (c >= 0x80) {
720                 memcpy(q, pp_directives[c-0x80], pp_directives_len[c-0x80]);
721                 q += pp_directives_len[c-0x80];
722                 *q++ = ' ';
723             } else {
724                 *q++ = c;
725             }
726         }
727         stdmacpos = p;
728         *q = '\0';
729
730         if (!*stdmacpos) {
731             /* This was the last of the standard macro chain... */
732             stdmacpos = NULL;
733             if (any_extrastdmac) {
734                 stdmacpos = extrastdmac;
735                 any_extrastdmac = false;
736             } else if (do_predef) {
737                 Line *pd, *l;
738                 Token *head, **tail, *t;
739
740                 /*
741                  * Nasty hack: here we push the contents of
742                  * `predef' on to the top-level expansion stack,
743                  * since this is the most convenient way to
744                  * implement the pre-include and pre-define
745                  * features.
746                  */
747                 for (pd = predef; pd; pd = pd->next) {
748                     head = NULL;
749                     tail = &head;
750                     for (t = pd->first; t; t = t->next) {
751                         *tail = new_Token(NULL, t->type, t->text, 0);
752                         tail = &(*tail)->next;
753                     }
754                     l = nasm_malloc(sizeof(Line));
755                     l->next = istk->expansion;
756                     l->first = head;
757                     l->finishes = NULL;
758                     istk->expansion = l;
759                 }
760                 do_predef = false;
761             }
762         }
763         return ret;
764     }
765
766     bufsize = BUF_DELTA;
767     buffer = nasm_malloc(BUF_DELTA);
768     p = buffer;
769     continued_count = 0;
770     while (1) {
771         q = fgets(p, bufsize - (p - buffer), istk->fp);
772         if (!q)
773             break;
774         p += strlen(p);
775         if (p > buffer && p[-1] == '\n') {
776             /* Convert backslash-CRLF line continuation sequences into
777                nothing at all (for DOS and Windows) */
778             if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
779                 p -= 3;
780                 *p = 0;
781                 continued_count++;
782             }
783             /* Also convert backslash-LF line continuation sequences into
784                nothing at all (for Unix) */
785             else if (((p - 1) > buffer) && (p[-2] == '\\')) {
786                 p -= 2;
787                 *p = 0;
788                 continued_count++;
789             } else {
790                 break;
791             }
792         }
793         if (p - buffer > bufsize - 10) {
794             int32_t offset = p - buffer;
795             bufsize += BUF_DELTA;
796             buffer = nasm_realloc(buffer, bufsize);
797             p = buffer + offset;        /* prevent stale-pointer problems */
798         }
799     }
800
801     if (!q && p == buffer) {
802         nasm_free(buffer);
803         return NULL;
804     }
805
806     src_set_linnum(src_get_linnum() + istk->lineinc +
807                    (continued_count * istk->lineinc));
808
809     /*
810      * Play safe: remove CRs as well as LFs, if any of either are
811      * present at the end of the line.
812      */
813     while (--p >= buffer && (*p == '\n' || *p == '\r'))
814         *p = '\0';
815
816     /*
817      * Handle spurious ^Z, which may be inserted into source files
818      * by some file transfer utilities.
819      */
820     buffer[strcspn(buffer, "\032")] = '\0';
821
822     list->line(LIST_READ, buffer);
823
824     return buffer;
825 }
826
827 /*
828  * Tokenize a line of text. This is a very simple process since we
829  * don't need to parse the value out of e.g. numeric tokens: we
830  * simply split one string into many.
831  */
832 static Token *tokenize(char *line)
833 {
834     char c, *p = line;
835     enum pp_token_type type;
836     Token *list = NULL;
837     Token *t, **tail = &list;
838
839     while (*line) {
840         p = line;
841         if (*p == '%') {
842             p++;
843             if (*p == '+' && !nasm_isdigit(p[1])) {
844                 p++;
845                 type = TOK_PASTE;
846             } else if (nasm_isdigit(*p) ||
847                        ((*p == '-' || *p == '+') && nasm_isdigit(p[1]))) {
848                 do {
849                     p++;
850                 }
851                 while (nasm_isdigit(*p));
852                 type = TOK_PREPROC_ID;
853             } else if (*p == '{') {
854                 p++;
855                 while (*p && *p != '}') {
856                     p[-1] = *p;
857                     p++;
858                 }
859                 p[-1] = '\0';
860                 if (*p)
861                     p++;
862                 type = TOK_PREPROC_ID;
863             } else if (*p == '[') {
864                 int lvl = 1;
865                 line += 2;      /* Skip the leading %[ */
866                 p++;
867                 while (lvl && (c = *p++)) {
868                     switch (c) {
869                     case ']':
870                         lvl--;
871                         break;
872                     case '%':
873                         if (*p == '[')
874                             lvl++;
875                         break;
876                     case '\'':
877                     case '\"':
878                     case '`':
879                         p = nasm_skip_string(p)+1;
880                         break;
881                     default:
882                         break;
883                     }
884                 }
885                 p--;
886                 if (*p)
887                     *p++ = '\0';
888                 if (lvl)
889                     error(ERR_NONFATAL, "unterminated %[ construct");
890                 type = TOK_INDIRECT;
891             } else if (*p == '?') {
892                 type = TOK_PREPROC_Q; /* %? */
893                 p++;
894                 if (*p == '?') {
895                     type = TOK_PREPROC_QQ; /* %?? */
896                     p++;
897                 }
898             } else if (isidchar(*p) ||
899                        ((*p == '!' || *p == '%' || *p == '$') &&
900                         isidchar(p[1]))) {
901                 do {
902                     p++;
903                 }
904                 while (isidchar(*p));
905                 type = TOK_PREPROC_ID;
906             } else {
907                 type = TOK_OTHER;
908                 if (*p == '%')
909                     p++;
910             }
911         } else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
912             type = TOK_ID;
913             p++;
914             while (*p && isidchar(*p))
915                 p++;
916         } else if (*p == '\'' || *p == '"' || *p == '`') {
917             /*
918              * A string token.
919              */
920             type = TOK_STRING;
921             p = nasm_skip_string(p);
922
923             if (*p) {
924                 p++;
925             } else {
926                 error(ERR_WARNING|ERR_PASS1, "unterminated string");
927                 /* Handling unterminated strings by UNV */
928                 /* type = -1; */
929             }
930         } else if (p[0] == '$' && p[1] == '$') {
931             type = TOK_OTHER;   /* TOKEN_BASE */
932             p += 2;
933         } else if (isnumstart(*p)) {
934             bool is_hex = false;
935             bool is_float = false;
936             bool has_e = false;
937             char c, *r;
938
939             /*
940              * A numeric token.
941              */
942
943             if (*p == '$') {
944                 p++;
945                 is_hex = true;
946             }
947
948             for (;;) {
949                 c = *p++;
950
951                 if (!is_hex && (c == 'e' || c == 'E')) {
952                     has_e = true;
953                     if (*p == '+' || *p == '-') {
954                         /* e can only be followed by +/- if it is either a
955                            prefixed hex number or a floating-point number */
956                         p++;
957                         is_float = true;
958                     }
959                 } else if (c == 'H' || c == 'h' || c == 'X' || c == 'x') {
960                     is_hex = true;
961                 } else if (c == 'P' || c == 'p') {
962                     is_float = true;
963                     if (*p == '+' || *p == '-')
964                         p++;
965                 } else if (isnumchar(c) || c == '_')
966                     ; /* just advance */
967                 else if (c == '.') {
968                     /* we need to deal with consequences of the legacy
969                        parser, like "1.nolist" being two tokens
970                        (TOK_NUMBER, TOK_ID) here; at least give it
971                        a shot for now.  In the future, we probably need
972                        a flex-based scanner with proper pattern matching
973                        to do it as well as it can be done.  Nothing in
974                        the world is going to help the person who wants
975                        0x123.p16 interpreted as two tokens, though. */
976                     r = p;
977                     while (*r == '_')
978                         r++;
979
980                     if (nasm_isdigit(*r) || (is_hex && nasm_isxdigit(*r)) ||
981                         (!is_hex && (*r == 'e' || *r == 'E')) ||
982                         (*r == 'p' || *r == 'P')) {
983                         p = r;
984                         is_float = true;
985                     } else
986                         break;  /* Terminate the token */
987                 } else
988                     break;
989             }
990             p--;        /* Point to first character beyond number */
991
992             if (p == line+1 && *line == '$') {
993                 type = TOK_OTHER; /* TOKEN_HERE */
994             } else {
995                 if (has_e && !is_hex) {
996                     /* 1e13 is floating-point, but 1e13h is not */
997                     is_float = true;
998                 }
999
1000                 type = is_float ? TOK_FLOAT : TOK_NUMBER;
1001             }
1002         } else if (nasm_isspace(*p)) {
1003             type = TOK_WHITESPACE;
1004             p++;
1005             while (*p && nasm_isspace(*p))
1006                 p++;
1007             /*
1008              * Whitespace just before end-of-line is discarded by
1009              * pretending it's a comment; whitespace just before a
1010              * comment gets lumped into the comment.
1011              */
1012             if (!*p || *p == ';') {
1013                 type = TOK_COMMENT;
1014                 while (*p)
1015                     p++;
1016             }
1017         } else if (*p == ';') {
1018             type = TOK_COMMENT;
1019             while (*p)
1020                 p++;
1021         } else {
1022             /*
1023              * Anything else is an operator of some kind. We check
1024              * for all the double-character operators (>>, <<, //,
1025              * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1026              * else is a single-character operator.
1027              */
1028             type = TOK_OTHER;
1029             if ((p[0] == '>' && p[1] == '>') ||
1030                 (p[0] == '<' && p[1] == '<') ||
1031                 (p[0] == '/' && p[1] == '/') ||
1032                 (p[0] == '<' && p[1] == '=') ||
1033                 (p[0] == '>' && p[1] == '=') ||
1034                 (p[0] == '=' && p[1] == '=') ||
1035                 (p[0] == '!' && p[1] == '=') ||
1036                 (p[0] == '<' && p[1] == '>') ||
1037                 (p[0] == '&' && p[1] == '&') ||
1038                 (p[0] == '|' && p[1] == '|') ||
1039                 (p[0] == '^' && p[1] == '^')) {
1040                 p++;
1041             }
1042             p++;
1043         }
1044
1045         /* Handling unterminated string by UNV */
1046         /*if (type == -1)
1047            {
1048            *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1049            t->text[p-line] = *line;
1050            tail = &t->next;
1051            }
1052            else */
1053         if (type != TOK_COMMENT) {
1054             *tail = t = new_Token(NULL, type, line, p - line);
1055             tail = &t->next;
1056         }
1057         line = p;
1058     }
1059     return list;
1060 }
1061
1062 /*
1063  * this function allocates a new managed block of memory and
1064  * returns a pointer to the block.  The managed blocks are
1065  * deleted only all at once by the delete_Blocks function.
1066  */
1067 static void *new_Block(size_t size)
1068 {
1069     Blocks *b = &blocks;
1070
1071     /* first, get to the end of the linked list */
1072     while (b->next)
1073         b = b->next;
1074     /* now allocate the requested chunk */
1075     b->chunk = nasm_malloc(size);
1076
1077     /* now allocate a new block for the next request */
1078     b->next = nasm_malloc(sizeof(Blocks));
1079     /* and initialize the contents of the new block */
1080     b->next->next = NULL;
1081     b->next->chunk = NULL;
1082     return b->chunk;
1083 }
1084
1085 /*
1086  * this function deletes all managed blocks of memory
1087  */
1088 static void delete_Blocks(void)
1089 {
1090     Blocks *a, *b = &blocks;
1091
1092     /*
1093      * keep in mind that the first block, pointed to by blocks
1094      * is a static and not dynamically allocated, so we don't
1095      * free it.
1096      */
1097     while (b) {
1098         if (b->chunk)
1099             nasm_free(b->chunk);
1100         a = b;
1101         b = b->next;
1102         if (a != &blocks)
1103             nasm_free(a);
1104     }
1105 }
1106
1107 /*
1108  *  this function creates a new Token and passes a pointer to it
1109  *  back to the caller.  It sets the type and text elements, and
1110  *  also the a.mac and next elements to NULL.
1111  */
1112 static Token *new_Token(Token * next, enum pp_token_type type,
1113                         const char *text, int txtlen)
1114 {
1115     Token *t;
1116     int i;
1117
1118     if (freeTokens == NULL) {
1119         freeTokens = (Token *) new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
1120         for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
1121             freeTokens[i].next = &freeTokens[i + 1];
1122         freeTokens[i].next = NULL;
1123     }
1124     t = freeTokens;
1125     freeTokens = t->next;
1126     t->next = next;
1127     t->a.mac = NULL;
1128     t->type = type;
1129     if (type == TOK_WHITESPACE || text == NULL) {
1130         t->text = NULL;
1131     } else {
1132         if (txtlen == 0)
1133             txtlen = strlen(text);
1134         t->text = nasm_malloc(txtlen+1);
1135         memcpy(t->text, text, txtlen);
1136         t->text[txtlen] = '\0';
1137     }
1138     return t;
1139 }
1140
1141 static Token *delete_Token(Token * t)
1142 {
1143     Token *next = t->next;
1144     nasm_free(t->text);
1145     t->next = freeTokens;
1146     freeTokens = t;
1147     return next;
1148 }
1149
1150 /*
1151  * Convert a line of tokens back into text.
1152  * If expand_locals is not zero, identifiers of the form "%$*xxx"
1153  * will be transformed into ..@ctxnum.xxx
1154  */
1155 static char *detoken(Token * tlist, bool expand_locals)
1156 {
1157     Token *t;
1158     int len;
1159     char *line, *p;
1160     const char *q;
1161
1162     len = 0;
1163     for (t = tlist; t; t = t->next) {
1164         if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
1165             char *p = getenv(t->text + 2);
1166             nasm_free(t->text);
1167             if (p)
1168                 t->text = nasm_strdup(p);
1169             else
1170                 t->text = NULL;
1171         }
1172         /* Expand local macros here and not during preprocessing */
1173         if (expand_locals &&
1174             t->type == TOK_PREPROC_ID && t->text &&
1175             t->text[0] == '%' && t->text[1] == '$') {
1176             const char *q;
1177             char *p;
1178             Context *ctx = get_ctx(t->text, &q, false);
1179             if (ctx) {
1180                 char buffer[40];
1181                 snprintf(buffer, sizeof(buffer), "..@%"PRIu32".", ctx->number);
1182                 p = nasm_strcat(buffer, q);
1183                 nasm_free(t->text);
1184                 t->text = p;
1185             }
1186         }
1187         if (t->type == TOK_WHITESPACE) {
1188             len++;
1189         } else if (t->text) {
1190             len += strlen(t->text);
1191         }
1192     }
1193     p = line = nasm_malloc(len + 1);
1194     for (t = tlist; t; t = t->next) {
1195         if (t->type == TOK_WHITESPACE) {
1196             *p++ = ' ';
1197         } else if (t->text) {
1198             q = t->text;
1199             while (*q)
1200                 *p++ = *q++;
1201         }
1202     }
1203     *p = '\0';
1204     return line;
1205 }
1206
1207 /*
1208  * A scanner, suitable for use by the expression evaluator, which
1209  * operates on a line of Tokens. Expects a pointer to a pointer to
1210  * the first token in the line to be passed in as its private_data
1211  * field.
1212  *
1213  * FIX: This really needs to be unified with stdscan.
1214  */
1215 static int ppscan(void *private_data, struct tokenval *tokval)
1216 {
1217     Token **tlineptr = private_data;
1218     Token *tline;
1219     char ourcopy[MAX_KEYWORD+1], *p, *r, *s;
1220
1221     do {
1222         tline = *tlineptr;
1223         *tlineptr = tline ? tline->next : NULL;
1224     }
1225     while (tline && (tline->type == TOK_WHITESPACE ||
1226                      tline->type == TOK_COMMENT));
1227
1228     if (!tline)
1229         return tokval->t_type = TOKEN_EOS;
1230
1231     tokval->t_charptr = tline->text;
1232
1233     if (tline->text[0] == '$' && !tline->text[1])
1234         return tokval->t_type = TOKEN_HERE;
1235     if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1236         return tokval->t_type = TOKEN_BASE;
1237
1238     if (tline->type == TOK_ID) {
1239         p = tokval->t_charptr = tline->text;
1240         if (p[0] == '$') {
1241             tokval->t_charptr++;
1242             return tokval->t_type = TOKEN_ID;
1243         }
1244
1245         for (r = p, s = ourcopy; *r; r++) {
1246             if (r >= p+MAX_KEYWORD)
1247                 return tokval->t_type = TOKEN_ID; /* Not a keyword */
1248             *s++ = nasm_tolower(*r);
1249         }
1250         *s = '\0';
1251         /* right, so we have an identifier sitting in temp storage. now,
1252          * is it actually a register or instruction name, or what? */
1253         return nasm_token_hash(ourcopy, tokval);
1254     }
1255
1256     if (tline->type == TOK_NUMBER) {
1257         bool rn_error;
1258         tokval->t_integer = readnum(tline->text, &rn_error);
1259         tokval->t_charptr = tline->text;
1260         if (rn_error)
1261             return tokval->t_type = TOKEN_ERRNUM;
1262         else
1263             return tokval->t_type = TOKEN_NUM;
1264     }
1265
1266     if (tline->type == TOK_FLOAT) {
1267         return tokval->t_type = TOKEN_FLOAT;
1268     }
1269
1270     if (tline->type == TOK_STRING) {
1271         char bq, *ep;
1272
1273         bq = tline->text[0];
1274         tokval->t_charptr = tline->text;
1275         tokval->t_inttwo = nasm_unquote(tline->text, &ep);
1276
1277         if (ep[0] != bq || ep[1] != '\0')
1278             return tokval->t_type = TOKEN_ERRSTR;
1279         else
1280             return tokval->t_type = TOKEN_STR;
1281     }
1282
1283     if (tline->type == TOK_OTHER) {
1284         if (!strcmp(tline->text, "<<"))
1285             return tokval->t_type = TOKEN_SHL;
1286         if (!strcmp(tline->text, ">>"))
1287             return tokval->t_type = TOKEN_SHR;
1288         if (!strcmp(tline->text, "//"))
1289             return tokval->t_type = TOKEN_SDIV;
1290         if (!strcmp(tline->text, "%%"))
1291             return tokval->t_type = TOKEN_SMOD;
1292         if (!strcmp(tline->text, "=="))
1293             return tokval->t_type = TOKEN_EQ;
1294         if (!strcmp(tline->text, "<>"))
1295             return tokval->t_type = TOKEN_NE;
1296         if (!strcmp(tline->text, "!="))
1297             return tokval->t_type = TOKEN_NE;
1298         if (!strcmp(tline->text, "<="))
1299             return tokval->t_type = TOKEN_LE;
1300         if (!strcmp(tline->text, ">="))
1301             return tokval->t_type = TOKEN_GE;
1302         if (!strcmp(tline->text, "&&"))
1303             return tokval->t_type = TOKEN_DBL_AND;
1304         if (!strcmp(tline->text, "^^"))
1305             return tokval->t_type = TOKEN_DBL_XOR;
1306         if (!strcmp(tline->text, "||"))
1307             return tokval->t_type = TOKEN_DBL_OR;
1308     }
1309
1310     /*
1311      * We have no other options: just return the first character of
1312      * the token text.
1313      */
1314     return tokval->t_type = tline->text[0];
1315 }
1316
1317 /*
1318  * Compare a string to the name of an existing macro; this is a
1319  * simple wrapper which calls either strcmp or nasm_stricmp
1320  * depending on the value of the `casesense' parameter.
1321  */
1322 static int mstrcmp(const char *p, const char *q, bool casesense)
1323 {
1324     return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1325 }
1326
1327 /*
1328  * Compare a string to the name of an existing macro; this is a
1329  * simple wrapper which calls either strcmp or nasm_stricmp
1330  * depending on the value of the `casesense' parameter.
1331  */
1332 static int mmemcmp(const char *p, const char *q, size_t l, bool casesense)
1333 {
1334     return casesense ? memcmp(p, q, l) : nasm_memicmp(p, q, l);
1335 }
1336
1337 /*
1338  * Return the Context structure associated with a %$ token. Return
1339  * NULL, having _already_ reported an error condition, if the
1340  * context stack isn't deep enough for the supplied number of $
1341  * signs.
1342  * If all_contexts == true, contexts that enclose current are
1343  * also scanned for such smacro, until it is found; if not -
1344  * only the context that directly results from the number of $'s
1345  * in variable's name.
1346  *
1347  * If "namep" is non-NULL, set it to the pointer to the macro name
1348  * tail, i.e. the part beyond %$...
1349  */
1350 static Context *get_ctx(const char *name, const char **namep,
1351                         bool all_contexts)
1352 {
1353     Context *ctx;
1354     SMacro *m;
1355     int i;
1356
1357     if (namep)
1358         *namep = name;
1359
1360     if (!name || name[0] != '%' || name[1] != '$')
1361         return NULL;
1362
1363     if (!cstk) {
1364         error(ERR_NONFATAL, "`%s': context stack is empty", name);
1365         return NULL;
1366     }
1367
1368     name += 2;
1369     ctx = cstk;
1370     i = 0;
1371     while (ctx && *name == '$') {
1372         name++;
1373         i++;
1374         ctx = ctx->next;
1375     }
1376     if (!ctx) {
1377         error(ERR_NONFATAL, "`%s': context stack is only"
1378               " %d level%s deep", name, i, (i == 1 ? "" : "s"));
1379         return NULL;
1380     }
1381
1382     if (namep)
1383         *namep = name;
1384
1385     if (!all_contexts)
1386         return ctx;
1387
1388     do {
1389         /* Search for this smacro in found context */
1390         m = hash_findix(&ctx->localmac, name);
1391         while (m) {
1392             if (!mstrcmp(m->name, name, m->casesense))
1393                 return ctx;
1394             m = m->next;
1395         }
1396         ctx = ctx->next;
1397     }
1398     while (ctx);
1399     return NULL;
1400 }
1401
1402 /*
1403  * Check to see if a file is already in a string list
1404  */
1405 static bool in_list(const StrList *list, const char *str)
1406 {
1407     while (list) {
1408         if (!strcmp(list->str, str))
1409             return true;
1410         list = list->next;
1411     }
1412     return false;
1413 }
1414
1415 /*
1416  * Open an include file. This routine must always return a valid
1417  * file pointer if it returns - it's responsible for throwing an
1418  * ERR_FATAL and bombing out completely if not. It should also try
1419  * the include path one by one until it finds the file or reaches
1420  * the end of the path.
1421  */
1422 static FILE *inc_fopen(const char *file, StrList **dhead, StrList ***dtail,
1423                        bool missing_ok)
1424 {
1425     FILE *fp;
1426     char *prefix = "";
1427     IncPath *ip = ipath;
1428     int len = strlen(file);
1429     size_t prefix_len = 0;
1430     StrList *sl;
1431
1432     while (1) {
1433         sl = nasm_malloc(prefix_len+len+1+sizeof sl->next);
1434         memcpy(sl->str, prefix, prefix_len);
1435         memcpy(sl->str+prefix_len, file, len+1);
1436         fp = fopen(sl->str, "r");
1437         if (fp && dhead && !in_list(*dhead, sl->str)) {
1438             sl->next = NULL;
1439             **dtail = sl;
1440             *dtail = &sl->next;
1441         } else {
1442             nasm_free(sl);
1443         }
1444         if (fp)
1445             return fp;
1446         if (!ip) {
1447             if (!missing_ok)
1448                 break;
1449             prefix = NULL;
1450         } else {
1451             prefix = ip->path;
1452             ip = ip->next;
1453         }
1454         if (prefix) {
1455             prefix_len = strlen(prefix);
1456         } else {
1457             /* -MG given and file not found */
1458             if (dhead && !in_list(*dhead, file)) {
1459                 sl = nasm_malloc(len+1+sizeof sl->next);
1460                 sl->next = NULL;
1461                 strcpy(sl->str, file);
1462                 **dtail = sl;
1463                 *dtail = &sl->next;
1464             }
1465             return NULL;
1466         }
1467     }
1468
1469     error(ERR_FATAL, "unable to open include file `%s'", file);
1470     return NULL;                /* never reached - placate compilers */
1471 }
1472
1473 /*
1474  * Determine if we should warn on defining a single-line macro of
1475  * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1476  * return true if _any_ single-line macro of that name is defined.
1477  * Otherwise, will return true if a single-line macro with either
1478  * `nparam' or no parameters is defined.
1479  *
1480  * If a macro with precisely the right number of parameters is
1481  * defined, or nparam is -1, the address of the definition structure
1482  * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1483  * is NULL, no action will be taken regarding its contents, and no
1484  * error will occur.
1485  *
1486  * Note that this is also called with nparam zero to resolve
1487  * `ifdef'.
1488  *
1489  * If you already know which context macro belongs to, you can pass
1490  * the context pointer as first parameter; if you won't but name begins
1491  * with %$ the context will be automatically computed. If all_contexts
1492  * is true, macro will be searched in outer contexts as well.
1493  */
1494 static bool
1495 smacro_defined(Context * ctx, const char *name, int nparam, SMacro ** defn,
1496                bool nocase)
1497 {
1498     struct hash_table *smtbl;
1499     SMacro *m;
1500
1501     if (ctx) {
1502         smtbl = &ctx->localmac;
1503     } else if (name[0] == '%' && name[1] == '$') {
1504         if (cstk)
1505             ctx = get_ctx(name, &name, false);
1506         if (!ctx)
1507             return false;       /* got to return _something_ */
1508         smtbl = &ctx->localmac;
1509     } else {
1510         smtbl = &smacros;
1511     }
1512     m = (SMacro *) hash_findix(smtbl, name);
1513
1514     while (m) {
1515         if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1516             (nparam <= 0 || m->nparam == 0 || nparam == (int) m->nparam)) {
1517             if (defn) {
1518                 if (nparam == (int) m->nparam || nparam == -1)
1519                     *defn = m;
1520                 else
1521                     *defn = NULL;
1522             }
1523             return true;
1524         }
1525         m = m->next;
1526     }
1527
1528     return false;
1529 }
1530
1531 /*
1532  * Count and mark off the parameters in a multi-line macro call.
1533  * This is called both from within the multi-line macro expansion
1534  * code, and also to mark off the default parameters when provided
1535  * in a %macro definition line.
1536  */
1537 static void count_mmac_params(Token * t, int *nparam, Token *** params)
1538 {
1539     int paramsize, brace;
1540
1541     *nparam = paramsize = 0;
1542     *params = NULL;
1543     while (t) {
1544         /* +1: we need space for the final NULL */
1545         if (*nparam+1 >= paramsize) {
1546             paramsize += PARAM_DELTA;
1547             *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1548         }
1549         skip_white_(t);
1550         brace = false;
1551         if (tok_is_(t, "{"))
1552             brace = true;
1553         (*params)[(*nparam)++] = t;
1554         while (tok_isnt_(t, brace ? "}" : ","))
1555             t = t->next;
1556         if (t) {                /* got a comma/brace */
1557             t = t->next;
1558             if (brace) {
1559                 /*
1560                  * Now we've found the closing brace, look further
1561                  * for the comma.
1562                  */
1563                 skip_white_(t);
1564                 if (tok_isnt_(t, ",")) {
1565                     error(ERR_NONFATAL,
1566                           "braces do not enclose all of macro parameter");
1567                     while (tok_isnt_(t, ","))
1568                         t = t->next;
1569                 }
1570                 if (t)
1571                     t = t->next;        /* eat the comma */
1572             }
1573         }
1574     }
1575 }
1576
1577 /*
1578  * Determine whether one of the various `if' conditions is true or
1579  * not.
1580  *
1581  * We must free the tline we get passed.
1582  */
1583 static bool if_condition(Token * tline, enum preproc_token ct)
1584 {
1585     enum pp_conditional i = PP_COND(ct);
1586     bool j;
1587     Token *t, *tt, **tptr, *origline;
1588     struct tokenval tokval;
1589     expr *evalresult;
1590     enum pp_token_type needtype;
1591
1592     origline = tline;
1593
1594     switch (i) {
1595     case PPC_IFCTX:
1596         j = false;              /* have we matched yet? */
1597         while (true) {
1598             skip_white_(tline);
1599             if (!tline)
1600                 break;
1601             if (tline->type != TOK_ID) {
1602                 error(ERR_NONFATAL,
1603                       "`%s' expects context identifiers", pp_directives[ct]);
1604                 free_tlist(origline);
1605                 return -1;
1606             }
1607             if (cstk && cstk->name && !nasm_stricmp(tline->text, cstk->name))
1608                 j = true;
1609             tline = tline->next;
1610         }
1611         break;
1612
1613     case PPC_IFDEF:
1614         j = false;              /* have we matched yet? */
1615         while (tline) {
1616             skip_white_(tline);
1617             if (!tline || (tline->type != TOK_ID &&
1618                            (tline->type != TOK_PREPROC_ID ||
1619                             tline->text[1] != '$'))) {
1620                 error(ERR_NONFATAL,
1621                       "`%s' expects macro identifiers", pp_directives[ct]);
1622                 goto fail;
1623             }
1624             if (smacro_defined(NULL, tline->text, 0, NULL, true))
1625                 j = true;
1626             tline = tline->next;
1627         }
1628         break;
1629
1630     case PPC_IFIDN:
1631     case PPC_IFIDNI:
1632         tline = expand_smacro(tline);
1633         t = tt = tline;
1634         while (tok_isnt_(tt, ","))
1635             tt = tt->next;
1636         if (!tt) {
1637             error(ERR_NONFATAL,
1638                   "`%s' expects two comma-separated arguments",
1639                   pp_directives[ct]);
1640             goto fail;
1641         }
1642         tt = tt->next;
1643         j = true;               /* assume equality unless proved not */
1644         while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1645             if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1646                 error(ERR_NONFATAL, "`%s': more than one comma on line",
1647                       pp_directives[ct]);
1648                 goto fail;
1649             }
1650             if (t->type == TOK_WHITESPACE) {
1651                 t = t->next;
1652                 continue;
1653             }
1654             if (tt->type == TOK_WHITESPACE) {
1655                 tt = tt->next;
1656                 continue;
1657             }
1658             if (tt->type != t->type) {
1659                 j = false;      /* found mismatching tokens */
1660                 break;
1661             }
1662             /* When comparing strings, need to unquote them first */
1663             if (t->type == TOK_STRING) {
1664                 size_t l1 = nasm_unquote(t->text, NULL);
1665                 size_t l2 = nasm_unquote(tt->text, NULL);
1666
1667                 if (l1 != l2) {
1668                     j = false;
1669                     break;
1670                 }
1671                 if (mmemcmp(t->text, tt->text, l1, i == PPC_IFIDN)) {
1672                     j = false;
1673                     break;
1674                 }
1675             } else if (mstrcmp(tt->text, t->text, i == PPC_IFIDN) != 0) {
1676                 j = false;      /* found mismatching tokens */
1677                 break;
1678             }
1679
1680             t = t->next;
1681             tt = tt->next;
1682         }
1683         if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1684             j = false;          /* trailing gunk on one end or other */
1685         break;
1686
1687     case PPC_IFMACRO:
1688         {
1689             bool found = false;
1690             MMacro searching, *mmac;
1691
1692             skip_white_(tline);
1693             tline = expand_id(tline);
1694             if (!tok_type_(tline, TOK_ID)) {
1695                 error(ERR_NONFATAL,
1696                       "`%s' expects a macro name", pp_directives[ct]);
1697                 goto fail;
1698             }
1699             searching.name = nasm_strdup(tline->text);
1700             searching.casesense = true;
1701             searching.plus = false;
1702             searching.nolist = false;
1703             searching.in_progress = 0;
1704                         searching.max_depth = 0;
1705             searching.rep_nest = NULL;
1706             searching.nparam_min = 0;
1707             searching.nparam_max = INT_MAX;
1708             tline = expand_smacro(tline->next);
1709             skip_white_(tline);
1710             if (!tline) {
1711             } else if (!tok_type_(tline, TOK_NUMBER)) {
1712                 error(ERR_NONFATAL,
1713                       "`%s' expects a parameter count or nothing",
1714                       pp_directives[ct]);
1715             } else {
1716                 searching.nparam_min = searching.nparam_max =
1717                     readnum(tline->text, &j);
1718                 if (j)
1719                     error(ERR_NONFATAL,
1720                           "unable to parse parameter count `%s'",
1721                           tline->text);
1722             }
1723             if (tline && tok_is_(tline->next, "-")) {
1724                 tline = tline->next->next;
1725                 if (tok_is_(tline, "*"))
1726                     searching.nparam_max = INT_MAX;
1727                 else if (!tok_type_(tline, TOK_NUMBER))
1728                     error(ERR_NONFATAL,
1729                           "`%s' expects a parameter count after `-'",
1730                           pp_directives[ct]);
1731                 else {
1732                     searching.nparam_max = readnum(tline->text, &j);
1733                     if (j)
1734                         error(ERR_NONFATAL,
1735                               "unable to parse parameter count `%s'",
1736                               tline->text);
1737                     if (searching.nparam_min > searching.nparam_max)
1738                         error(ERR_NONFATAL,
1739                               "minimum parameter count exceeds maximum");
1740                 }
1741             }
1742             if (tline && tok_is_(tline->next, "+")) {
1743                 tline = tline->next;
1744                 searching.plus = true;
1745             }
1746             mmac = (MMacro *) hash_findix(&mmacros, searching.name);
1747             while (mmac) {
1748                 if (!strcmp(mmac->name, searching.name) &&
1749                     (mmac->nparam_min <= searching.nparam_max
1750                      || searching.plus)
1751                     && (searching.nparam_min <= mmac->nparam_max
1752                         || mmac->plus)) {
1753                     found = true;
1754                     break;
1755                 }
1756                 mmac = mmac->next;
1757             }
1758             if(tline && tline->next)
1759                 error(ERR_WARNING|ERR_PASS1,
1760                       "trailing garbage after %%ifmacro ignored");
1761             nasm_free(searching.name);
1762             j = found;
1763             break;
1764         }
1765
1766     case PPC_IFID:
1767         needtype = TOK_ID;
1768         goto iftype;
1769     case PPC_IFNUM:
1770         needtype = TOK_NUMBER;
1771         goto iftype;
1772     case PPC_IFSTR:
1773         needtype = TOK_STRING;
1774         goto iftype;
1775
1776     iftype:
1777         t = tline = expand_smacro(tline);
1778
1779         while (tok_type_(t, TOK_WHITESPACE) ||
1780                (needtype == TOK_NUMBER &&
1781                 tok_type_(t, TOK_OTHER) &&
1782                 (t->text[0] == '-' || t->text[0] == '+') &&
1783                 !t->text[1]))
1784             t = t->next;
1785
1786         j = tok_type_(t, needtype);
1787         break;
1788
1789     case PPC_IFTOKEN:
1790         t = tline = expand_smacro(tline);
1791         while (tok_type_(t, TOK_WHITESPACE))
1792             t = t->next;
1793
1794         j = false;
1795         if (t) {
1796             t = t->next;        /* Skip the actual token */
1797             while (tok_type_(t, TOK_WHITESPACE))
1798                 t = t->next;
1799             j = !t;             /* Should be nothing left */
1800         }
1801         break;
1802
1803     case PPC_IFEMPTY:
1804         t = tline = expand_smacro(tline);
1805         while (tok_type_(t, TOK_WHITESPACE))
1806             t = t->next;
1807
1808         j = !t;                 /* Should be empty */
1809         break;
1810
1811     case PPC_IF:
1812         t = tline = expand_smacro(tline);
1813         tptr = &t;
1814         tokval.t_type = TOKEN_INVALID;
1815         evalresult = evaluate(ppscan, tptr, &tokval,
1816                               NULL, pass | CRITICAL, error, NULL);
1817         if (!evalresult)
1818             return -1;
1819         if (tokval.t_type)
1820             error(ERR_WARNING|ERR_PASS1,
1821                   "trailing garbage after expression ignored");
1822         if (!is_simple(evalresult)) {
1823             error(ERR_NONFATAL,
1824                   "non-constant value given to `%s'", pp_directives[ct]);
1825             goto fail;
1826         }
1827         j = reloc_value(evalresult) != 0;
1828         break;
1829
1830     default:
1831         error(ERR_FATAL,
1832               "preprocessor directive `%s' not yet implemented",
1833               pp_directives[ct]);
1834         goto fail;
1835     }
1836
1837     free_tlist(origline);
1838     return j ^ PP_NEGATIVE(ct);
1839
1840 fail:
1841     free_tlist(origline);
1842     return -1;
1843 }
1844
1845 /*
1846  * Common code for defining an smacro
1847  */
1848 static bool define_smacro(Context *ctx, const char *mname, bool casesense,
1849                           int nparam, Token *expansion)
1850 {
1851     SMacro *smac, **smhead;
1852     struct hash_table *smtbl;
1853
1854     if (smacro_defined(ctx, mname, nparam, &smac, casesense)) {
1855         if (!smac) {
1856             error(ERR_WARNING|ERR_PASS1,
1857                   "single-line macro `%s' defined both with and"
1858                   " without parameters", mname);
1859
1860             /* Some instances of the old code considered this a failure,
1861                some others didn't.  What is the right thing to do here? */
1862             free_tlist(expansion);
1863             return false;       /* Failure */
1864         } else {
1865             /*
1866              * We're redefining, so we have to take over an
1867              * existing SMacro structure. This means freeing
1868              * what was already in it.
1869              */
1870             nasm_free(smac->name);
1871             free_tlist(smac->expansion);
1872         }
1873     } else {
1874         smtbl  = ctx ? &ctx->localmac : &smacros;
1875         smhead = (SMacro **) hash_findi_add(smtbl, mname);
1876         smac = nasm_malloc(sizeof(SMacro));
1877         smac->next = *smhead;
1878         *smhead = smac;
1879     }
1880     smac->name = nasm_strdup(mname);
1881     smac->casesense = casesense;
1882     smac->nparam = nparam;
1883     smac->expansion = expansion;
1884     smac->in_progress = false;
1885     return true;                /* Success */
1886 }
1887
1888 /*
1889  * Undefine an smacro
1890  */
1891 static void undef_smacro(Context *ctx, const char *mname)
1892 {
1893     SMacro **smhead, *s, **sp;
1894     struct hash_table *smtbl;
1895
1896     smtbl = ctx ? &ctx->localmac : &smacros;
1897     smhead = (SMacro **)hash_findi(smtbl, mname, NULL);
1898
1899     if (smhead) {
1900         /*
1901          * We now have a macro name... go hunt for it.
1902          */
1903         sp = smhead;
1904         while ((s = *sp) != NULL) {
1905             if (!mstrcmp(s->name, mname, s->casesense)) {
1906                 *sp = s->next;
1907                 nasm_free(s->name);
1908                 free_tlist(s->expansion);
1909                 nasm_free(s);
1910             } else {
1911                 sp = &s->next;
1912             }
1913         }
1914     }
1915 }
1916
1917 /*
1918  * Parse a mmacro specification.
1919  */
1920 static bool parse_mmacro_spec(Token *tline, MMacro *def, const char *directive)
1921 {
1922     bool err;
1923
1924     tline = tline->next;
1925     skip_white_(tline);
1926     tline = expand_id(tline);
1927     if (!tok_type_(tline, TOK_ID)) {
1928         error(ERR_NONFATAL, "`%s' expects a macro name", directive);
1929         return false;
1930     }
1931
1932         def->prev = NULL;
1933     def->name = nasm_strdup(tline->text);
1934     def->plus = false;
1935     def->nolist = false;
1936     def->in_progress = 0;
1937     def->rep_nest = NULL;
1938     def->nparam_min = 0;
1939     def->nparam_max = 0;
1940
1941     tline = expand_smacro(tline->next);
1942     skip_white_(tline);
1943     if (!tok_type_(tline, TOK_NUMBER)) {
1944         error(ERR_NONFATAL, "`%s' expects a parameter count", directive);
1945     } else {
1946         def->nparam_min = def->nparam_max =
1947             readnum(tline->text, &err);
1948         if (err)
1949             error(ERR_NONFATAL,
1950                   "unable to parse parameter count `%s'", tline->text);
1951     }
1952     if (tline && tok_is_(tline->next, "-")) {
1953         tline = tline->next->next;
1954         if (tok_is_(tline, "*")) {
1955             def->nparam_max = INT_MAX;
1956         } else if (!tok_type_(tline, TOK_NUMBER)) {
1957             error(ERR_NONFATAL,
1958                   "`%s' expects a parameter count after `-'", directive);
1959         } else {
1960             def->nparam_max = readnum(tline->text, &err);
1961             if (err) {
1962                 error(ERR_NONFATAL, "unable to parse parameter count `%s'",
1963                       tline->text);
1964             }
1965             if (def->nparam_min > def->nparam_max) {
1966                 error(ERR_NONFATAL, "minimum parameter count exceeds maximum");
1967             }
1968         }
1969     }
1970     if (tline && tok_is_(tline->next, "+")) {
1971         tline = tline->next;
1972         def->plus = true;
1973     }
1974     if (tline && tok_type_(tline->next, TOK_ID) &&
1975         !nasm_stricmp(tline->next->text, ".nolist")) {
1976         tline = tline->next;
1977         def->nolist = true;
1978     }
1979         
1980     /*
1981      * Handle default parameters.
1982      */
1983     if (tline && tline->next) {
1984         def->dlist = tline->next;
1985         tline->next = NULL;
1986         count_mmac_params(def->dlist, &def->ndefs, &def->defaults);
1987     } else {
1988         def->dlist = NULL;
1989         def->defaults = NULL;
1990     }
1991     def->expansion = NULL;
1992
1993         if(def->defaults &&
1994            def->ndefs > def->nparam_max - def->nparam_min &&
1995            !def->plus)
1996          error(ERR_WARNING|ERR_PASS1|ERR_WARN_MDP,
1997                "too many default macro parameters");
1998
1999     return true;
2000 }
2001
2002
2003 /*
2004  * Decode a size directive
2005  */
2006 static int parse_size(const char *str) {
2007     static const char *size_names[] =
2008         { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2009     static const int sizes[] =
2010         { 0, 1, 4, 16, 8, 10, 2, 32 };
2011
2012     return sizes[bsii(str, size_names, elements(size_names))+1];
2013 }
2014
2015 /**
2016  * find and process preprocessor directive in passed line
2017  * Find out if a line contains a preprocessor directive, and deal
2018  * with it if so.
2019  *
2020  * If a directive _is_ found, it is the responsibility of this routine
2021  * (and not the caller) to free_tlist() the line.
2022  *
2023  * @param tline a pointer to the current tokeninzed line linked list
2024  * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2025  *
2026  */
2027 static int do_directive(Token * tline)
2028 {
2029     enum preproc_token i;
2030     int j;
2031     bool err;
2032     int nparam;
2033     bool nolist;
2034     bool casesense;
2035     int k, m;
2036     int offset;
2037     char *p, *pp;
2038     const char *mname;
2039     Include *inc;
2040     Context *ctx;
2041     Cond *cond;
2042     MMacro *mmac, **mmhead;
2043     Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
2044     Line *l;
2045     struct tokenval tokval;
2046     expr *evalresult;
2047     MMacro *tmp_defining;       /* Used when manipulating rep_nest */
2048     int64_t count;
2049     size_t len;
2050     int severity;
2051
2052     origline = tline;
2053
2054     skip_white_(tline);
2055     if (!tline || !tok_type_(tline, TOK_PREPROC_ID) ||
2056         (tline->text[1] == '%' || tline->text[1] == '$'
2057          || tline->text[1] == '!'))
2058         return NO_DIRECTIVE_FOUND;
2059
2060     i = pp_token_hash(tline->text);
2061
2062     /*
2063      * If we're in a non-emitting branch of a condition construct,
2064      * or walking to the end of an already terminated %rep block,
2065      * we should ignore all directives except for condition
2066      * directives.
2067      */
2068     if (((istk->conds && !emitting(istk->conds->state)) ||
2069          (istk->mstk && !istk->mstk->in_progress)) && !is_condition(i)) {
2070         return NO_DIRECTIVE_FOUND;
2071     }
2072
2073     /*
2074      * If we're defining a macro or reading a %rep block, we should
2075      * ignore all directives except for %macro/%imacro (which nest),
2076      * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2077      * If we're in a %rep block, another %rep nests, so should be let through.
2078      */
2079     if (defining && i != PP_MACRO && i != PP_IMACRO &&
2080             i != PP_RMACRO &&  i != PP_RIMACRO &&
2081         i != PP_ENDMACRO && i != PP_ENDM &&
2082         (defining->name || (i != PP_ENDREP && i != PP_REP))) {
2083         return NO_DIRECTIVE_FOUND;
2084     }
2085
2086     if (defining) {
2087         if (i == PP_MACRO || i == PP_IMACRO ||
2088                     i == PP_RMACRO || i == PP_RIMACRO) {
2089             nested_mac_count++;
2090             return NO_DIRECTIVE_FOUND;
2091         } else if (nested_mac_count > 0) {
2092             if (i == PP_ENDMACRO) {
2093                 nested_mac_count--;
2094                 return NO_DIRECTIVE_FOUND;
2095             }
2096         }
2097         if (!defining->name) {
2098             if (i == PP_REP) {
2099                 nested_rep_count++;
2100                 return NO_DIRECTIVE_FOUND;
2101             } else if (nested_rep_count > 0) {
2102                 if (i == PP_ENDREP) {
2103                     nested_rep_count--;
2104                     return NO_DIRECTIVE_FOUND;
2105                 }
2106             }
2107         }
2108     }
2109
2110     switch (i) {
2111     case PP_INVALID:
2112         error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
2113               tline->text);
2114         return NO_DIRECTIVE_FOUND;      /* didn't get it */
2115
2116     case PP_STACKSIZE:
2117         /* Directive to tell NASM what the default stack size is. The
2118          * default is for a 16-bit stack, and this can be overriden with
2119          * %stacksize large.
2120          * the following form:
2121          *
2122          *      ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2123          */
2124         tline = tline->next;
2125         if (tline && tline->type == TOK_WHITESPACE)
2126             tline = tline->next;
2127         if (!tline || tline->type != TOK_ID) {
2128             error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
2129             free_tlist(origline);
2130             return DIRECTIVE_FOUND;
2131         }
2132         if (nasm_stricmp(tline->text, "flat") == 0) {
2133             /* All subsequent ARG directives are for a 32-bit stack */
2134             StackSize = 4;
2135             StackPointer = "ebp";
2136             ArgOffset = 8;
2137             LocalOffset = 0;
2138         } else if (nasm_stricmp(tline->text, "flat64") == 0) {
2139             /* All subsequent ARG directives are for a 64-bit stack */
2140             StackSize = 8;
2141             StackPointer = "rbp";
2142             ArgOffset = 8;
2143             LocalOffset = 0;
2144         } else if (nasm_stricmp(tline->text, "large") == 0) {
2145             /* All subsequent ARG directives are for a 16-bit stack,
2146              * far function call.
2147              */
2148             StackSize = 2;
2149             StackPointer = "bp";
2150             ArgOffset = 4;
2151             LocalOffset = 0;
2152         } else if (nasm_stricmp(tline->text, "small") == 0) {
2153             /* All subsequent ARG directives are for a 16-bit stack,
2154              * far function call. We don't support near functions.
2155              */
2156             StackSize = 2;
2157             StackPointer = "bp";
2158             ArgOffset = 6;
2159             LocalOffset = 0;
2160         } else {
2161             error(ERR_NONFATAL, "`%%stacksize' invalid size type");
2162             free_tlist(origline);
2163             return DIRECTIVE_FOUND;
2164         }
2165         free_tlist(origline);
2166         return DIRECTIVE_FOUND;
2167
2168     case PP_ARG:
2169         /* TASM like ARG directive to define arguments to functions, in
2170          * the following form:
2171          *
2172          *      ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2173          */
2174         offset = ArgOffset;
2175         do {
2176             char *arg, directive[256];
2177             int size = StackSize;
2178
2179             /* Find the argument name */
2180             tline = tline->next;
2181             if (tline && tline->type == TOK_WHITESPACE)
2182                 tline = tline->next;
2183             if (!tline || tline->type != TOK_ID) {
2184                 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
2185                 free_tlist(origline);
2186                 return DIRECTIVE_FOUND;
2187             }
2188             arg = tline->text;
2189
2190             /* Find the argument size type */
2191             tline = tline->next;
2192             if (!tline || tline->type != TOK_OTHER
2193                 || tline->text[0] != ':') {
2194                 error(ERR_NONFATAL,
2195                       "Syntax error processing `%%arg' directive");
2196                 free_tlist(origline);
2197                 return DIRECTIVE_FOUND;
2198             }
2199             tline = tline->next;
2200             if (!tline || tline->type != TOK_ID) {
2201                 error(ERR_NONFATAL, "`%%arg' missing size type parameter");
2202                 free_tlist(origline);
2203                 return DIRECTIVE_FOUND;
2204             }
2205
2206             /* Allow macro expansion of type parameter */
2207             tt = tokenize(tline->text);
2208             tt = expand_smacro(tt);
2209             size = parse_size(tt->text);
2210             if (!size) {
2211                 error(ERR_NONFATAL,
2212                       "Invalid size type for `%%arg' missing directive");
2213                 free_tlist(tt);
2214                 free_tlist(origline);
2215                 return DIRECTIVE_FOUND;
2216             }
2217             free_tlist(tt);
2218
2219             /* Round up to even stack slots */
2220             size = (size+StackSize-1) & ~(StackSize-1);
2221
2222             /* Now define the macro for the argument */
2223             snprintf(directive, sizeof(directive), "%%define %s (%s+%d)",
2224                      arg, StackPointer, offset);
2225             do_directive(tokenize(directive));
2226             offset += size;
2227
2228             /* Move to the next argument in the list */
2229             tline = tline->next;
2230             if (tline && tline->type == TOK_WHITESPACE)
2231                 tline = tline->next;
2232         } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2233         ArgOffset = offset;
2234         free_tlist(origline);
2235         return DIRECTIVE_FOUND;
2236
2237     case PP_LOCAL:
2238         /* TASM like LOCAL directive to define local variables for a
2239          * function, in the following form:
2240          *
2241          *      LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2242          *
2243          * The '= LocalSize' at the end is ignored by NASM, but is
2244          * required by TASM to define the local parameter size (and used
2245          * by the TASM macro package).
2246          */
2247         offset = LocalOffset;
2248         do {
2249             char *local, directive[256];
2250             int size = StackSize;
2251
2252             /* Find the argument name */
2253             tline = tline->next;
2254             if (tline && tline->type == TOK_WHITESPACE)
2255                 tline = tline->next;
2256             if (!tline || tline->type != TOK_ID) {
2257                 error(ERR_NONFATAL,
2258                       "`%%local' missing argument parameter");
2259                 free_tlist(origline);
2260                 return DIRECTIVE_FOUND;
2261             }
2262             local = tline->text;
2263
2264             /* Find the argument size type */
2265             tline = tline->next;
2266             if (!tline || tline->type != TOK_OTHER
2267                 || tline->text[0] != ':') {
2268                 error(ERR_NONFATAL,
2269                       "Syntax error processing `%%local' directive");
2270                 free_tlist(origline);
2271                 return DIRECTIVE_FOUND;
2272             }
2273             tline = tline->next;
2274             if (!tline || tline->type != TOK_ID) {
2275                 error(ERR_NONFATAL,
2276                       "`%%local' missing size type parameter");
2277                 free_tlist(origline);
2278                 return DIRECTIVE_FOUND;
2279             }
2280
2281             /* Allow macro expansion of type parameter */
2282             tt = tokenize(tline->text);
2283             tt = expand_smacro(tt);
2284             size = parse_size(tt->text);
2285             if (!size) {
2286                 error(ERR_NONFATAL,
2287                       "Invalid size type for `%%local' missing directive");
2288                 free_tlist(tt);
2289                 free_tlist(origline);
2290                 return DIRECTIVE_FOUND;
2291             }
2292             free_tlist(tt);
2293
2294             /* Round up to even stack slots */
2295             size = (size+StackSize-1) & ~(StackSize-1);
2296
2297             offset += size;     /* Negative offset, increment before */
2298
2299             /* Now define the macro for the argument */
2300             snprintf(directive, sizeof(directive), "%%define %s (%s-%d)",
2301                      local, StackPointer, offset);
2302             do_directive(tokenize(directive));
2303
2304             /* Now define the assign to setup the enter_c macro correctly */
2305             snprintf(directive, sizeof(directive),
2306                      "%%assign %%$localsize %%$localsize+%d", size);
2307             do_directive(tokenize(directive));
2308
2309             /* Move to the next argument in the list */
2310             tline = tline->next;
2311             if (tline && tline->type == TOK_WHITESPACE)
2312                 tline = tline->next;
2313         } while (tline && tline->type == TOK_OTHER && tline->text[0] == ',');
2314         LocalOffset = offset;
2315         free_tlist(origline);
2316         return DIRECTIVE_FOUND;
2317
2318     case PP_CLEAR:
2319         if (tline->next)
2320             error(ERR_WARNING|ERR_PASS1,
2321                   "trailing garbage after `%%clear' ignored");
2322         free_macros();
2323         init_macros();
2324         free_tlist(origline);
2325         return DIRECTIVE_FOUND;
2326
2327     case PP_DEPEND:
2328         t = tline->next = expand_smacro(tline->next);
2329         skip_white_(t);
2330         if (!t || (t->type != TOK_STRING &&
2331                        t->type != TOK_INTERNAL_STRING)) {
2332             error(ERR_NONFATAL, "`%%depend' expects a file name");
2333             free_tlist(origline);
2334             return DIRECTIVE_FOUND;     /* but we did _something_ */
2335         }
2336         if (t->next)
2337             error(ERR_WARNING|ERR_PASS1,
2338                   "trailing garbage after `%%depend' ignored");
2339         p = t->text;
2340         if (t->type != TOK_INTERNAL_STRING)
2341             nasm_unquote(p, NULL);
2342         if (dephead && !in_list(*dephead, p)) {
2343             StrList *sl = nasm_malloc(strlen(p)+1+sizeof sl->next);
2344             sl->next = NULL;
2345             strcpy(sl->str, p);
2346             *deptail = sl;
2347             deptail = &sl->next;
2348         }
2349         free_tlist(origline);
2350         return DIRECTIVE_FOUND;
2351
2352     case PP_INCLUDE:
2353         t = tline->next = expand_smacro(tline->next);
2354         skip_white_(t);
2355
2356         if (!t || (t->type != TOK_STRING &&
2357                        t->type != TOK_INTERNAL_STRING)) {
2358             error(ERR_NONFATAL, "`%%include' expects a file name");
2359             free_tlist(origline);
2360             return DIRECTIVE_FOUND;     /* but we did _something_ */
2361         }
2362         if (t->next)
2363             error(ERR_WARNING|ERR_PASS1,
2364                   "trailing garbage after `%%include' ignored");
2365         p = t->text;
2366         if (t->type != TOK_INTERNAL_STRING)
2367             nasm_unquote(p, NULL);
2368         inc = nasm_malloc(sizeof(Include));
2369         inc->next = istk;
2370         inc->conds = NULL;
2371         inc->fp = inc_fopen(p, dephead, &deptail, pass == 0);
2372         if (!inc->fp) {
2373             /* -MG given but file not found */
2374             nasm_free(inc);
2375         } else {
2376             inc->fname = src_set_fname(nasm_strdup(p));
2377             inc->lineno = src_set_linnum(0);
2378             inc->lineinc = 1;
2379             inc->expansion = NULL;
2380             inc->mstk = NULL;
2381             istk = inc;
2382             list->uplevel(LIST_INCLUDE);
2383         }
2384         free_tlist(origline);
2385         return DIRECTIVE_FOUND;
2386
2387     case PP_USE:
2388     {
2389         static macros_t *use_pkg;
2390         const char *pkg_macro;
2391
2392         tline = tline->next;
2393         skip_white_(tline);
2394         tline = expand_id(tline);
2395
2396         if (!tline || (tline->type != TOK_STRING &&
2397                        tline->type != TOK_INTERNAL_STRING &&
2398                        tline->type != TOK_ID)) {
2399             error(ERR_NONFATAL, "`%%use' expects a package name");
2400             free_tlist(origline);
2401             return DIRECTIVE_FOUND;     /* but we did _something_ */
2402         }
2403         if (tline->next)
2404             error(ERR_WARNING|ERR_PASS1,
2405                   "trailing garbage after `%%use' ignored");
2406         if (tline->type == TOK_STRING)
2407             nasm_unquote(tline->text, NULL);
2408         use_pkg = nasm_stdmac_find_package(tline->text);
2409         if (!use_pkg)
2410             error(ERR_NONFATAL, "unknown `%%use' package: %s", tline->text);
2411         /* The first string will be <%define>__USE_*__ */
2412         pkg_macro = (char *)use_pkg + 1;
2413         if (!smacro_defined(NULL, pkg_macro, 0, NULL, true)) {
2414             /* Not already included, go ahead and include it */
2415             stdmacpos = use_pkg;
2416         }
2417         free_tlist(origline);
2418         return DIRECTIVE_FOUND;
2419     }
2420     case PP_PUSH:
2421     case PP_REPL:
2422     case PP_POP:
2423         tline = tline->next;
2424         skip_white_(tline);
2425         tline = expand_id(tline);
2426         if (tline) {
2427             if (!tok_type_(tline, TOK_ID)) {
2428                 error(ERR_NONFATAL, "`%s' expects a context identifier",
2429                       pp_directives[i]);
2430                 free_tlist(origline);
2431                 return DIRECTIVE_FOUND;     /* but we did _something_ */
2432             }
2433             if (tline->next)
2434                 error(ERR_WARNING|ERR_PASS1,
2435                       "trailing garbage after `%s' ignored",
2436                       pp_directives[i]);
2437             p = nasm_strdup(tline->text);
2438         } else {
2439             p = NULL;           /* Anonymous */
2440         }
2441
2442         if (i == PP_PUSH) {
2443             ctx = nasm_malloc(sizeof(Context));
2444             ctx->next = cstk;
2445             hash_init(&ctx->localmac, HASH_SMALL);
2446             ctx->name = p;
2447             ctx->number = unique++;
2448             cstk = ctx;
2449         } else {
2450             /* %pop or %repl */
2451             if (!cstk) {
2452                 error(ERR_NONFATAL, "`%s': context stack is empty",
2453                       pp_directives[i]);
2454             } else if (i == PP_POP) {
2455                 if (p && (!cstk->name || nasm_stricmp(p, cstk->name)))
2456                     error(ERR_NONFATAL, "`%%pop' in wrong context: %s, "
2457                           "expected %s",
2458                           cstk->name ? cstk->name : "anonymous", p);
2459                 else
2460                     ctx_pop();
2461             } else {
2462                 /* i == PP_REPL */
2463                 nasm_free(cstk->name);
2464                 cstk->name = p;
2465                 p = NULL;
2466             }
2467             nasm_free(p);
2468         }
2469         free_tlist(origline);
2470         return DIRECTIVE_FOUND;
2471     case PP_FATAL:
2472         severity = ERR_FATAL;
2473         goto issue_error;
2474     case PP_ERROR:
2475         severity = ERR_NONFATAL;
2476         goto issue_error;
2477     case PP_WARNING:
2478         severity = ERR_WARNING|ERR_WARN_USER;
2479         goto issue_error;
2480
2481     issue_error:
2482     {
2483         /* Only error out if this is the final pass */
2484         if (pass != 2 && i != PP_FATAL)
2485             return DIRECTIVE_FOUND;
2486
2487         tline->next = expand_smacro(tline->next);
2488         tline = tline->next;
2489         skip_white_(tline);
2490         t = tline ? tline->next : NULL;
2491         skip_white_(t);
2492         if (tok_type_(tline, TOK_STRING) && !t) {
2493             /* The line contains only a quoted string */
2494             p = tline->text;
2495             nasm_unquote(p, NULL);
2496             error(severity, "%s",  p);
2497         } else {
2498             /* Not a quoted string, or more than a quoted string */
2499             p = detoken(tline, false);
2500             error(severity, "%s",  p);
2501             nasm_free(p);
2502         }
2503         free_tlist(origline);
2504         return DIRECTIVE_FOUND;
2505     }
2506
2507     CASE_PP_IF:
2508         if (istk->conds && !emitting(istk->conds->state))
2509             j = COND_NEVER;
2510         else {
2511             j = if_condition(tline->next, i);
2512             tline->next = NULL; /* it got freed */
2513             j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2514         }
2515         cond = nasm_malloc(sizeof(Cond));
2516         cond->next = istk->conds;
2517         cond->state = j;
2518         istk->conds = cond;
2519         free_tlist(origline);
2520         return DIRECTIVE_FOUND;
2521
2522     CASE_PP_ELIF:
2523         if (!istk->conds)
2524             error(ERR_FATAL, "`%s': no matching `%%if'", pp_directives[i]);
2525         switch(istk->conds->state) {
2526             case COND_IF_TRUE:
2527                 istk->conds->state = COND_DONE;
2528                 break;
2529
2530             case COND_DONE:
2531             case COND_NEVER:
2532                 break;
2533
2534             case COND_ELSE_TRUE:
2535             case COND_ELSE_FALSE:
2536                 error_precond(ERR_WARNING|ERR_PASS1,
2537                               "`%%elif' after `%%else' ignored");
2538                 istk->conds->state = COND_NEVER;
2539                 break;
2540
2541             case COND_IF_FALSE:
2542                 /*
2543                  * IMPORTANT: In the case of %if, we will already have
2544                  * called expand_mmac_params(); however, if we're
2545                  * processing an %elif we must have been in a
2546                  * non-emitting mode, which would have inhibited
2547                  * the normal invocation of expand_mmac_params().
2548                  * Therefore, we have to do it explicitly here.
2549                  */
2550                 j = if_condition(expand_mmac_params(tline->next), i);
2551                 tline->next = NULL; /* it got freed */
2552                 istk->conds->state =
2553                     j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2554                 break;
2555         }
2556         free_tlist(origline);
2557         return DIRECTIVE_FOUND;
2558
2559     case PP_ELSE:
2560         if (tline->next)
2561             error_precond(ERR_WARNING|ERR_PASS1,
2562                           "trailing garbage after `%%else' ignored");
2563         if (!istk->conds)
2564             error(ERR_FATAL, "`%%else': no matching `%%if'");
2565         switch(istk->conds->state) {
2566             case COND_IF_TRUE:
2567             case COND_DONE:
2568                 istk->conds->state = COND_ELSE_FALSE;
2569                 break;
2570
2571             case COND_NEVER:
2572                 break;
2573
2574             case COND_IF_FALSE:
2575                 istk->conds->state = COND_ELSE_TRUE;
2576                 break;
2577
2578             case COND_ELSE_TRUE:
2579             case COND_ELSE_FALSE:
2580                 error_precond(ERR_WARNING|ERR_PASS1,
2581                               "`%%else' after `%%else' ignored.");
2582                 istk->conds->state = COND_NEVER;
2583                 break;
2584         }
2585         free_tlist(origline);
2586         return DIRECTIVE_FOUND;
2587
2588     case PP_ENDIF:
2589         if (tline->next)
2590             error_precond(ERR_WARNING|ERR_PASS1,
2591                           "trailing garbage after `%%endif' ignored");
2592         if (!istk->conds)
2593             error(ERR_FATAL, "`%%endif': no matching `%%if'");
2594         cond = istk->conds;
2595         istk->conds = cond->next;
2596         nasm_free(cond);
2597         free_tlist(origline);
2598         return DIRECTIVE_FOUND;
2599                 
2600         case PP_RMACRO:
2601         case PP_RIMACRO:
2602     case PP_MACRO:
2603     case PP_IMACRO:
2604         if (defining) {
2605             error(ERR_FATAL,
2606                   "`%%%smacro': already defining a macro",
2607                   (i == PP_IMACRO ? "i" :
2608                                    i == PP_RMACRO ? "r" :
2609                                    i == PP_RIMACRO ? "ri" : ""));
2610             return DIRECTIVE_FOUND;
2611         }
2612     defining = nasm_malloc(sizeof(MMacro));
2613         defining->max_depth = (((i == PP_RMACRO) || (i == PP_RIMACRO))
2614                                                         ? (DEADMAN_LIMIT)  : 0);
2615         defining->casesense = ((i == PP_MACRO) || (i == PP_RMACRO));
2616         if (!parse_mmacro_spec(tline, defining, pp_directives[i])) {
2617             nasm_free(defining);
2618             defining = NULL;
2619             return DIRECTIVE_FOUND;
2620         }
2621
2622         mmac = (MMacro *) hash_findix(&mmacros, defining->name);
2623         while (mmac) {
2624             if (!strcmp(mmac->name, defining->name) &&
2625                 (mmac->nparam_min <= defining->nparam_max
2626                  || defining->plus)
2627                 && (defining->nparam_min <= mmac->nparam_max
2628                     || mmac->plus)) {
2629                 error(ERR_WARNING|ERR_PASS1,
2630                       "redefining multi-line macro `%s'", defining->name);
2631                 return DIRECTIVE_FOUND;
2632             }
2633             mmac = mmac->next;
2634         }
2635         free_tlist(origline);
2636         return DIRECTIVE_FOUND;
2637
2638     case PP_ENDM:
2639     case PP_ENDMACRO:
2640         if (! (defining && defining->name)) {
2641             error(ERR_NONFATAL, "`%s': not defining a macro", tline->text);
2642             return DIRECTIVE_FOUND;
2643         }
2644         mmhead = (MMacro **) hash_findi_add(&mmacros, defining->name);
2645         defining->next = *mmhead;
2646         *mmhead = defining;
2647         defining = NULL;
2648         free_tlist(origline);
2649         return DIRECTIVE_FOUND;
2650
2651         case PP_EXITMACRO:
2652         /*
2653          * We must search along istk->expansion until we hit a
2654          * macro-end marker for a macro with a name. Then we set
2655          * its `in_progress' flag to 0.
2656          */
2657                 for (l = istk->expansion; l; l = l->next)
2658             if (l->finishes && l->finishes->name)
2659                 break;
2660
2661         if (l) {
2662                         l->finishes->in_progress = 0;
2663         } else {
2664             error(ERR_NONFATAL, "`%%exitmacro' not within `%%macro' block");
2665                 }
2666         free_tlist(origline);
2667         return DIRECTIVE_FOUND;
2668
2669     case PP_UNMACRO:
2670     case PP_UNIMACRO:
2671     {
2672         MMacro **mmac_p;
2673         MMacro spec;
2674
2675         spec.casesense = (i == PP_UNMACRO);
2676         if (!parse_mmacro_spec(tline, &spec, pp_directives[i])) {
2677             return DIRECTIVE_FOUND;
2678         }
2679         mmac_p = (MMacro **) hash_findi(&mmacros, spec.name, NULL);
2680         while (mmac_p && *mmac_p) {
2681             mmac = *mmac_p;
2682             if (mmac->casesense == spec.casesense &&
2683                 !mstrcmp(mmac->name, spec.name, spec.casesense) &&
2684                 mmac->nparam_min == spec.nparam_min &&
2685                 mmac->nparam_max == spec.nparam_max &&
2686                 mmac->plus == spec.plus) {
2687                 *mmac_p = mmac->next;
2688                 free_mmacro(mmac);
2689             } else {
2690                 mmac_p = &mmac->next;
2691             }
2692         }
2693         free_tlist(origline);
2694         free_tlist(spec.dlist);
2695         return DIRECTIVE_FOUND;
2696     }
2697
2698     case PP_ROTATE:
2699         if (tline->next && tline->next->type == TOK_WHITESPACE)
2700             tline = tline->next;
2701         if (tline->next == NULL) {
2702             free_tlist(origline);
2703             error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2704             return DIRECTIVE_FOUND;
2705         }
2706         t = expand_smacro(tline->next);
2707         tline->next = NULL;
2708         free_tlist(origline);
2709         tline = t;
2710         tptr = &t;
2711         tokval.t_type = TOKEN_INVALID;
2712         evalresult =
2713             evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2714         free_tlist(tline);
2715         if (!evalresult)
2716             return DIRECTIVE_FOUND;
2717         if (tokval.t_type)
2718             error(ERR_WARNING|ERR_PASS1,
2719                   "trailing garbage after expression ignored");
2720         if (!is_simple(evalresult)) {
2721             error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2722             return DIRECTIVE_FOUND;
2723         }
2724         mmac = istk->mstk;
2725         while (mmac && !mmac->name)     /* avoid mistaking %reps for macros */
2726             mmac = mmac->next_active;
2727         if (!mmac) {
2728             error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
2729         } else if (mmac->nparam == 0) {
2730             error(ERR_NONFATAL,
2731                   "`%%rotate' invoked within macro without parameters");
2732         } else {
2733             int rotate = mmac->rotate + reloc_value(evalresult);
2734
2735             rotate %= (int)mmac->nparam;
2736             if (rotate < 0)
2737                 rotate += mmac->nparam;
2738
2739             mmac->rotate = rotate;
2740         }
2741         return DIRECTIVE_FOUND;
2742
2743     case PP_REP:
2744         nolist = false;
2745         do {
2746             tline = tline->next;
2747         } while (tok_type_(tline, TOK_WHITESPACE));
2748
2749         if (tok_type_(tline, TOK_ID) &&
2750             nasm_stricmp(tline->text, ".nolist") == 0) {
2751             nolist = true;
2752             do {
2753                 tline = tline->next;
2754             } while (tok_type_(tline, TOK_WHITESPACE));
2755         }
2756
2757         if (tline) {
2758             t = expand_smacro(tline);
2759             tptr = &t;
2760             tokval.t_type = TOKEN_INVALID;
2761             evalresult =
2762                 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2763             if (!evalresult) {
2764                 free_tlist(origline);
2765                 return DIRECTIVE_FOUND;
2766             }
2767             if (tokval.t_type)
2768                 error(ERR_WARNING|ERR_PASS1,
2769                       "trailing garbage after expression ignored");
2770             if (!is_simple(evalresult)) {
2771                 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2772                 return DIRECTIVE_FOUND;
2773             }
2774             count = reloc_value(evalresult) + 1;
2775         } else {
2776             error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2777             count = 0;
2778         }
2779         free_tlist(origline);
2780
2781         tmp_defining = defining;
2782         defining = nasm_malloc(sizeof(MMacro));
2783                 defining->prev = NULL;
2784         defining->name = NULL;  /* flags this macro as a %rep block */
2785         defining->casesense = false;
2786         defining->plus = false;
2787         defining->nolist = nolist;
2788         defining->in_progress = count;
2789                 defining->max_depth = 0;
2790         defining->nparam_min = defining->nparam_max = 0;
2791         defining->defaults = NULL;
2792         defining->dlist = NULL;
2793         defining->expansion = NULL;
2794         defining->next_active = istk->mstk;
2795         defining->rep_nest = tmp_defining;
2796         return DIRECTIVE_FOUND;
2797
2798     case PP_ENDREP:
2799         if (!defining || defining->name) {
2800             error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2801             return DIRECTIVE_FOUND;
2802         }
2803
2804         /*
2805          * Now we have a "macro" defined - although it has no name
2806          * and we won't be entering it in the hash tables - we must
2807          * push a macro-end marker for it on to istk->expansion.
2808          * After that, it will take care of propagating itself (a
2809          * macro-end marker line for a macro which is really a %rep
2810          * block will cause the macro to be re-expanded, complete
2811          * with another macro-end marker to ensure the process
2812          * continues) until the whole expansion is forcibly removed
2813          * from istk->expansion by a %exitrep.
2814          */
2815         l = nasm_malloc(sizeof(Line));
2816         l->next = istk->expansion;
2817         l->finishes = defining;
2818         l->first = NULL;
2819         istk->expansion = l;
2820
2821         istk->mstk = defining;
2822
2823         list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2824         tmp_defining = defining;
2825         defining = defining->rep_nest;
2826         free_tlist(origline);
2827         return DIRECTIVE_FOUND;
2828
2829     case PP_EXITREP:
2830         /*
2831          * We must search along istk->expansion until we hit a
2832          * macro-end marker for a macro with no name. Then we set
2833          * its `in_progress' flag to 0.
2834          */
2835         for (l = istk->expansion; l; l = l->next)
2836             if (l->finishes && !l->finishes->name)
2837                 break;
2838
2839         if (l)
2840             l->finishes->in_progress = 1;
2841         else
2842             error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2843         free_tlist(origline);
2844         return DIRECTIVE_FOUND;
2845
2846     case PP_XDEFINE:
2847     case PP_IXDEFINE:
2848     case PP_DEFINE:
2849     case PP_IDEFINE:
2850         casesense = (i == PP_DEFINE || i == PP_XDEFINE);
2851
2852         tline = tline->next;
2853         skip_white_(tline);
2854         tline = expand_id(tline);
2855         if (!tline || (tline->type != TOK_ID &&
2856                        (tline->type != TOK_PREPROC_ID ||
2857                         tline->text[1] != '$'))) {
2858             error(ERR_NONFATAL, "`%s' expects a macro identifier",
2859                   pp_directives[i]);
2860             free_tlist(origline);
2861             return DIRECTIVE_FOUND;
2862         }
2863
2864         ctx = get_ctx(tline->text, &mname, false);
2865         last = tline;
2866         param_start = tline = tline->next;
2867         nparam = 0;
2868
2869         /* Expand the macro definition now for %xdefine and %ixdefine */
2870         if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2871             tline = expand_smacro(tline);
2872
2873         if (tok_is_(tline, "(")) {
2874             /*
2875              * This macro has parameters.
2876              */
2877
2878             tline = tline->next;
2879             while (1) {
2880                 skip_white_(tline);
2881                 if (!tline) {
2882                     error(ERR_NONFATAL, "parameter identifier expected");
2883                     free_tlist(origline);
2884                     return DIRECTIVE_FOUND;
2885                 }
2886                 if (tline->type != TOK_ID) {
2887                     error(ERR_NONFATAL,
2888                           "`%s': parameter identifier expected",
2889                           tline->text);
2890                     free_tlist(origline);
2891                     return DIRECTIVE_FOUND;
2892                 }
2893                 tline->type = TOK_SMAC_PARAM + nparam++;
2894                 tline = tline->next;
2895                 skip_white_(tline);
2896                 if (tok_is_(tline, ",")) {
2897                     tline = tline->next;
2898                 } else {
2899                     if (!tok_is_(tline, ")")) {
2900                         error(ERR_NONFATAL,
2901                               "`)' expected to terminate macro template");
2902                         free_tlist(origline);
2903                         return DIRECTIVE_FOUND;
2904                     }
2905                     break;
2906                 }
2907             }
2908             last = tline;
2909             tline = tline->next;
2910         }
2911         if (tok_type_(tline, TOK_WHITESPACE))
2912             last = tline, tline = tline->next;
2913         macro_start = NULL;
2914         last->next = NULL;
2915         t = tline;
2916         while (t) {
2917             if (t->type == TOK_ID) {
2918                 for (tt = param_start; tt; tt = tt->next)
2919                     if (tt->type >= TOK_SMAC_PARAM &&
2920                         !strcmp(tt->text, t->text))
2921                         t->type = tt->type;
2922             }
2923             tt = t->next;
2924             t->next = macro_start;
2925             macro_start = t;
2926             t = tt;
2927         }
2928         /*
2929          * Good. We now have a macro name, a parameter count, and a
2930          * token list (in reverse order) for an expansion. We ought
2931          * to be OK just to create an SMacro, store it, and let
2932          * free_tlist have the rest of the line (which we have
2933          * carefully re-terminated after chopping off the expansion
2934          * from the end).
2935          */
2936         define_smacro(ctx, mname, casesense, nparam, macro_start);
2937         free_tlist(origline);
2938         return DIRECTIVE_FOUND;
2939
2940     case PP_UNDEF:
2941         tline = tline->next;
2942         skip_white_(tline);
2943         tline = expand_id(tline);
2944         if (!tline || (tline->type != TOK_ID &&
2945                        (tline->type != TOK_PREPROC_ID ||
2946                         tline->text[1] != '$'))) {
2947             error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2948             free_tlist(origline);
2949             return DIRECTIVE_FOUND;
2950         }
2951         if (tline->next) {
2952             error(ERR_WARNING|ERR_PASS1,
2953                   "trailing garbage after macro name ignored");
2954         }
2955
2956         /* Find the context that symbol belongs to */
2957         ctx = get_ctx(tline->text, &mname, false);
2958         undef_smacro(ctx, mname);
2959         free_tlist(origline);
2960         return DIRECTIVE_FOUND;
2961
2962     case PP_DEFSTR:
2963     case PP_IDEFSTR:
2964         casesense = (i == PP_DEFSTR);
2965
2966         tline = tline->next;
2967         skip_white_(tline);
2968         tline = expand_id(tline);
2969         if (!tline || (tline->type != TOK_ID &&
2970                        (tline->type != TOK_PREPROC_ID ||
2971                         tline->text[1] != '$'))) {
2972             error(ERR_NONFATAL, "`%s' expects a macro identifier",
2973                   pp_directives[i]);
2974             free_tlist(origline);
2975             return DIRECTIVE_FOUND;
2976         }
2977
2978         ctx = get_ctx(tline->text, &mname, false);
2979         last = tline;
2980         tline = expand_smacro(tline->next);
2981         last->next = NULL;
2982
2983         while (tok_type_(tline, TOK_WHITESPACE))
2984             tline = delete_Token(tline);
2985
2986         p = detoken(tline, false);
2987         macro_start = nasm_malloc(sizeof(*macro_start));
2988         macro_start->next = NULL;
2989         macro_start->text = nasm_quote(p, strlen(p));
2990         macro_start->type = TOK_STRING;
2991         macro_start->a.mac = NULL;
2992         nasm_free(p);
2993
2994         /*
2995          * We now have a macro name, an implicit parameter count of
2996          * zero, and a string token to use as an expansion. Create
2997          * and store an SMacro.
2998          */
2999         define_smacro(ctx, mname, casesense, 0, macro_start);
3000         free_tlist(origline);
3001         return DIRECTIVE_FOUND;
3002                 
3003         case PP_DEFTOK:
3004         case PP_IDEFTOK:
3005         casesense = (i == PP_DEFTOK);
3006
3007         tline = tline->next;
3008         skip_white_(tline);
3009         tline = expand_id(tline);
3010         if (!tline || (tline->type != TOK_ID &&
3011                        (tline->type != TOK_PREPROC_ID ||
3012                         tline->text[1] != '$'))) {
3013             error(ERR_NONFATAL,
3014                   "`%s' expects a macro identifier as first parameter",
3015                         pp_directives[i]);
3016             free_tlist(origline);
3017             return DIRECTIVE_FOUND;
3018         }
3019         ctx = get_ctx(tline->text, &mname, false);
3020         last = tline;
3021         tline = expand_smacro(tline->next);
3022         last->next = NULL;
3023
3024         t = tline;
3025         while (tok_type_(t, TOK_WHITESPACE))
3026             t = t->next;
3027         /* t should now point to the string */
3028         if (t->type != TOK_STRING) {
3029             error(ERR_NONFATAL,
3030                   "`%s` requires string as second parameter",
3031                         pp_directives[i]);
3032             free_tlist(tline);
3033             free_tlist(origline);
3034             return DIRECTIVE_FOUND;
3035         }
3036
3037                 nasm_unquote(t->text, NULL);
3038                 macro_start = tokenize(t->text);
3039
3040         /*
3041          * We now have a macro name, an implicit parameter count of
3042          * zero, and a numeric token to use as an expansion. Create
3043          * and store an SMacro.
3044          */
3045         define_smacro(ctx, mname, casesense, 0, macro_start);
3046         free_tlist(tline);
3047         free_tlist(origline);
3048         return DIRECTIVE_FOUND;
3049
3050     case PP_PATHSEARCH:
3051     {
3052         FILE *fp;
3053         StrList *xsl = NULL;
3054         StrList **xst = &xsl;
3055
3056         casesense = true;
3057
3058         tline = tline->next;
3059         skip_white_(tline);
3060         tline = expand_id(tline);
3061         if (!tline || (tline->type != TOK_ID &&
3062                        (tline->type != TOK_PREPROC_ID ||
3063                         tline->text[1] != '$'))) {
3064             error(ERR_NONFATAL,
3065                   "`%%pathsearch' expects a macro identifier as first parameter");
3066             free_tlist(origline);
3067             return DIRECTIVE_FOUND;
3068         }
3069         ctx = get_ctx(tline->text, &mname, false);
3070         last = tline;
3071         tline = expand_smacro(tline->next);
3072         last->next = NULL;
3073
3074         t = tline;
3075         while (tok_type_(t, TOK_WHITESPACE))
3076             t = t->next;
3077
3078         if (!t || (t->type != TOK_STRING &&
3079                    t->type != TOK_INTERNAL_STRING)) {
3080             error(ERR_NONFATAL, "`%%pathsearch' expects a file name");
3081             free_tlist(tline);
3082             free_tlist(origline);
3083             return DIRECTIVE_FOUND;     /* but we did _something_ */
3084         }
3085         if (t->next)
3086             error(ERR_WARNING|ERR_PASS1,
3087                   "trailing garbage after `%%pathsearch' ignored");
3088         p = t->text;
3089         if (t->type != TOK_INTERNAL_STRING)
3090             nasm_unquote(p, NULL);
3091
3092         fp = inc_fopen(p, &xsl, &xst, true);
3093         if (fp) {
3094             p = xsl->str;
3095             fclose(fp);         /* Don't actually care about the file */
3096         }
3097         macro_start = nasm_malloc(sizeof(*macro_start));
3098         macro_start->next = NULL;
3099         macro_start->text = nasm_quote(p, strlen(p));
3100         macro_start->type = TOK_STRING;
3101         macro_start->a.mac = NULL;
3102         if (xsl)
3103             nasm_free(xsl);
3104
3105         /*
3106          * We now have a macro name, an implicit parameter count of
3107          * zero, and a string token to use as an expansion. Create
3108          * and store an SMacro.
3109          */
3110         define_smacro(ctx, mname, casesense, 0, macro_start);
3111         free_tlist(tline);
3112         free_tlist(origline);
3113         return DIRECTIVE_FOUND;
3114     }
3115
3116     case PP_STRLEN:
3117         casesense = true;
3118
3119         tline = tline->next;
3120         skip_white_(tline);
3121         tline = expand_id(tline);
3122         if (!tline || (tline->type != TOK_ID &&
3123                        (tline->type != TOK_PREPROC_ID ||
3124                         tline->text[1] != '$'))) {
3125             error(ERR_NONFATAL,
3126                   "`%%strlen' expects a macro identifier as first parameter");
3127             free_tlist(origline);
3128             return DIRECTIVE_FOUND;
3129         }
3130         ctx = get_ctx(tline->text, &mname, false);
3131         last = tline;
3132         tline = expand_smacro(tline->next);
3133         last->next = NULL;
3134
3135         t = tline;
3136         while (tok_type_(t, TOK_WHITESPACE))
3137             t = t->next;
3138         /* t should now point to the string */
3139         if (t->type != TOK_STRING) {
3140             error(ERR_NONFATAL,
3141                   "`%%strlen` requires string as second parameter");
3142             free_tlist(tline);
3143             free_tlist(origline);
3144             return DIRECTIVE_FOUND;
3145         }
3146
3147         macro_start = nasm_malloc(sizeof(*macro_start));
3148         macro_start->next = NULL;
3149         make_tok_num(macro_start, nasm_unquote(t->text, NULL));
3150         macro_start->a.mac = NULL;
3151
3152         /*
3153          * We now have a macro name, an implicit parameter count of
3154          * zero, and a numeric token to use as an expansion. Create
3155          * and store an SMacro.
3156          */
3157         define_smacro(ctx, mname, casesense, 0, macro_start);
3158         free_tlist(tline);
3159         free_tlist(origline);
3160         return DIRECTIVE_FOUND;
3161
3162     case PP_STRCAT:
3163         casesense = true;
3164
3165         tline = tline->next;
3166         skip_white_(tline);
3167         tline = expand_id(tline);
3168         if (!tline || (tline->type != TOK_ID &&
3169                        (tline->type != TOK_PREPROC_ID ||
3170                         tline->text[1] != '$'))) {
3171             error(ERR_NONFATAL,
3172                   "`%%strcat' expects a macro identifier as first parameter");
3173             free_tlist(origline);
3174             return DIRECTIVE_FOUND;
3175         }
3176         ctx = get_ctx(tline->text, &mname, false);
3177         last = tline;
3178         tline = expand_smacro(tline->next);
3179         last->next = NULL;
3180
3181         len = 0;
3182         for (t = tline; t; t = t->next) {
3183             switch (t->type) {
3184             case TOK_WHITESPACE:
3185                 break;
3186             case TOK_STRING:
3187                 len += t->a.len = nasm_unquote(t->text, NULL);
3188                 break;
3189             case TOK_OTHER:
3190                 if (!strcmp(t->text, ",")) /* permit comma separators */
3191                     break;
3192                 /* else fall through */
3193             default:
3194                 error(ERR_NONFATAL,
3195                       "non-string passed to `%%strcat' (%d)", t->type);
3196                 free_tlist(tline);
3197                 free_tlist(origline);
3198                 return DIRECTIVE_FOUND;
3199             }
3200         }
3201
3202         p = pp = nasm_malloc(len);
3203         t = tline;
3204         for (t = tline; t; t = t->next) {
3205             if (t->type == TOK_STRING) {
3206                 memcpy(p, t->text, t->a.len);
3207                 p += t->a.len;
3208             }
3209         }
3210
3211         /*
3212          * We now have a macro name, an implicit parameter count of
3213          * zero, and a numeric token to use as an expansion. Create
3214          * and store an SMacro.
3215          */
3216         macro_start = new_Token(NULL, TOK_STRING, NULL, 0);
3217         macro_start->text = nasm_quote(pp, len);
3218         nasm_free(pp);
3219         define_smacro(ctx, mname, casesense, 0, macro_start);
3220         free_tlist(tline);
3221         free_tlist(origline);
3222         return DIRECTIVE_FOUND;
3223
3224     case PP_SUBSTR:
3225     {
3226         int64_t a1, a2;
3227         size_t len;
3228
3229         casesense = true;
3230
3231         tline = tline->next;
3232         skip_white_(tline);
3233         tline = expand_id(tline);
3234         if (!tline || (tline->type != TOK_ID &&
3235                        (tline->type != TOK_PREPROC_ID ||
3236                         tline->text[1] != '$'))) {
3237             error(ERR_NONFATAL,
3238                   "`%%substr' expects a macro identifier as first parameter");
3239             free_tlist(origline);
3240             return DIRECTIVE_FOUND;
3241         }
3242         ctx = get_ctx(tline->text, &mname, false);
3243         last = tline;
3244         tline = expand_smacro(tline->next);
3245         last->next = NULL;
3246
3247         t = tline->next;
3248         while (tok_type_(t, TOK_WHITESPACE))
3249             t = t->next;
3250
3251         /* t should now point to the string */
3252         if (t->type != TOK_STRING) {
3253             error(ERR_NONFATAL,
3254                   "`%%substr` requires string as second parameter");
3255             free_tlist(tline);
3256             free_tlist(origline);
3257             return DIRECTIVE_FOUND;
3258         }
3259
3260         tt = t->next;
3261         tptr = &tt;
3262         tokval.t_type = TOKEN_INVALID;
3263         evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3264                               pass, error, NULL);
3265         if (!evalresult) {
3266             free_tlist(tline);
3267             free_tlist(origline);
3268             return DIRECTIVE_FOUND;
3269         } else if (!is_simple(evalresult)) {
3270             error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3271             free_tlist(tline);
3272             free_tlist(origline);
3273             return DIRECTIVE_FOUND;
3274         }
3275         a1 = evalresult->value-1;
3276
3277         while (tok_type_(tt, TOK_WHITESPACE))
3278             tt = tt->next;
3279         if (!tt) {
3280             a2 = 1;             /* Backwards compatibility: one character */
3281         } else {
3282             tokval.t_type = TOKEN_INVALID;
3283             evalresult = evaluate(ppscan, tptr, &tokval, NULL,
3284                                   pass, error, NULL);
3285             if (!evalresult) {
3286                 free_tlist(tline);
3287                 free_tlist(origline);
3288                 return DIRECTIVE_FOUND;
3289             } else if (!is_simple(evalresult)) {
3290                 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
3291                 free_tlist(tline);
3292                 free_tlist(origline);
3293                 return DIRECTIVE_FOUND;
3294             }
3295             a2 = evalresult->value;
3296         }
3297
3298         len = nasm_unquote(t->text, NULL);
3299         if (a2 < 0)
3300             a2 = a2+1+len-a1;
3301         if (a1+a2 > (int64_t)len)
3302             a2 = len-a1;
3303
3304         macro_start = nasm_malloc(sizeof(*macro_start));
3305         macro_start->next = NULL;
3306         macro_start->text = nasm_quote((a1 < 0) ? "" : t->text+a1, a2);
3307         macro_start->type = TOK_STRING;
3308         macro_start->a.mac = NULL;
3309
3310         /*
3311          * We now have a macro name, an implicit parameter count of
3312          * zero, and a numeric token to use as an expansion. Create
3313          * and store an SMacro.
3314          */
3315         define_smacro(ctx, mname, casesense, 0, macro_start);
3316         free_tlist(tline);
3317         free_tlist(origline);
3318         return DIRECTIVE_FOUND;
3319     }
3320
3321     case PP_ASSIGN:
3322     case PP_IASSIGN:
3323         casesense = (i == PP_ASSIGN);
3324
3325         tline = tline->next;
3326         skip_white_(tline);
3327         tline = expand_id(tline);
3328         if (!tline || (tline->type != TOK_ID &&
3329                        (tline->type != TOK_PREPROC_ID ||
3330                         tline->text[1] != '$'))) {
3331             error(ERR_NONFATAL,
3332                   "`%%%sassign' expects a macro identifier",
3333                   (i == PP_IASSIGN ? "i" : ""));
3334             free_tlist(origline);
3335             return DIRECTIVE_FOUND;
3336         }
3337         ctx = get_ctx(tline->text, &mname, false);
3338         last = tline;
3339         tline = expand_smacro(tline->next);
3340         last->next = NULL;
3341
3342         t = tline;
3343         tptr = &t;
3344         tokval.t_type = TOKEN_INVALID;
3345         evalresult =
3346             evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
3347         free_tlist(tline);
3348         if (!evalresult) {
3349             free_tlist(origline);
3350             return DIRECTIVE_FOUND;
3351         }
3352
3353         if (tokval.t_type)
3354             error(ERR_WARNING|ERR_PASS1,
3355                   "trailing garbage after expression ignored");
3356
3357         if (!is_simple(evalresult)) {
3358             error(ERR_NONFATAL,
3359                   "non-constant value given to `%%%sassign'",
3360                   (i == PP_IASSIGN ? "i" : ""));
3361             free_tlist(origline);
3362             return DIRECTIVE_FOUND;
3363         }
3364
3365         macro_start = nasm_malloc(sizeof(*macro_start));
3366         macro_start->next = NULL;
3367         make_tok_num(macro_start, reloc_value(evalresult));
3368         macro_start->a.mac = NULL;
3369
3370         /*
3371          * We now have a macro name, an implicit parameter count of
3372          * zero, and a numeric token to use as an expansion. Create
3373          * and store an SMacro.
3374          */
3375         define_smacro(ctx, mname, casesense, 0, macro_start);
3376         free_tlist(origline);
3377         return DIRECTIVE_FOUND;
3378
3379     case PP_LINE:
3380         /*
3381          * Syntax is `%line nnn[+mmm] [filename]'
3382          */
3383         tline = tline->next;
3384         skip_white_(tline);
3385         if (!tok_type_(tline, TOK_NUMBER)) {
3386             error(ERR_NONFATAL, "`%%line' expects line number");
3387             free_tlist(origline);
3388             return DIRECTIVE_FOUND;
3389         }
3390         k = readnum(tline->text, &err);
3391         m = 1;
3392         tline = tline->next;
3393         if (tok_is_(tline, "+")) {
3394             tline = tline->next;
3395             if (!tok_type_(tline, TOK_NUMBER)) {
3396                 error(ERR_NONFATAL, "`%%line' expects line increment");
3397                 free_tlist(origline);
3398                 return DIRECTIVE_FOUND;
3399             }
3400             m = readnum(tline->text, &err);
3401             tline = tline->next;
3402         }
3403         skip_white_(tline);
3404         src_set_linnum(k);
3405         istk->lineinc = m;
3406         if (tline) {
3407             nasm_free(src_set_fname(detoken(tline, false)));
3408         }
3409         free_tlist(origline);
3410         return DIRECTIVE_FOUND;
3411
3412     default:
3413         error(ERR_FATAL,
3414               "preprocessor directive `%s' not yet implemented",
3415               pp_directives[i]);
3416         return DIRECTIVE_FOUND;
3417     }
3418 }
3419
3420 /*
3421  * Ensure that a macro parameter contains a condition code and
3422  * nothing else. Return the condition code index if so, or -1
3423  * otherwise.
3424  */
3425 static int find_cc(Token * t)
3426 {
3427     Token *tt;
3428     int i, j, k, m;
3429
3430     if (!t)
3431             return -1;          /* Probably a %+ without a space */
3432
3433     skip_white_(t);
3434     if (t->type != TOK_ID)
3435         return -1;
3436     tt = t->next;
3437     skip_white_(tt);
3438     if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3439         return -1;
3440
3441     i = -1;
3442     j = elements(conditions);
3443     while (j - i > 1) {
3444         k = (j + i) / 2;
3445         m = nasm_stricmp(t->text, conditions[k]);
3446         if (m == 0) {
3447             i = k;
3448             j = -2;
3449             break;
3450         } else if (m < 0) {
3451             j = k;
3452         } else
3453             i = k;
3454     }
3455     if (j != -2)
3456         return -1;
3457     return i;
3458 }
3459
3460 static bool paste_tokens(Token **head, bool handle_paste_tokens)
3461 {
3462     Token **tail, *t, *tt;
3463     Token **paste_head;
3464     bool did_paste = false;
3465     char *tmp;
3466
3467     /* Now handle token pasting... */
3468     paste_head = NULL;
3469     tail = head;
3470     while ((t = *tail) && (tt = t->next)) {
3471         switch (t->type) {
3472         case TOK_WHITESPACE:
3473             if (tt->type == TOK_WHITESPACE) {
3474                 /* Zap adjacent whitespace tokens */
3475                 t->next = delete_Token(tt);
3476             } else {
3477                 /* Do not advance paste_head here */
3478                 tail = &t->next;
3479             }
3480             break;
3481         case TOK_ID:
3482         case TOK_PREPROC_ID:
3483         case TOK_NUMBER:
3484         case TOK_FLOAT:
3485         {
3486             size_t len = 0;
3487             char *tmp, *p;
3488
3489             while (tt && (tt->type == TOK_ID || tt->type == TOK_PREPROC_ID ||
3490                           tt->type == TOK_NUMBER || tt->type == TOK_FLOAT ||
3491                           tt->type == TOK_OTHER)) {
3492                 len += strlen(tt->text);
3493                 tt = tt->next;
3494             }
3495
3496             /* Now tt points to the first token after the potential
3497                paste area... */
3498             if (tt != t->next) {
3499                 /* We have at least two tokens... */
3500                 len += strlen(t->text);
3501                 p = tmp = nasm_malloc(len+1);
3502
3503                 while (t != tt) {
3504                     strcpy(p, t->text);
3505                     p = strchr(p, '\0');
3506                     t = delete_Token(t);
3507                 }
3508
3509                 t = *tail = tokenize(tmp);
3510                 nasm_free(tmp);
3511
3512                 while (t->next) {
3513                     tail = &t->next;
3514                     t = t->next;
3515                 }
3516                 t->next = tt;   /* Attach the remaining token chain */
3517
3518                 did_paste = true;
3519             }
3520             paste_head = tail;
3521             tail = &t->next;
3522             break;
3523         }
3524         case TOK_PASTE:         /* %+ */
3525             if (handle_paste_tokens) {
3526                 /* Zap %+ and whitespace tokens to the right */
3527                 while (t && (t->type == TOK_WHITESPACE ||
3528                              t->type == TOK_PASTE))
3529                     t = *tail = delete_Token(t);
3530                 if (!paste_head || !t)
3531                     break;      /* Nothing to paste with */
3532                 tail = paste_head;
3533                 t = *tail;
3534                 tt = t->next;
3535                 while (tok_type_(tt, TOK_WHITESPACE))
3536                     tt = t->next = delete_Token(tt);
3537
3538                 if (tt) {
3539                     tmp = nasm_strcat(t->text, tt->text);
3540                     delete_Token(t);
3541                     tt = delete_Token(tt);
3542                     t = *tail = tokenize(tmp);
3543                     nasm_free(tmp);
3544                     while (t->next) {
3545                         tail = &t->next;
3546                         t = t->next;
3547                     }
3548                     t->next = tt; /* Attach the remaining token chain */
3549                     did_paste = true;
3550                 }
3551                 paste_head = tail;
3552                 tail = &t->next;
3553                 break;
3554             }
3555             /* else fall through */
3556         default:
3557             tail = paste_head = &t->next;
3558             break;
3559         }
3560     }
3561     return did_paste;
3562 }
3563 /*
3564  * Expand MMacro-local things: parameter references (%0, %n, %+n,
3565  * %-n) and MMacro-local identifiers (%%foo) as well as
3566  * macro indirection (%[...]).
3567  */
3568 static Token *expand_mmac_params(Token * tline)
3569 {
3570     Token *t, *tt, **tail, *thead;
3571     bool changed = false;
3572
3573     tail = &thead;
3574     thead = NULL;
3575
3576     while (tline) {
3577         if (tline->type == TOK_PREPROC_ID &&
3578             (((tline->text[1] == '+' || tline->text[1] == '-')
3579               && tline->text[2]) || tline->text[1] == '%'
3580              || (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
3581             char *text = NULL;
3582             int type = 0, cc;   /* type = 0 to placate optimisers */
3583             char tmpbuf[30];
3584             unsigned int n;
3585             int i;
3586             MMacro *mac;
3587
3588             t = tline;
3589             tline = tline->next;
3590
3591             mac = istk->mstk;
3592             while (mac && !mac->name)   /* avoid mistaking %reps for macros */
3593                 mac = mac->next_active;
3594             if (!mac)
3595                 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3596             else
3597                 switch (t->text[1]) {
3598                     /*
3599                      * We have to make a substitution of one of the
3600                      * forms %1, %-1, %+1, %%foo, %0.
3601                      */
3602                 case '0':
3603                     type = TOK_NUMBER;
3604                     snprintf(tmpbuf, sizeof(tmpbuf), "%d", mac->nparam);
3605                     text = nasm_strdup(tmpbuf);
3606                     break;
3607                 case '%':
3608                     type = TOK_ID;
3609                     snprintf(tmpbuf, sizeof(tmpbuf), "..@%"PRIu64".",
3610                              mac->unique);
3611                     text = nasm_strcat(tmpbuf, t->text + 2);
3612                     break;
3613                 case '-':
3614                     n = atoi(t->text + 2) - 1;
3615                     if (n >= mac->nparam)
3616                         tt = NULL;
3617                     else {
3618                         if (mac->nparam > 1)
3619                             n = (n + mac->rotate) % mac->nparam;
3620                         tt = mac->params[n];
3621                     }
3622                     cc = find_cc(tt);
3623                     if (cc == -1) {
3624                         error(ERR_NONFATAL,
3625                               "macro parameter %d is not a condition code",
3626                               n + 1);
3627                         text = NULL;
3628                     } else {
3629                         type = TOK_ID;
3630                         if (inverse_ccs[cc] == -1) {
3631                             error(ERR_NONFATAL,
3632                                   "condition code `%s' is not invertible",
3633                                   conditions[cc]);
3634                             text = NULL;
3635                         } else
3636                             text = nasm_strdup(conditions[inverse_ccs[cc]]);
3637                     }
3638                     break;
3639                 case '+':
3640                     n = atoi(t->text + 2) - 1;
3641                     if (n >= mac->nparam)
3642                         tt = NULL;
3643                     else {
3644                         if (mac->nparam > 1)
3645                             n = (n + mac->rotate) % mac->nparam;
3646                         tt = mac->params[n];
3647                     }
3648                     cc = find_cc(tt);
3649                     if (cc == -1) {
3650                         error(ERR_NONFATAL,
3651                               "macro parameter %d is not a condition code",
3652                               n + 1);
3653                         text = NULL;
3654                     } else {
3655                         type = TOK_ID;
3656                         text = nasm_strdup(conditions[cc]);
3657                     }
3658                     break;
3659                 default:
3660                     n = atoi(t->text + 1) - 1;
3661                     if (n >= mac->nparam)
3662                         tt = NULL;
3663                     else {
3664                         if (mac->nparam > 1)
3665                             n = (n + mac->rotate) % mac->nparam;
3666                         tt = mac->params[n];
3667                     }
3668                     if (tt) {
3669                         for (i = 0; i < mac->paramlen[n]; i++) {
3670                             *tail = new_Token(NULL, tt->type, tt->text, 0);
3671                             tail = &(*tail)->next;
3672                             tt = tt->next;
3673                         }
3674                     }
3675                     text = NULL;        /* we've done it here */
3676                     break;
3677                 }
3678             if (!text) {
3679                 delete_Token(t);
3680             } else {
3681                 *tail = t;
3682                 tail = &t->next;
3683                 t->type = type;
3684                 nasm_free(t->text);
3685                 t->text = text;
3686                 t->a.mac = NULL;
3687             }
3688             changed = true;
3689             continue;
3690         } else if (tline->type == TOK_INDIRECT) {
3691             t = tline;
3692             tline = tline->next;
3693             tt = tokenize(t->text);
3694             tt = expand_mmac_params(tt);
3695             tt = expand_smacro(tt);
3696             *tail = tt;
3697             while (tt) {
3698                 tt->a.mac = NULL; /* Necessary? */
3699                 tail = &tt->next;
3700                 tt = tt->next;
3701             }
3702             delete_Token(t);
3703             changed = true;
3704         } else {
3705             t = *tail = tline;
3706             tline = tline->next;
3707             t->a.mac = NULL;
3708             tail = &t->next;
3709         }
3710     }
3711     *tail = NULL;
3712
3713     if (changed)
3714         paste_tokens(&thead, false);
3715
3716     return thead;
3717 }
3718
3719 /*
3720  * Expand all single-line macro calls made in the given line.
3721  * Return the expanded version of the line. The original is deemed
3722  * to be destroyed in the process. (In reality we'll just move
3723  * Tokens from input to output a lot of the time, rather than
3724  * actually bothering to destroy and replicate.)
3725  */
3726
3727 static Token *expand_smacro(Token * tline)
3728 {
3729     Token *t, *tt, *mstart, **tail, *thead;
3730     struct hash_table *smtbl;
3731     SMacro *head = NULL, *m;
3732     Token **params;
3733     int *paramsize;
3734     unsigned int nparam, sparam;
3735     int brackets;
3736     Token *org_tline = tline;
3737     Context *ctx;
3738     const char *mname;
3739     int deadman = DEADMAN_LIMIT;
3740     bool expanded;
3741
3742     /*
3743      * Trick: we should avoid changing the start token pointer since it can
3744      * be contained in "next" field of other token. Because of this
3745      * we allocate a copy of first token and work with it; at the end of
3746      * routine we copy it back
3747      */
3748     if (org_tline) {
3749         tline =
3750             new_Token(org_tline->next, org_tline->type, org_tline->text,
3751                       0);
3752         tline->a.mac = org_tline->a.mac;
3753         nasm_free(org_tline->text);
3754         org_tline->text = NULL;
3755     }
3756
3757     expanded = true;            /* Always expand %+ at least once */
3758
3759 again:
3760     tail = &thead;
3761     thead = NULL;
3762
3763     while (tline) {             /* main token loop */
3764         if (!--deadman) {
3765             error(ERR_NONFATAL, "interminable macro recursion");
3766             break;
3767         }
3768
3769         if ((mname = tline->text)) {
3770             /* if this token is a local macro, look in local context */
3771             if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3772                 ctx = get_ctx(mname, &mname, true);
3773             else
3774                 ctx = NULL;
3775             smtbl = ctx ? &ctx->localmac : &smacros;
3776             head = (SMacro *) hash_findix(smtbl, mname);
3777
3778             /*
3779              * We've hit an identifier. As in is_mmacro below, we first
3780              * check whether the identifier is a single-line macro at
3781              * all, then think about checking for parameters if
3782              * necessary.
3783              */
3784             for (m = head; m; m = m->next)
3785                 if (!mstrcmp(m->name, mname, m->casesense))
3786                     break;
3787             if (m) {
3788                 mstart = tline;
3789                 params = NULL;
3790                 paramsize = NULL;
3791                 if (m->nparam == 0) {
3792                     /*
3793                      * Simple case: the macro is parameterless. Discard the
3794                      * one token that the macro call took, and push the
3795                      * expansion back on the to-do stack.
3796                      */
3797                     if (!m->expansion) {
3798                         if (!strcmp("__FILE__", m->name)) {
3799                             int32_t num = 0;
3800                             char *file = NULL;
3801                             src_get(&num, &file);
3802                             tline->text = nasm_quote(file, strlen(file));
3803                             tline->type = TOK_STRING;
3804                             nasm_free(file);
3805                             continue;
3806                         }
3807                         if (!strcmp("__LINE__", m->name)) {
3808                             nasm_free(tline->text);
3809                             make_tok_num(tline, src_get_linnum());
3810                             continue;
3811                         }
3812                         if (!strcmp("__BITS__", m->name)) {
3813                             nasm_free(tline->text);
3814                             make_tok_num(tline, globalbits);
3815                             continue;
3816                         }
3817                         tline = delete_Token(tline);
3818                         continue;
3819                     }
3820                 } else {
3821                     /*
3822                      * Complicated case: at least one macro with this name
3823                      * exists and takes parameters. We must find the
3824                      * parameters in the call, count them, find the SMacro
3825                      * that corresponds to that form of the macro call, and
3826                      * substitute for the parameters when we expand. What a
3827                      * pain.
3828                      */
3829                     /*tline = tline->next;
3830                        skip_white_(tline); */
3831                     do {
3832                         t = tline->next;
3833                         while (tok_type_(t, TOK_SMAC_END)) {
3834                             t->a.mac->in_progress = false;
3835                             t->text = NULL;
3836                             t = tline->next = delete_Token(t);
3837                         }
3838                         tline = t;
3839                     } while (tok_type_(tline, TOK_WHITESPACE));
3840                     if (!tok_is_(tline, "(")) {
3841                         /*
3842                          * This macro wasn't called with parameters: ignore
3843                          * the call. (Behaviour borrowed from gnu cpp.)
3844                          */
3845                         tline = mstart;
3846                         m = NULL;
3847                     } else {
3848                         int paren = 0;
3849                         int white = 0;
3850                         brackets = 0;
3851                         nparam = 0;
3852                         sparam = PARAM_DELTA;
3853                         params = nasm_malloc(sparam * sizeof(Token *));
3854                         params[0] = tline->next;
3855                         paramsize = nasm_malloc(sparam * sizeof(int));
3856                         paramsize[0] = 0;
3857                         while (true) {  /* parameter loop */
3858                             /*
3859                              * For some unusual expansions
3860                              * which concatenates function call
3861                              */
3862                             t = tline->next;
3863                             while (tok_type_(t, TOK_SMAC_END)) {
3864                                 t->a.mac->in_progress = false;
3865                                 t->text = NULL;
3866                                 t = tline->next = delete_Token(t);
3867                             }
3868                             tline = t;
3869
3870                             if (!tline) {
3871                                 error(ERR_NONFATAL,
3872                                       "macro call expects terminating `)'");
3873                                 break;
3874                             }
3875                             if (tline->type == TOK_WHITESPACE
3876                                 && brackets <= 0) {
3877                                 if (paramsize[nparam])
3878                                     white++;
3879                                 else
3880                                     params[nparam] = tline->next;
3881                                 continue;       /* parameter loop */
3882                             }
3883                             if (tline->type == TOK_OTHER
3884                                 && tline->text[1] == 0) {
3885                                 char ch = tline->text[0];
3886                                 if (ch == ',' && !paren && brackets <= 0) {
3887                                     if (++nparam >= sparam) {
3888                                         sparam += PARAM_DELTA;
3889                                         params = nasm_realloc(params,
3890                                                               sparam *
3891                                                               sizeof(Token
3892                                                                      *));
3893                                         paramsize =
3894                                             nasm_realloc(paramsize,
3895                                                          sparam *
3896                                                          sizeof(int));
3897                                     }
3898                                     params[nparam] = tline->next;
3899                                     paramsize[nparam] = 0;
3900                                     white = 0;
3901                                     continue;   /* parameter loop */
3902                                 }
3903                                 if (ch == '{' &&
3904                                     (brackets > 0 || (brackets == 0 &&
3905                                                       !paramsize[nparam])))
3906                                 {
3907                                     if (!(brackets++)) {
3908                                         params[nparam] = tline->next;
3909                                         continue;       /* parameter loop */
3910                                     }
3911                                 }
3912                                 if (ch == '}' && brackets > 0)
3913                                     if (--brackets == 0) {
3914                                         brackets = -1;
3915                                         continue;       /* parameter loop */
3916                                     }
3917                                 if (ch == '(' && !brackets)
3918                                     paren++;
3919                                 if (ch == ')' && brackets <= 0)
3920                                     if (--paren < 0)
3921                                         break;
3922                             }
3923                             if (brackets < 0) {
3924                                 brackets = 0;
3925                                 error(ERR_NONFATAL, "braces do not "
3926                                       "enclose all of macro parameter");
3927                             }
3928                             paramsize[nparam] += white + 1;
3929                             white = 0;
3930                         }       /* parameter loop */
3931                         nparam++;
3932                         while (m && (m->nparam != nparam ||
3933                                      mstrcmp(m->name, mname,
3934                                              m->casesense)))
3935                             m = m->next;
3936                         if (!m)
3937                             error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
3938                                   "macro `%s' exists, "
3939                                   "but not taking %d parameters",
3940                                   mstart->text, nparam);
3941                     }
3942                 }
3943                 if (m && m->in_progress)
3944                     m = NULL;
3945                 if (!m) {       /* in progess or didn't find '(' or wrong nparam */
3946                     /*
3947                      * Design question: should we handle !tline, which
3948                      * indicates missing ')' here, or expand those
3949                      * macros anyway, which requires the (t) test a few
3950                      * lines down?
3951                      */
3952                     nasm_free(params);
3953                     nasm_free(paramsize);
3954                     tline = mstart;
3955                 } else {
3956                     /*
3957                      * Expand the macro: we are placed on the last token of the
3958                      * call, so that we can easily split the call from the
3959                      * following tokens. We also start by pushing an SMAC_END
3960                      * token for the cycle removal.
3961                      */
3962                     t = tline;
3963                     if (t) {
3964                         tline = t->next;
3965                         t->next = NULL;
3966                     }
3967                     tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3968                     tt->a.mac = m;
3969                     m->in_progress = true;
3970                     tline = tt;
3971                     for (t = m->expansion; t; t = t->next) {
3972                         if (t->type >= TOK_SMAC_PARAM) {
3973                             Token *pcopy = tline, **ptail = &pcopy;
3974                             Token *ttt, *pt;
3975                             int i;
3976
3977                             ttt = params[t->type - TOK_SMAC_PARAM];
3978                             for (i = paramsize[t->type - TOK_SMAC_PARAM];
3979                                  --i >= 0;) {
3980                                 pt = *ptail =
3981                                     new_Token(tline, ttt->type, ttt->text,
3982                                               0);
3983                                 ptail = &pt->next;
3984                                 ttt = ttt->next;
3985                             }
3986                             tline = pcopy;
3987                         } else if (t->type == TOK_PREPROC_Q) {
3988                             tt = new_Token(tline, TOK_ID, mname, 0);
3989                             tline = tt;
3990                         } else if (t->type == TOK_PREPROC_QQ) {
3991                             tt = new_Token(tline, TOK_ID, m->name, 0);
3992                             tline = tt;
3993                         } else {
3994                             tt = new_Token(tline, t->type, t->text, 0);
3995                             tline = tt;
3996                         }
3997                     }
3998
3999                     /*
4000                      * Having done that, get rid of the macro call, and clean
4001                      * up the parameters.
4002                      */
4003                     nasm_free(params);
4004                     nasm_free(paramsize);
4005                     free_tlist(mstart);
4006                     expanded = true;
4007                     continue;   /* main token loop */
4008                 }
4009             }
4010         }
4011
4012         if (tline->type == TOK_SMAC_END) {
4013             tline->a.mac->in_progress = false;
4014             tline = delete_Token(tline);
4015         } else {
4016             t = *tail = tline;
4017             tline = tline->next;
4018             t->a.mac = NULL;
4019             t->next = NULL;
4020             tail = &t->next;
4021         }
4022     }
4023
4024     /*
4025      * Now scan the entire line and look for successive TOK_IDs that resulted
4026      * after expansion (they can't be produced by tokenize()). The successive
4027      * TOK_IDs should be concatenated.
4028      * Also we look for %+ tokens and concatenate the tokens before and after
4029      * them (without white spaces in between).
4030      */
4031     if (expanded && paste_tokens(&thead, true)) {
4032         /*
4033          * If we concatenated something, *and* we had previously expanded
4034          * an actual macro, scan the lines again for macros...
4035          */
4036         tline = thead;
4037         expanded = false;
4038         goto again;
4039     }
4040
4041     if (org_tline) {
4042         if (thead) {
4043             *org_tline = *thead;
4044             /* since we just gave text to org_line, don't free it */
4045             thead->text = NULL;
4046             delete_Token(thead);
4047         } else {
4048             /* the expression expanded to empty line;
4049                we can't return NULL for some reasons
4050                we just set the line to a single WHITESPACE token. */
4051             memset(org_tline, 0, sizeof(*org_tline));
4052             org_tline->text = NULL;
4053             org_tline->type = TOK_WHITESPACE;
4054         }
4055         thead = org_tline;
4056     }
4057
4058     return thead;
4059 }
4060
4061 /*
4062  * Similar to expand_smacro but used exclusively with macro identifiers
4063  * right before they are fetched in. The reason is that there can be
4064  * identifiers consisting of several subparts. We consider that if there
4065  * are more than one element forming the name, user wants a expansion,
4066  * otherwise it will be left as-is. Example:
4067  *
4068  *      %define %$abc cde
4069  *
4070  * the identifier %$abc will be left as-is so that the handler for %define
4071  * will suck it and define the corresponding value. Other case:
4072  *
4073  *      %define _%$abc cde
4074  *
4075  * In this case user wants name to be expanded *before* %define starts
4076  * working, so we'll expand %$abc into something (if it has a value;
4077  * otherwise it will be left as-is) then concatenate all successive
4078  * PP_IDs into one.
4079  */
4080 static Token *expand_id(Token * tline)
4081 {
4082     Token *cur, *oldnext = NULL;
4083
4084     if (!tline || !tline->next)
4085         return tline;
4086
4087     cur = tline;
4088     while (cur->next &&
4089            (cur->next->type == TOK_ID ||
4090             cur->next->type == TOK_PREPROC_ID
4091             || cur->next->type == TOK_NUMBER))
4092         cur = cur->next;
4093
4094     /* If identifier consists of just one token, don't expand */
4095     if (cur == tline)
4096         return tline;
4097
4098     if (cur) {
4099         oldnext = cur->next;    /* Detach the tail past identifier */
4100         cur->next = NULL;       /* so that expand_smacro stops here */
4101     }
4102
4103     tline = expand_smacro(tline);
4104
4105     if (cur) {
4106         /* expand_smacro possibly changhed tline; re-scan for EOL */
4107         cur = tline;
4108         while (cur && cur->next)
4109             cur = cur->next;
4110         if (cur)
4111             cur->next = oldnext;
4112     }
4113
4114     return tline;
4115 }
4116
4117 /*
4118  * Determine whether the given line constitutes a multi-line macro
4119  * call, and return the MMacro structure called if so. Doesn't have
4120  * to check for an initial label - that's taken care of in
4121  * expand_mmacro - but must check numbers of parameters. Guaranteed
4122  * to be called with tline->type == TOK_ID, so the putative macro
4123  * name is easy to find.
4124  */
4125 static MMacro *is_mmacro(Token * tline, Token *** params_array)
4126 {
4127     MMacro *head, *m;
4128     Token **params;
4129     int nparam;
4130
4131     head = (MMacro *) hash_findix(&mmacros, tline->text);
4132
4133     /*
4134      * Efficiency: first we see if any macro exists with the given
4135      * name. If not, we can return NULL immediately. _Then_ we
4136      * count the parameters, and then we look further along the
4137      * list if necessary to find the proper MMacro.
4138      */
4139     for (m = head; m; m = m->next)
4140         if (!mstrcmp(m->name, tline->text, m->casesense))
4141             break;
4142     if (!m)
4143         return NULL;
4144
4145     /*
4146      * OK, we have a potential macro. Count and demarcate the
4147      * parameters.
4148      */
4149     count_mmac_params(tline->next, &nparam, &params);
4150
4151     /*
4152      * So we know how many parameters we've got. Find the MMacro
4153      * structure that handles this number.
4154      */
4155     while (m) {
4156         if (m->nparam_min <= nparam
4157             && (m->plus || nparam <= m->nparam_max)) {
4158             /*
4159              * This one is right. Just check if cycle removal
4160              * prohibits us using it before we actually celebrate...
4161              */
4162               if (m->in_progress > m->max_depth) {
4163                               if (m->max_depth > 0) {
4164                       error(ERR_WARNING,
4165                                                         "reached maximum recursion depth of %i",
4166                             m->max_depth);
4167                   }
4168                   nasm_free(params);
4169                   return NULL;
4170               }
4171             /*
4172              * It's right, and we can use it. Add its default
4173              * parameters to the end of our list if necessary.
4174              */
4175             if (m->defaults && nparam < m->nparam_min + m->ndefs) {
4176                 params =
4177                     nasm_realloc(params,
4178                                  ((m->nparam_min + m->ndefs +
4179                                    1) * sizeof(*params)));
4180                 while (nparam < m->nparam_min + m->ndefs) {
4181                     params[nparam] = m->defaults[nparam - m->nparam_min];
4182                     nparam++;
4183                 }
4184             }
4185             /*
4186              * If we've gone over the maximum parameter count (and
4187              * we're in Plus mode), ignore parameters beyond
4188              * nparam_max.
4189              */
4190             if (m->plus && nparam > m->nparam_max)
4191                 nparam = m->nparam_max;
4192             /*
4193              * Then terminate the parameter list, and leave.
4194              */
4195             if (!params) {      /* need this special case */
4196                 params = nasm_malloc(sizeof(*params));
4197                 nparam = 0;
4198             }
4199             params[nparam] = NULL;
4200             *params_array = params;
4201             return m;
4202         }
4203         /*
4204          * This one wasn't right: look for the next one with the
4205          * same name.
4206          */
4207         for (m = m->next; m; m = m->next)
4208             if (!mstrcmp(m->name, tline->text, m->casesense))
4209                 break;
4210     }
4211
4212     /*
4213      * After all that, we didn't find one with the right number of
4214      * parameters. Issue a warning, and fail to expand the macro.
4215      */
4216     error(ERR_WARNING|ERR_PASS1|ERR_WARN_MNP,
4217           "macro `%s' exists, but not taking %d parameters",
4218           tline->text, nparam);
4219     nasm_free(params);
4220     return NULL;
4221 }
4222
4223
4224 /*
4225  * Save MMacro invocation specific fields in
4226  * preparation for a recursive macro expansion
4227  */
4228 static void push_mmacro(MMacro *m)
4229 {
4230     MMacroInvocation *i;
4231
4232         i = nasm_malloc(sizeof(MMacroInvocation));
4233         i->prev = m->prev;
4234         i->params = m->params;
4235         i->iline = m->iline;
4236         i->nparam = m->nparam;
4237         i->rotate = m->rotate;
4238         i->paramlen = m->paramlen;
4239         i->unique = m->unique;
4240         m->prev = i;
4241 }
4242
4243
4244 /*
4245  * Restore MMacro invocation specific fields that were
4246  * saved during a previous recursive macro expansion
4247  */
4248 static void pop_mmacro(MMacro *m)
4249 {
4250     MMacroInvocation *i;
4251
4252         if(m->prev != NULL){
4253                 i = m->prev;
4254                 m->prev = i->prev;
4255                 m->params = i->params;
4256                 m->iline = i->iline;
4257                 m->nparam = i->nparam;
4258                 m->rotate = i->rotate;
4259                 m->paramlen = i->paramlen;
4260                 m->unique = i->unique;
4261                 nasm_free(i);
4262         }
4263 }
4264
4265
4266 /*
4267  * Expand the multi-line macro call made by the given line, if
4268  * there is one to be expanded. If there is, push the expansion on
4269  * istk->expansion and return 1. Otherwise return 0.
4270  */
4271 static int expand_mmacro(Token * tline)
4272 {
4273     Token *startline = tline;
4274     Token *label = NULL;
4275     int dont_prepend = 0;
4276     Token **params, *t, *mtok, *tt;
4277     MMacro *m;
4278     Line *l, *ll;
4279     int i, nparam, *paramlen;
4280     const char *mname;
4281
4282     t = tline;
4283     skip_white_(t);
4284     /*    if (!tok_type_(t, TOK_ID))  Lino 02/25/02 */
4285     if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
4286         return 0;
4287     mtok = t;
4288     m = is_mmacro(t, &params);
4289     if (m) {
4290         mname = t->text;
4291     } else {
4292         Token *last;
4293         /*
4294          * We have an id which isn't a macro call. We'll assume
4295          * it might be a label; we'll also check to see if a
4296          * colon follows it. Then, if there's another id after
4297          * that lot, we'll check it again for macro-hood.
4298          */
4299         label = last = t;
4300         t = t->next;
4301         if (tok_type_(t, TOK_WHITESPACE))
4302             last = t, t = t->next;
4303         if (tok_is_(t, ":")) {
4304             dont_prepend = 1;
4305             last = t, t = t->next;
4306             if (tok_type_(t, TOK_WHITESPACE))
4307                 last = t, t = t->next;
4308         }
4309         if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
4310             return 0;
4311         last->next = NULL;
4312         mname = t->text;
4313         tline = t;
4314     }
4315
4316     /*
4317      * Fix up the parameters: this involves stripping leading and
4318      * trailing whitespace, then stripping braces if they are
4319      * present.
4320      */
4321     for (nparam = 0; params[nparam]; nparam++) ;
4322     paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
4323
4324     for (i = 0; params[i]; i++) {
4325         int brace = false;
4326         int comma = (!m->plus || i < nparam - 1);
4327
4328         t = params[i];
4329         skip_white_(t);
4330         if (tok_is_(t, "{"))
4331             t = t->next, brace = true, comma = false;
4332         params[i] = t;
4333         paramlen[i] = 0;
4334         while (t) {
4335             if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
4336                 break;          /* ... because we have hit a comma */
4337             if (comma && t->type == TOK_WHITESPACE
4338                 && tok_is_(t->next, ","))
4339                 break;          /* ... or a space then a comma */
4340             if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
4341                 break;          /* ... or a brace */
4342             t = t->next;
4343             paramlen[i]++;
4344         }
4345     }
4346
4347     /*
4348      * OK, we have a MMacro structure together with a set of
4349      * parameters. We must now go through the expansion and push
4350      * copies of each Line on to istk->expansion. Substitution of
4351      * parameter tokens and macro-local tokens doesn't get done
4352      * until the single-line macro substitution process; this is
4353      * because delaying them allows us to change the semantics
4354      * later through %rotate.
4355      *
4356      * First, push an end marker on to istk->expansion, mark this
4357      * macro as in progress, and set up its invocation-specific
4358      * variables.
4359      */
4360     ll = nasm_malloc(sizeof(Line));
4361     ll->next = istk->expansion;
4362     ll->finishes = m;
4363     ll->first = NULL;
4364     istk->expansion = ll;
4365         
4366         /*
4367          * Save the previous MMacro expansion in the case of
4368          * macro recursion
4369          */
4370         if (m->max_depth && m->in_progress)
4371             push_mmacro(m);
4372
4373     m->in_progress ++;
4374     m->params = params;
4375     m->iline = tline;
4376     m->nparam = nparam;
4377     m->rotate = 0;
4378     m->paramlen = paramlen;
4379     m->unique = unique++;
4380     m->lineno = 0;
4381
4382     m->next_active = istk->mstk;
4383     istk->mstk = m;
4384
4385     for (l = m->expansion; l; l = l->next) {
4386         Token **tail;
4387
4388         ll = nasm_malloc(sizeof(Line));
4389         ll->finishes = NULL;
4390         ll->next = istk->expansion;
4391         istk->expansion = ll;
4392         tail = &ll->first;
4393
4394         for (t = l->first; t; t = t->next) {
4395             Token *x = t;
4396             switch (t->type) {
4397             case TOK_PREPROC_Q:
4398                 tt = *tail = new_Token(NULL, TOK_ID, mname, 0);
4399                 break;
4400             case TOK_PREPROC_QQ:
4401                 tt = *tail = new_Token(NULL, TOK_ID, m->name, 0);
4402                 break;
4403             case TOK_PREPROC_ID:
4404                 if (t->text[1] == '0' && t->text[2] == '0') {
4405                     dont_prepend = -1;
4406                     x = label;
4407                     if (!x)
4408                         continue;
4409                 }
4410                 /* fall through */
4411             default:
4412                 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4413                 break;
4414             }
4415             tail = &tt->next;
4416         }
4417         *tail = NULL;
4418     }
4419
4420     /*
4421      * If we had a label, push it on as the first line of
4422      * the macro expansion.
4423      */
4424     if (label) {
4425         if (dont_prepend < 0)
4426             free_tlist(startline);
4427         else {
4428             ll = nasm_malloc(sizeof(Line));
4429             ll->finishes = NULL;
4430             ll->next = istk->expansion;
4431             istk->expansion = ll;
4432             ll->first = startline;
4433             if (!dont_prepend) {
4434                 while (label->next)
4435                     label = label->next;
4436                 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4437             }
4438         }
4439     }
4440
4441     list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4442
4443     return 1;
4444 }
4445
4446 /* The function that actually does the error reporting */
4447 static void verror(int severity, const char *fmt, va_list arg)
4448 {
4449     char buff[1024];
4450
4451     vsnprintf(buff, sizeof(buff), fmt, arg);
4452
4453     if (istk && istk->mstk && istk->mstk->name)
4454         _error(severity, "(%s:%d) %s", istk->mstk->name,
4455                istk->mstk->lineno, buff);
4456     else
4457         _error(severity, "%s", buff);
4458 }
4459
4460 /*
4461  * Since preprocessor always operate only on the line that didn't
4462  * arrived yet, we should always use ERR_OFFBY1.
4463  */
4464 static void error(int severity, const char *fmt, ...)
4465 {
4466     va_list arg;
4467
4468     /* If we're in a dead branch of IF or something like it, ignore the error */
4469     if (istk && istk->conds && !emitting(istk->conds->state))
4470         return;
4471
4472     va_start(arg, fmt);
4473     verror(severity, fmt, arg);
4474     va_end(arg);
4475 }
4476
4477 /*
4478  * Because %else etc are evaluated in the state context
4479  * of the previous branch, errors might get lost with error():
4480  *   %if 0 ... %else trailing garbage ... %endif
4481  * So %else etc should report errors with this function.
4482  */
4483 static void error_precond(int severity, const char *fmt, ...)
4484 {
4485     va_list arg;
4486
4487     /* Only ignore the error if it's really in a dead branch */
4488     if (istk && istk->conds && istk->conds->state == COND_NEVER)
4489         return;
4490
4491     va_start(arg, fmt);
4492     verror(severity, fmt, arg);
4493     va_end(arg);
4494 }
4495
4496 static void
4497 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
4498          ListGen * listgen, StrList **deplist)
4499 {
4500     Token *t;
4501
4502     _error = errfunc;
4503     cstk = NULL;
4504     istk = nasm_malloc(sizeof(Include));
4505     istk->next = NULL;
4506     istk->conds = NULL;
4507     istk->expansion = NULL;
4508     istk->mstk = NULL;
4509     istk->fp = fopen(file, "r");
4510     istk->fname = NULL;
4511     src_set_fname(nasm_strdup(file));
4512     src_set_linnum(0);
4513     istk->lineinc = 1;
4514     if (!istk->fp)
4515         error(ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'",
4516               file);
4517     defining = NULL;
4518     nested_mac_count = 0;
4519     nested_rep_count = 0;
4520     init_macros();
4521     unique = 0;
4522     if (tasm_compatible_mode) {
4523         stdmacpos = nasm_stdmac;
4524     } else {
4525         stdmacpos = nasm_stdmac_after_tasm;
4526     }
4527     any_extrastdmac = extrastdmac && *extrastdmac;
4528     do_predef = true;
4529     list = listgen;
4530     evaluate = eval;
4531
4532     /*
4533      * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4534      * The caller, however, will also pass in 3 for preprocess-only so
4535      * we can set __PASS__ accordingly.
4536      */
4537     pass = apass > 2 ? 2 : apass;
4538
4539     dephead = deptail = deplist;
4540     if (deplist) {
4541         StrList *sl = nasm_malloc(strlen(file)+1+sizeof sl->next);
4542         sl->next = NULL;
4543         strcpy(sl->str, file);
4544         *deptail = sl;
4545         deptail = &sl->next;
4546     }
4547
4548     /*
4549      * Define the __PASS__ macro.  This is defined here unlike
4550      * all the other builtins, because it is special -- it varies between
4551      * passes.
4552      */
4553     t = nasm_malloc(sizeof(*t));
4554     t->next = NULL;
4555     make_tok_num(t, apass);
4556     t->a.mac = NULL;
4557     define_smacro(NULL, "__PASS__", true, 0, t);
4558 }
4559
4560 static char *pp_getline(void)
4561 {
4562     char *line;
4563     Token *tline;
4564
4565     while (1) {
4566         /*
4567          * Fetch a tokenized line, either from the macro-expansion
4568          * buffer or from the input file.
4569          */
4570         tline = NULL;
4571         while (istk->expansion && istk->expansion->finishes) {
4572             Line *l = istk->expansion;
4573             if (!l->finishes->name && l->finishes->in_progress > 1) {
4574                 Line *ll;
4575
4576                 /*
4577                  * This is a macro-end marker for a macro with no
4578                  * name, which means it's not really a macro at all
4579                  * but a %rep block, and the `in_progress' field is
4580                  * more than 1, meaning that we still need to
4581                  * repeat. (1 means the natural last repetition; 0
4582                  * means termination by %exitrep.) We have
4583                  * therefore expanded up to the %endrep, and must
4584                  * push the whole block on to the expansion buffer
4585                  * again. We don't bother to remove the macro-end
4586                  * marker: we'd only have to generate another one
4587                  * if we did.
4588                  */
4589                 l->finishes->in_progress--;
4590                 for (l = l->finishes->expansion; l; l = l->next) {
4591                     Token *t, *tt, **tail;
4592
4593                     ll = nasm_malloc(sizeof(Line));
4594                     ll->next = istk->expansion;
4595                     ll->finishes = NULL;
4596                     ll->first = NULL;
4597                     tail = &ll->first;
4598
4599                     for (t = l->first; t; t = t->next) {
4600                         if (t->text || t->type == TOK_WHITESPACE) {
4601                             tt = *tail =
4602                                 new_Token(NULL, t->type, t->text, 0);
4603                             tail = &tt->next;
4604                         }
4605                     }
4606
4607                     istk->expansion = ll;
4608                 }
4609             } else {
4610                 /*
4611                  * Check whether a `%rep' was started and not ended
4612                  * within this macro expansion. This can happen and
4613                  * should be detected. It's a fatal error because
4614                  * I'm too confused to work out how to recover
4615                  * sensibly from it.
4616                  */
4617                 if (defining) {
4618                     if (defining->name)
4619                         error(ERR_PANIC,
4620                               "defining with name in expansion");
4621                     else if (istk->mstk->name)
4622                         error(ERR_FATAL,
4623                               "`%%rep' without `%%endrep' within"
4624                               " expansion of macro `%s'",
4625                               istk->mstk->name);
4626                 }
4627
4628                 /*
4629                  * FIXME:  investigate the relationship at this point between
4630                  * istk->mstk and l->finishes
4631                  */
4632                 {
4633                     MMacro *m = istk->mstk;
4634                     istk->mstk = m->next_active;
4635                     if (m->name) {
4636                         /*
4637                          * This was a real macro call, not a %rep, and
4638                          * therefore the parameter information needs to
4639                          * be freed.
4640                          */
4641                                                 if (m->prev != NULL) {
4642                                                         pop_mmacro(m);
4643                                                         l->finishes->in_progress --;
4644                                                 } else {
4645                             nasm_free(m->params);
4646                             free_tlist(m->iline);
4647                                                         nasm_free(m->paramlen);
4648                                                         l->finishes->in_progress = 0;
4649                                                 }
4650                     } else
4651                         free_mmacro(m);
4652                 }
4653                 istk->expansion = l->next;
4654                 nasm_free(l);
4655                 list->downlevel(LIST_MACRO);
4656             }
4657         }
4658         while (1) {             /* until we get a line we can use */
4659
4660             if (istk->expansion) {      /* from a macro expansion */
4661                 char *p;
4662                 Line *l = istk->expansion;
4663                 if (istk->mstk)
4664                     istk->mstk->lineno++;
4665                 tline = l->first;
4666                 istk->expansion = l->next;
4667                 nasm_free(l);
4668                 p = detoken(tline, false);
4669                 list->line(LIST_MACRO, p);
4670                 nasm_free(p);
4671                 break;
4672             }
4673             line = read_line();
4674             if (line) {         /* from the current input file */
4675                 line = prepreproc(line);
4676                 tline = tokenize(line);
4677                 nasm_free(line);
4678                 break;
4679             }
4680             /*
4681              * The current file has ended; work down the istk
4682              */
4683             {
4684                 Include *i = istk;
4685                 fclose(i->fp);
4686                 if (i->conds)
4687                     error(ERR_FATAL,
4688                           "expected `%%endif' before end of file");
4689                 /* only set line and file name if there's a next node */
4690                 if (i->next) {
4691                     src_set_linnum(i->lineno);
4692                     nasm_free(src_set_fname(i->fname));
4693                 }
4694                 istk = i->next;
4695                 list->downlevel(LIST_INCLUDE);
4696                 nasm_free(i);
4697                 if (!istk)
4698                     return NULL;
4699                 if (istk->expansion && istk->expansion->finishes)
4700                     break;
4701             }
4702         }
4703
4704         /*
4705          * We must expand MMacro parameters and MMacro-local labels
4706          * _before_ we plunge into directive processing, to cope
4707          * with things like `%define something %1' such as STRUC
4708          * uses. Unless we're _defining_ a MMacro, in which case
4709          * those tokens should be left alone to go into the
4710          * definition; and unless we're in a non-emitting
4711          * condition, in which case we don't want to meddle with
4712          * anything.
4713          */
4714         if (!defining && !(istk->conds && !emitting(istk->conds->state))
4715             && !(istk->mstk && !istk->mstk->in_progress)) {
4716             tline = expand_mmac_params(tline);
4717         }
4718
4719         /*
4720          * Check the line to see if it's a preprocessor directive.
4721          */
4722         if (do_directive(tline) == DIRECTIVE_FOUND) {
4723             continue;
4724         } else if (defining) {
4725             /*
4726              * We're defining a multi-line macro. We emit nothing
4727              * at all, and just
4728              * shove the tokenized line on to the macro definition.
4729              */
4730             Line *l = nasm_malloc(sizeof(Line));
4731             l->next = defining->expansion;
4732             l->first = tline;
4733             l->finishes = NULL;
4734             defining->expansion = l;
4735             continue;
4736         } else if (istk->conds && !emitting(istk->conds->state)) {
4737             /*
4738              * We're in a non-emitting branch of a condition block.
4739              * Emit nothing at all, not even a blank line: when we
4740              * emerge from the condition we'll give a line-number
4741              * directive so we keep our place correctly.
4742              */
4743             free_tlist(tline);
4744             continue;
4745         } else if (istk->mstk && !istk->mstk->in_progress) {
4746             /*
4747              * We're in a %rep block which has been terminated, so
4748              * we're walking through to the %endrep without
4749              * emitting anything. Emit nothing at all, not even a
4750              * blank line: when we emerge from the %rep block we'll
4751              * give a line-number directive so we keep our place
4752              * correctly.
4753              */
4754             free_tlist(tline);
4755             continue;
4756         } else {
4757             tline = expand_smacro(tline);
4758             if (!expand_mmacro(tline)) {
4759                 /*
4760                  * De-tokenize the line again, and emit it.
4761                  */
4762                 line = detoken(tline, true);
4763                 free_tlist(tline);
4764                 break;
4765             } else {
4766                 continue;       /* expand_mmacro calls free_tlist */
4767             }
4768         }
4769     }
4770
4771     return line;
4772 }
4773
4774 static void pp_cleanup(int pass)
4775 {
4776     if (defining) {
4777         if(defining->name) {
4778             error(ERR_NONFATAL,
4779                   "end of file while still defining macro `%s'",
4780                   defining->name);
4781         } else {
4782             error(ERR_NONFATAL, "end of file while still in %%rep");
4783         }
4784
4785         free_mmacro(defining);
4786     }
4787     while (cstk)
4788         ctx_pop();
4789     free_macros();
4790     while (istk) {
4791         Include *i = istk;
4792         istk = istk->next;
4793         fclose(i->fp);
4794         nasm_free(i->fname);
4795         nasm_free(i);
4796     }
4797     while (cstk)
4798         ctx_pop();
4799     nasm_free(src_set_fname(NULL));
4800     if (pass == 0) {
4801         IncPath *i;
4802         free_llist(predef);
4803         delete_Blocks();
4804         while ((i = ipath)) {
4805             ipath = i->next;
4806             if (i->path)
4807                 nasm_free(i->path);
4808             nasm_free(i);
4809         }
4810     }
4811 }
4812
4813 void pp_include_path(char *path)
4814 {
4815     IncPath *i;
4816
4817     i = nasm_malloc(sizeof(IncPath));
4818     i->path = path ? nasm_strdup(path) : NULL;
4819     i->next = NULL;
4820
4821     if (ipath != NULL) {
4822         IncPath *j = ipath;
4823         while (j->next != NULL)
4824             j = j->next;
4825         j->next = i;
4826     } else {
4827         ipath = i;
4828     }
4829 }
4830
4831 void pp_pre_include(char *fname)
4832 {
4833     Token *inc, *space, *name;
4834     Line *l;
4835
4836     name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4837     space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4838     inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4839
4840     l = nasm_malloc(sizeof(Line));
4841     l->next = predef;
4842     l->first = inc;
4843     l->finishes = NULL;
4844     predef = l;
4845 }
4846
4847 void pp_pre_define(char *definition)
4848 {
4849     Token *def, *space;
4850     Line *l;
4851     char *equals;
4852
4853     equals = strchr(definition, '=');
4854     space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4855     def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4856     if (equals)
4857         *equals = ' ';
4858     space->next = tokenize(definition);
4859     if (equals)
4860         *equals = '=';
4861
4862     l = nasm_malloc(sizeof(Line));
4863     l->next = predef;
4864     l->first = def;
4865     l->finishes = NULL;
4866     predef = l;
4867 }
4868
4869 void pp_pre_undefine(char *definition)
4870 {
4871     Token *def, *space;
4872     Line *l;
4873
4874     space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4875     def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4876     space->next = tokenize(definition);
4877
4878     l = nasm_malloc(sizeof(Line));
4879     l->next = predef;
4880     l->first = def;
4881     l->finishes = NULL;
4882     predef = l;
4883 }
4884
4885 /*
4886  * Added by Keith Kanios:
4887  *
4888  * This function is used to assist with "runtime" preprocessor
4889  * directives. (e.g. pp_runtime("%define __BITS__ 64");)
4890  *
4891  * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
4892  * PASS A VALID STRING TO THIS FUNCTION!!!!!
4893  */
4894
4895 void pp_runtime(char *definition)
4896 {
4897     Token *def;
4898
4899     def = tokenize(definition);
4900     if(do_directive(def) == NO_DIRECTIVE_FOUND)
4901         free_tlist(def);
4902
4903 }
4904
4905 void pp_extra_stdmac(macros_t *macros)
4906 {
4907     extrastdmac = macros;
4908 }
4909
4910 static void make_tok_num(Token * tok, int64_t val)
4911 {
4912     char numbuf[20];
4913     snprintf(numbuf, sizeof(numbuf), "%"PRId64"", val);
4914     tok->text = nasm_strdup(numbuf);
4915     tok->type = TOK_NUMBER;
4916 }
4917
4918 Preproc nasmpp = {
4919     pp_reset,
4920     pp_getline,
4921     pp_cleanup
4922 };