1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
85 typedef struct SMacro SMacro
;
86 typedef struct MMacro MMacro
;
87 typedef struct MMacroInvocation MMacroInvocation
;
88 typedef struct Context Context
;
89 typedef struct Token Token
;
90 typedef struct Blocks Blocks
;
91 typedef struct Line Line
;
92 typedef struct Include Include
;
93 typedef struct Cond Cond
;
94 typedef struct IncPath IncPath
;
97 * Note on the storage of both SMacro and MMacros: the hash table
98 * indexes them case-insensitively, and we then have to go through a
99 * linked list of potential case aliases (and, for MMacros, parameter
100 * ranges); this is to preserve the matching semantics of the earlier
101 * code. If the number of case aliases for a specific macro is a
102 * performance issue, you may want to reconsider your coding style.
106 * Store the definition of a single-line macro.
118 * Store the definition of a multi-line macro. This is also used to
119 * store the interiors of `%rep...%endrep' blocks, which are
120 * effectively self-re-invoking multi-line macros which simply
121 * don't have a name or bother to appear in the hash tables. %rep
122 * blocks are signified by having a NULL `name' field.
124 * In a MMacro describing a `%rep' block, the `in_progress' field
125 * isn't merely boolean, but gives the number of repeats left to
128 * The `next' field is used for storing MMacros in hash tables; the
129 * `next_active' field is for stacking them on istk entries.
131 * When a MMacro is being expanded, `params', `iline', `nparam',
132 * `paramlen', `rotate' and `unique' are local to the invocation.
136 MMacroInvocation
*prev
; /* previous invocation */
138 int nparam_min
, nparam_max
;
140 bool plus
; /* is the last parameter greedy? */
141 bool nolist
; /* is this macro listing-inhibited? */
142 int64_t in_progress
; /* is this macro currently being expanded? */
143 int32_t max_depth
; /* maximum number of recursive expansions allowed */
144 Token
*dlist
; /* All defaults as one list */
145 Token
**defaults
; /* Parameter default pointers */
146 int ndefs
; /* number of default parameters */
150 MMacro
*rep_nest
; /* used for nesting %rep */
151 Token
**params
; /* actual parameters */
152 Token
*iline
; /* invocation line */
153 unsigned int nparam
, rotate
;
156 int lineno
; /* Current line number on expansion */
157 uint64_t condcnt
; /* number of if blocks... */
159 const char *fname
; /* File where defined */
160 int32_t xline
; /* First line in macro */
164 /* Store the definition of a multi-line macro, as defined in a
165 * previous recursive macro expansion.
167 struct MMacroInvocation
{
168 MMacroInvocation
*prev
; /* previous invocation */
169 Token
**params
; /* actual parameters */
170 Token
*iline
; /* invocation line */
171 unsigned int nparam
, rotate
;
179 * The context stack is composed of a linked list of these.
184 struct hash_table localmac
;
189 * This is the internal form which we break input lines up into.
190 * Typically stored in linked lists.
192 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
193 * necessarily used as-is, but is intended to denote the number of
194 * the substituted parameter. So in the definition
196 * %define a(x,y) ( (x) & ~(y) )
198 * the token representing `x' will have its type changed to
199 * TOK_SMAC_PARAM, but the one representing `y' will be
202 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
203 * which doesn't need quotes around it. Used in the pre-include
204 * mechanism as an alternative to trying to find a sensible type of
205 * quote to use on the filename we were passed.
208 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
209 TOK_PREPROC_ID
, TOK_STRING
,
210 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
212 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
214 TOK_INDIRECT
, /* %[...] */
215 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
216 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
219 #define PP_CONCAT_MASK(x) (1 << (x))
220 #define PP_CONCAT_MATCH(t, mask) (PP_CONCAT_MASK((t)->type) & mask)
222 struct tokseq_match
{
231 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
232 size_t len
; /* scratch length field */
233 } a
; /* Auxiliary data */
234 enum pp_token_type type
;
238 * Multi-line macro definitions are stored as a linked list of
239 * these, which is essentially a container to allow several linked
242 * Note that in this module, linked lists are treated as stacks
243 * wherever possible. For this reason, Lines are _pushed_ on to the
244 * `expansion' field in MMacro structures, so that the linked list,
245 * if walked, would give the macro lines in reverse order; this
246 * means that we can walk the list when expanding a macro, and thus
247 * push the lines on to the `expansion' field in _istk_ in reverse
248 * order (so that when popped back off they are in the right
249 * order). It may seem cockeyed, and it relies on my design having
250 * an even number of steps in, but it works...
252 * Some of these structures, rather than being actual lines, are
253 * markers delimiting the end of the expansion of a given macro.
254 * This is for use in the cycle-tracking and %rep-handling code.
255 * Such structures have `finishes' non-NULL, and `first' NULL. All
256 * others have `finishes' NULL, but `first' may still be NULL if
266 * To handle an arbitrary level of file inclusion, we maintain a
267 * stack (ie linked list) of these things.
276 MMacro
*mstk
; /* stack of active macros/reps */
280 * Include search path. This is simply a list of strings which get
281 * prepended, in turn, to the name of an include file, in an
282 * attempt to find the file if it's not in the current directory.
290 * Conditional assembly: we maintain a separate stack of these for
291 * each level of file inclusion. (The only reason we keep the
292 * stacks separate is to ensure that a stray `%endif' in a file
293 * included from within the true branch of a `%if' won't terminate
294 * it and cause confusion: instead, rightly, it'll cause an error.)
302 * These states are for use just after %if or %elif: IF_TRUE
303 * means the condition has evaluated to truth so we are
304 * currently emitting, whereas IF_FALSE means we are not
305 * currently emitting but will start doing so if a %else comes
306 * up. In these states, all directives are admissible: %elif,
307 * %else and %endif. (And of course %if.)
309 COND_IF_TRUE
, COND_IF_FALSE
,
311 * These states come up after a %else: ELSE_TRUE means we're
312 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
313 * any %elif or %else will cause an error.
315 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
317 * These states mean that we're not emitting now, and also that
318 * nothing until %endif will be emitted at all. COND_DONE is
319 * used when we've had our moment of emission
320 * and have now started seeing %elifs. COND_NEVER is used when
321 * the condition construct in question is contained within a
322 * non-emitting branch of a larger condition construct,
323 * or if there is an error.
325 COND_DONE
, COND_NEVER
327 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
330 * These defines are used as the possible return values for do_directive
332 #define NO_DIRECTIVE_FOUND 0
333 #define DIRECTIVE_FOUND 1
336 * This define sets the upper limit for smacro and recursive mmacro
339 #define DEADMAN_LIMIT (1 << 20)
342 #define REP_LIMIT ((INT64_C(1) << 62))
345 * Condition codes. Note that we use c_ prefix not C_ because C_ is
346 * used in nasm.h for the "real" condition codes. At _this_ level,
347 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
348 * ones, so we need a different enum...
350 static const char * const conditions
[] = {
351 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
352 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
353 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
356 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
357 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
358 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
361 static const enum pp_conds inverse_ccs
[] = {
362 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
363 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
,
364 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
370 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
371 static int is_condition(enum preproc_token arg
)
373 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
376 /* For TASM compatibility we need to be able to recognise TASM compatible
377 * conditional compilation directives. Using the NASM pre-processor does
378 * not work, so we look for them specifically from the following list and
379 * then jam in the equivalent NASM directive into the input stream.
383 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
384 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
387 static const char * const tasm_directives
[] = {
388 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
389 "ifndef", "include", "local"
392 static int StackSize
= 4;
393 static char *StackPointer
= "ebp";
394 static int ArgOffset
= 8;
395 static int LocalOffset
= 0;
397 static Context
*cstk
;
398 static Include
*istk
;
399 static IncPath
*ipath
= NULL
;
401 static int pass
; /* HACK: pass 0 = generate dependencies only */
402 static StrList
**dephead
, **deptail
; /* Dependency list */
404 static uint64_t unique
; /* unique identifier numbers */
406 static Line
*predef
= NULL
;
407 static bool do_predef
;
410 * The current set of multi-line macros we have defined.
412 static struct hash_table mmacros
;
415 * The current set of single-line macros we have defined.
417 static struct hash_table smacros
;
420 * The multi-line macro we are currently defining, or the %rep
421 * block we are currently reading, if any.
423 static MMacro
*defining
;
425 static uint64_t nested_mac_count
;
426 static uint64_t nested_rep_count
;
429 * The number of macro parameters to allocate space for at a time.
431 #define PARAM_DELTA 16
434 * The standard macro set: defined in macros.c in the array nasm_stdmac.
435 * This gives our position in the macro set, when we're processing it.
437 static macros_t
*stdmacpos
;
440 * The extra standard macros that come from the object format, if
443 static macros_t
*extrastdmac
= NULL
;
444 static bool any_extrastdmac
;
447 * Tokens are allocated in blocks to improve speed
449 #define TOKEN_BLOCKSIZE 4096
450 static Token
*freeTokens
= NULL
;
456 static Blocks blocks
= { NULL
, NULL
};
459 * Forward declarations.
461 static Token
*expand_mmac_params(Token
* tline
);
462 static Token
*expand_smacro(Token
* tline
);
463 static Token
*expand_id(Token
* tline
);
464 static Context
*get_ctx(const char *name
, const char **namep
);
465 static void make_tok_num(Token
* tok
, int64_t val
);
466 static void pp_verror(int severity
, const char *fmt
, va_list ap
);
467 static vefunc real_verror
;
468 static void *new_Block(size_t size
);
469 static void delete_Blocks(void);
470 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
471 const char *text
, int txtlen
);
472 static Token
*delete_Token(Token
* t
);
475 * Macros for safe checking of token pointers, avoid *(NULL)
477 #define tok_type_(x,t) ((x) && (x)->type == (t))
478 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
479 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
480 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
483 * nasm_unquote with error if the string contains NUL characters.
484 * If the string contains NUL characters, issue an error and return
485 * the C len, i.e. truncate at the NUL.
487 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
489 size_t len
= nasm_unquote(qstr
, NULL
);
490 size_t clen
= strlen(qstr
);
493 nasm_error(ERR_NONFATAL
, "NUL character in `%s' directive",
494 pp_directives
[directive
]);
500 * In-place reverse a list of tokens.
502 static Token
*reverse_tokens(Token
*t
)
518 * Handle TASM specific directives, which do not contain a % in
519 * front of them. We do it here because I could not find any other
520 * place to do it for the moment, and it is a hack (ideally it would
521 * be nice to be able to use the NASM pre-processor to do it).
523 static char *check_tasm_directive(char *line
)
525 int32_t i
, j
, k
, m
, len
;
526 char *p
, *q
, *oldline
, oldchar
;
528 p
= nasm_skip_spaces(line
);
530 /* Binary search for the directive name */
532 j
= ARRAY_SIZE(tasm_directives
);
533 q
= nasm_skip_word(p
);
540 m
= nasm_stricmp(p
, tasm_directives
[k
]);
542 /* We have found a directive, so jam a % in front of it
543 * so that NASM will then recognise it as one if it's own.
548 line
= nasm_malloc(len
+ 2);
550 if (k
== TM_IFDIFI
) {
552 * NASM does not recognise IFDIFI, so we convert
553 * it to %if 0. This is not used in NASM
554 * compatible code, but does need to parse for the
555 * TASM macro package.
557 strcpy(line
+ 1, "if 0");
559 memcpy(line
+ 1, p
, len
+ 1);
574 * The pre-preprocessing stage... This function translates line
575 * number indications as they emerge from GNU cpp (`# lineno "file"
576 * flags') into NASM preprocessor line number indications (`%line
579 static char *prepreproc(char *line
)
582 char *fname
, *oldline
;
584 if (line
[0] == '#' && line
[1] == ' ') {
587 lineno
= atoi(fname
);
588 fname
+= strspn(fname
, "0123456789 ");
591 fnlen
= strcspn(fname
, "\"");
592 line
= nasm_malloc(20 + fnlen
);
593 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
596 if (tasm_compatible_mode
)
597 return check_tasm_directive(line
);
602 * Free a linked list of tokens.
604 static void free_tlist(Token
* list
)
607 list
= delete_Token(list
);
611 * Free a linked list of lines.
613 static void free_llist(Line
* list
)
616 list_for_each_safe(l
, tmp
, list
) {
617 free_tlist(l
->first
);
625 static void free_mmacro(MMacro
* m
)
628 free_tlist(m
->dlist
);
629 nasm_free(m
->defaults
);
630 free_llist(m
->expansion
);
635 * Free all currently defined macros, and free the hash tables
637 static void free_smacro_table(struct hash_table
*smt
)
641 struct hash_tbl_node
*it
= NULL
;
643 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
644 nasm_free((void *)key
);
645 list_for_each_safe(s
, tmp
, s
) {
647 free_tlist(s
->expansion
);
654 static void free_mmacro_table(struct hash_table
*mmt
)
658 struct hash_tbl_node
*it
= NULL
;
661 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
662 nasm_free((void *)key
);
663 list_for_each_safe(m
,tmp
, m
)
669 static void free_macros(void)
671 free_smacro_table(&smacros
);
672 free_mmacro_table(&mmacros
);
676 * Initialize the hash tables
678 static void init_macros(void)
680 hash_init(&smacros
, HASH_LARGE
);
681 hash_init(&mmacros
, HASH_LARGE
);
685 * Pop the context stack.
687 static void ctx_pop(void)
692 free_smacro_table(&c
->localmac
);
698 * Search for a key in the hash index; adding it if necessary
699 * (in which case we initialize the data pointer to NULL.)
702 hash_findi_add(struct hash_table
*hash
, const char *str
)
704 struct hash_insert hi
;
708 r
= hash_findi(hash
, str
, &hi
);
712 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
713 return hash_add(&hi
, strx
, NULL
);
717 * Like hash_findi, but returns the data element rather than a pointer
718 * to it. Used only when not adding a new element, hence no third
722 hash_findix(struct hash_table
*hash
, const char *str
)
726 p
= hash_findi(hash
, str
, NULL
);
727 return p
? *p
: NULL
;
731 * read line from standart macros set,
732 * if there no more left -- return NULL
734 static char *line_from_stdmac(void)
737 const unsigned char *p
= stdmacpos
;
746 len
+= pp_directives_len
[c
- 0x80] + 1;
751 line
= nasm_malloc(len
+ 1);
753 while ((c
= *stdmacpos
++)) {
755 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
756 q
+= pp_directives_len
[c
- 0x80];
766 /* This was the last of the standard macro chain... */
768 if (any_extrastdmac
) {
769 stdmacpos
= extrastdmac
;
770 any_extrastdmac
= false;
771 } else if (do_predef
) {
773 Token
*head
, **tail
, *t
;
776 * Nasty hack: here we push the contents of
777 * `predef' on to the top-level expansion stack,
778 * since this is the most convenient way to
779 * implement the pre-include and pre-define
782 list_for_each(pd
, predef
) {
785 list_for_each(t
, pd
->first
) {
786 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
787 tail
= &(*tail
)->next
;
790 l
= nasm_malloc(sizeof(Line
));
791 l
->next
= istk
->expansion
;
804 static char *read_line(void)
806 unsigned int size
, c
, next
;
807 const unsigned int delta
= 512;
808 const unsigned int pad
= 8;
809 unsigned int nr_cont
= 0;
813 /* Standart macros set (predefined) goes first */
814 p
= line_from_stdmac();
819 p
= buffer
= nasm_malloc(size
);
823 if ((int)(c
) == EOF
) {
830 next
= fgetc(istk
->fp
);
832 ungetc(next
, istk
->fp
);
847 next
= fgetc(istk
->fp
);
848 ungetc(next
, istk
->fp
);
849 if (next
== '\r' || next
== '\n') {
857 if (c
== '\r' || c
== '\n') {
862 if (p
>= (buffer
+ size
- pad
)) {
863 buffer
= nasm_realloc(buffer
, size
+ delta
);
864 p
= buffer
+ size
- pad
;
868 *p
++ = (unsigned char)c
;
876 src_set_linnum(src_get_linnum() + istk
->lineinc
+
877 (nr_cont
* istk
->lineinc
));
880 * Handle spurious ^Z, which may be inserted into source files
881 * by some file transfer utilities.
883 buffer
[strcspn(buffer
, "\032")] = '\0';
885 lfmt
->line(LIST_READ
, buffer
);
891 * Tokenize a line of text. This is a very simple process since we
892 * don't need to parse the value out of e.g. numeric tokens: we
893 * simply split one string into many.
895 static Token
*tokenize(char *line
)
898 enum pp_token_type type
;
900 Token
*t
, **tail
= &list
;
906 if (*p
== '+' && !nasm_isdigit(p
[1])) {
909 } else if (nasm_isdigit(*p
) ||
910 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
914 while (nasm_isdigit(*p
));
915 type
= TOK_PREPROC_ID
;
916 } else if (*p
== '{') {
925 nasm_error(ERR_WARNING
| ERR_PASS1
,
926 "unterminated %%{ construct");
930 type
= TOK_PREPROC_ID
;
931 } else if (*p
== '[') {
933 line
+= 2; /* Skip the leading %[ */
935 while (lvl
&& (c
= *p
++)) {
947 p
= nasm_skip_string(p
- 1) + 1;
957 nasm_error(ERR_NONFATAL
|ERR_PASS1
,
958 "unterminated %%[ construct");
960 } else if (*p
== '?') {
961 type
= TOK_PREPROC_Q
; /* %? */
964 type
= TOK_PREPROC_QQ
; /* %?? */
967 } else if (*p
== '!') {
968 type
= TOK_PREPROC_ID
;
974 while (isidchar(*p
));
975 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
976 p
= nasm_skip_string(p
);
980 nasm_error(ERR_NONFATAL
|ERR_PASS1
,
981 "unterminated %%! string");
983 /* %! without string or identifier */
984 type
= TOK_OTHER
; /* Legacy behavior... */
986 } else if (isidchar(*p
) ||
987 ((*p
== '!' || *p
== '%' || *p
== '$') &&
992 while (isidchar(*p
));
993 type
= TOK_PREPROC_ID
;
999 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
1002 while (*p
&& isidchar(*p
))
1004 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
1009 p
= nasm_skip_string(p
);
1014 nasm_error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1015 /* Handling unterminated strings by UNV */
1018 } else if (p
[0] == '$' && p
[1] == '$') {
1019 type
= TOK_OTHER
; /* TOKEN_BASE */
1021 } else if (isnumstart(*p
)) {
1022 bool is_hex
= false;
1023 bool is_float
= false;
1039 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1041 if (*p
== '+' || *p
== '-') {
1043 * e can only be followed by +/- if it is either a
1044 * prefixed hex number or a floating-point number
1049 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1051 } else if (c
== 'P' || c
== 'p') {
1053 if (*p
== '+' || *p
== '-')
1055 } else if (isnumchar(c
) || c
== '_')
1056 ; /* just advance */
1057 else if (c
== '.') {
1059 * we need to deal with consequences of the legacy
1060 * parser, like "1.nolist" being two tokens
1061 * (TOK_NUMBER, TOK_ID) here; at least give it
1062 * a shot for now. In the future, we probably need
1063 * a flex-based scanner with proper pattern matching
1064 * to do it as well as it can be done. Nothing in
1065 * the world is going to help the person who wants
1066 * 0x123.p16 interpreted as two tokens, though.
1072 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1073 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1074 (*r
== 'p' || *r
== 'P')) {
1078 break; /* Terminate the token */
1082 p
--; /* Point to first character beyond number */
1084 if (p
== line
+1 && *line
== '$') {
1085 type
= TOK_OTHER
; /* TOKEN_HERE */
1087 if (has_e
&& !is_hex
) {
1088 /* 1e13 is floating-point, but 1e13h is not */
1092 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1094 } else if (nasm_isspace(*p
)) {
1095 type
= TOK_WHITESPACE
;
1096 p
= nasm_skip_spaces(p
);
1098 * Whitespace just before end-of-line is discarded by
1099 * pretending it's a comment; whitespace just before a
1100 * comment gets lumped into the comment.
1102 if (!*p
|| *p
== ';') {
1107 } else if (*p
== ';') {
1113 * Anything else is an operator of some kind. We check
1114 * for all the double-character operators (>>, <<, //,
1115 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1116 * else is a single-character operator.
1119 if ((p
[0] == '>' && p
[1] == '>') ||
1120 (p
[0] == '<' && p
[1] == '<') ||
1121 (p
[0] == '/' && p
[1] == '/') ||
1122 (p
[0] == '<' && p
[1] == '=') ||
1123 (p
[0] == '>' && p
[1] == '=') ||
1124 (p
[0] == '=' && p
[1] == '=') ||
1125 (p
[0] == '!' && p
[1] == '=') ||
1126 (p
[0] == '<' && p
[1] == '>') ||
1127 (p
[0] == '&' && p
[1] == '&') ||
1128 (p
[0] == '|' && p
[1] == '|') ||
1129 (p
[0] == '^' && p
[1] == '^')) {
1135 /* Handling unterminated string by UNV */
1138 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1139 t->text[p-line] = *line;
1143 if (type
!= TOK_COMMENT
) {
1144 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1153 * this function allocates a new managed block of memory and
1154 * returns a pointer to the block. The managed blocks are
1155 * deleted only all at once by the delete_Blocks function.
1157 static void *new_Block(size_t size
)
1159 Blocks
*b
= &blocks
;
1161 /* first, get to the end of the linked list */
1164 /* now allocate the requested chunk */
1165 b
->chunk
= nasm_malloc(size
);
1167 /* now allocate a new block for the next request */
1168 b
->next
= nasm_zalloc(sizeof(Blocks
));
1173 * this function deletes all managed blocks of memory
1175 static void delete_Blocks(void)
1177 Blocks
*a
, *b
= &blocks
;
1180 * keep in mind that the first block, pointed to by blocks
1181 * is a static and not dynamically allocated, so we don't
1186 nasm_free(b
->chunk
);
1192 memset(&blocks
, 0, sizeof(blocks
));
1196 * this function creates a new Token and passes a pointer to it
1197 * back to the caller. It sets the type and text elements, and
1198 * also the a.mac and next elements to NULL.
1200 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1201 const char *text
, int txtlen
)
1207 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1208 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1209 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1210 freeTokens
[i
].next
= NULL
;
1213 freeTokens
= t
->next
;
1217 if (type
== TOK_WHITESPACE
|| !text
) {
1221 txtlen
= strlen(text
);
1222 t
->text
= nasm_malloc(txtlen
+1);
1223 memcpy(t
->text
, text
, txtlen
);
1224 t
->text
[txtlen
] = '\0';
1229 static Token
*delete_Token(Token
* t
)
1231 Token
*next
= t
->next
;
1233 t
->next
= freeTokens
;
1239 * Convert a line of tokens back into text.
1240 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1241 * will be transformed into ..@ctxnum.xxx
1243 static char *detoken(Token
* tlist
, bool expand_locals
)
1250 list_for_each(t
, tlist
) {
1251 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1256 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1257 size_t len
= nasm_unquote(v
, NULL
);
1258 size_t clen
= strlen(v
);
1261 nasm_error(ERR_NONFATAL
| ERR_PASS1
,
1262 "NUL character in %%! string");
1268 char *p
= getenv(v
);
1270 nasm_error(ERR_NONFATAL
| ERR_PASS1
,
1271 "nonexistent environment variable `%s'", v
);
1273 * FIXME We better should investigate if accessing
1274 * ->text[1] without ->text[0] is safe enough.
1276 t
->text
= nasm_zalloc(2);
1278 t
->text
= nasm_strdup(p
);
1283 /* Expand local macros here and not during preprocessing */
1284 if (expand_locals
&&
1285 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1286 t
->text
[0] == '%' && t
->text
[1] == '$') {
1289 Context
*ctx
= get_ctx(t
->text
, &q
);
1292 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1293 p
= nasm_strcat(buffer
, q
);
1298 if (t
->type
== TOK_WHITESPACE
)
1301 len
+= strlen(t
->text
);
1304 p
= line
= nasm_malloc(len
+ 1);
1306 list_for_each(t
, tlist
) {
1307 if (t
->type
== TOK_WHITESPACE
) {
1309 } else if (t
->text
) {
1321 * A scanner, suitable for use by the expression evaluator, which
1322 * operates on a line of Tokens. Expects a pointer to a pointer to
1323 * the first token in the line to be passed in as its private_data
1326 * FIX: This really needs to be unified with stdscan.
1328 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1330 Token
**tlineptr
= private_data
;
1332 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1336 *tlineptr
= tline
? tline
->next
: NULL
;
1337 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1338 tline
->type
== TOK_COMMENT
));
1341 return tokval
->t_type
= TOKEN_EOS
;
1343 tokval
->t_charptr
= tline
->text
;
1345 if (tline
->text
[0] == '$' && !tline
->text
[1])
1346 return tokval
->t_type
= TOKEN_HERE
;
1347 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1348 return tokval
->t_type
= TOKEN_BASE
;
1350 if (tline
->type
== TOK_ID
) {
1351 p
= tokval
->t_charptr
= tline
->text
;
1353 tokval
->t_charptr
++;
1354 return tokval
->t_type
= TOKEN_ID
;
1357 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1358 if (r
>= p
+MAX_KEYWORD
)
1359 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1360 *s
++ = nasm_tolower(*r
);
1363 /* right, so we have an identifier sitting in temp storage. now,
1364 * is it actually a register or instruction name, or what? */
1365 return nasm_token_hash(ourcopy
, tokval
);
1368 if (tline
->type
== TOK_NUMBER
) {
1370 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1371 tokval
->t_charptr
= tline
->text
;
1373 return tokval
->t_type
= TOKEN_ERRNUM
;
1375 return tokval
->t_type
= TOKEN_NUM
;
1378 if (tline
->type
== TOK_FLOAT
) {
1379 return tokval
->t_type
= TOKEN_FLOAT
;
1382 if (tline
->type
== TOK_STRING
) {
1385 bq
= tline
->text
[0];
1386 tokval
->t_charptr
= tline
->text
;
1387 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1389 if (ep
[0] != bq
|| ep
[1] != '\0')
1390 return tokval
->t_type
= TOKEN_ERRSTR
;
1392 return tokval
->t_type
= TOKEN_STR
;
1395 if (tline
->type
== TOK_OTHER
) {
1396 if (!strcmp(tline
->text
, "<<"))
1397 return tokval
->t_type
= TOKEN_SHL
;
1398 if (!strcmp(tline
->text
, ">>"))
1399 return tokval
->t_type
= TOKEN_SHR
;
1400 if (!strcmp(tline
->text
, "//"))
1401 return tokval
->t_type
= TOKEN_SDIV
;
1402 if (!strcmp(tline
->text
, "%%"))
1403 return tokval
->t_type
= TOKEN_SMOD
;
1404 if (!strcmp(tline
->text
, "=="))
1405 return tokval
->t_type
= TOKEN_EQ
;
1406 if (!strcmp(tline
->text
, "<>"))
1407 return tokval
->t_type
= TOKEN_NE
;
1408 if (!strcmp(tline
->text
, "!="))
1409 return tokval
->t_type
= TOKEN_NE
;
1410 if (!strcmp(tline
->text
, "<="))
1411 return tokval
->t_type
= TOKEN_LE
;
1412 if (!strcmp(tline
->text
, ">="))
1413 return tokval
->t_type
= TOKEN_GE
;
1414 if (!strcmp(tline
->text
, "&&"))
1415 return tokval
->t_type
= TOKEN_DBL_AND
;
1416 if (!strcmp(tline
->text
, "^^"))
1417 return tokval
->t_type
= TOKEN_DBL_XOR
;
1418 if (!strcmp(tline
->text
, "||"))
1419 return tokval
->t_type
= TOKEN_DBL_OR
;
1423 * We have no other options: just return the first character of
1426 return tokval
->t_type
= tline
->text
[0];
1430 * Compare a string to the name of an existing macro; this is a
1431 * simple wrapper which calls either strcmp or nasm_stricmp
1432 * depending on the value of the `casesense' parameter.
1434 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1436 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1440 * Compare a string to the name of an existing macro; this is a
1441 * simple wrapper which calls either strcmp or nasm_stricmp
1442 * depending on the value of the `casesense' parameter.
1444 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1446 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1450 * Return the Context structure associated with a %$ token. Return
1451 * NULL, having _already_ reported an error condition, if the
1452 * context stack isn't deep enough for the supplied number of $
1455 * If "namep" is non-NULL, set it to the pointer to the macro name
1456 * tail, i.e. the part beyond %$...
1458 static Context
*get_ctx(const char *name
, const char **namep
)
1466 if (!name
|| name
[0] != '%' || name
[1] != '$')
1470 nasm_error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1477 while (ctx
&& *name
== '$') {
1483 nasm_error(ERR_NONFATAL
, "`%s': context stack is only"
1484 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1495 * Check to see if a file is already in a string list
1497 static bool in_list(const StrList
*list
, const char *str
)
1500 if (!strcmp(list
->str
, str
))
1508 * Open an include file. This routine must always return a valid
1509 * file pointer if it returns - it's responsible for throwing an
1510 * ERR_FATAL and bombing out completely if not. It should also try
1511 * the include path one by one until it finds the file or reaches
1512 * the end of the path.
1514 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1515 char **found_path
, bool missing_ok
, const char *mode
)
1519 IncPath
*ip
= ipath
;
1520 int len
= strlen(file
);
1521 size_t prefix_len
= 0;
1526 path_len
= prefix_len
+ len
+ 1;
1528 sl
= nasm_malloc(path_len
+ sizeof sl
->next
);
1529 memcpy(sl
->str
, prefix
, prefix_len
);
1530 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1532 if (found_path
!= NULL
) {
1533 *found_path
= nasm_malloc(path_len
);
1534 memcpy(*found_path
, sl
->str
, path_len
);
1537 fp
= fopen(sl
->str
, mode
);
1538 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1548 if (found_path
!= NULL
&& *found_path
!= NULL
) {
1549 nasm_free(*found_path
);
1562 prefix_len
= strlen(prefix
);
1564 /* -MG given and file not found */
1565 if (dhead
&& !in_list(*dhead
, file
)) {
1566 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1568 strcpy(sl
->str
, file
);
1576 nasm_error(ERR_FATAL
, "unable to open include file `%s'", file
);
1581 * Opens an include or input file. Public version, for use by modules
1582 * that get a file:lineno pair and need to look at the file again
1583 * (e.g. the CodeView debug backend). Returns NULL on failure.
1585 FILE *pp_input_fopen(const char *filename
, const char *mode
)
1588 StrList
*xsl
= NULL
;
1589 StrList
**xst
= &xsl
;
1591 fp
= inc_fopen(filename
, &xsl
, &xst
, NULL
, true, mode
);
1598 * Determine if we should warn on defining a single-line macro of
1599 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1600 * return true if _any_ single-line macro of that name is defined.
1601 * Otherwise, will return true if a single-line macro with either
1602 * `nparam' or no parameters is defined.
1604 * If a macro with precisely the right number of parameters is
1605 * defined, or nparam is -1, the address of the definition structure
1606 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1607 * is NULL, no action will be taken regarding its contents, and no
1610 * Note that this is also called with nparam zero to resolve
1613 * If you already know which context macro belongs to, you can pass
1614 * the context pointer as first parameter; if you won't but name begins
1615 * with %$ the context will be automatically computed. If all_contexts
1616 * is true, macro will be searched in outer contexts as well.
1619 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1622 struct hash_table
*smtbl
;
1626 smtbl
= &ctx
->localmac
;
1627 } else if (name
[0] == '%' && name
[1] == '$') {
1629 ctx
= get_ctx(name
, &name
);
1631 return false; /* got to return _something_ */
1632 smtbl
= &ctx
->localmac
;
1636 m
= (SMacro
*) hash_findix(smtbl
, name
);
1639 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1640 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1642 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1656 * Count and mark off the parameters in a multi-line macro call.
1657 * This is called both from within the multi-line macro expansion
1658 * code, and also to mark off the default parameters when provided
1659 * in a %macro definition line.
1661 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1663 int paramsize
, brace
;
1665 *nparam
= paramsize
= 0;
1668 /* +1: we need space for the final NULL */
1669 if (*nparam
+1 >= paramsize
) {
1670 paramsize
+= PARAM_DELTA
;
1671 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1675 if (tok_is_(t
, "{"))
1677 (*params
)[(*nparam
)++] = t
;
1679 while (brace
&& (t
= t
->next
) != NULL
) {
1680 if (tok_is_(t
, "{"))
1682 else if (tok_is_(t
, "}"))
1688 * Now we've found the closing brace, look further
1693 if (tok_isnt_(t
, ",")) {
1694 nasm_error(ERR_NONFATAL
,
1695 "braces do not enclose all of macro parameter");
1696 while (tok_isnt_(t
, ","))
1701 while (tok_isnt_(t
, ","))
1704 if (t
) { /* got a comma/brace */
1705 t
= t
->next
; /* eat the comma */
1711 * Determine whether one of the various `if' conditions is true or
1714 * We must free the tline we get passed.
1716 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1718 enum pp_conditional i
= PP_COND(ct
);
1720 Token
*t
, *tt
, **tptr
, *origline
;
1721 struct tokenval tokval
;
1723 enum pp_token_type needtype
;
1730 j
= false; /* have we matched yet? */
1735 if (tline
->type
!= TOK_ID
) {
1736 nasm_error(ERR_NONFATAL
,
1737 "`%s' expects context identifiers", pp_directives
[ct
]);
1738 free_tlist(origline
);
1741 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1743 tline
= tline
->next
;
1748 j
= false; /* have we matched yet? */
1751 if (!tline
|| (tline
->type
!= TOK_ID
&&
1752 (tline
->type
!= TOK_PREPROC_ID
||
1753 tline
->text
[1] != '$'))) {
1754 nasm_error(ERR_NONFATAL
,
1755 "`%s' expects macro identifiers", pp_directives
[ct
]);
1758 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1760 tline
= tline
->next
;
1765 tline
= expand_smacro(tline
);
1766 j
= false; /* have we matched yet? */
1769 if (!tline
|| (tline
->type
!= TOK_ID
&&
1770 tline
->type
!= TOK_STRING
&&
1771 (tline
->type
!= TOK_PREPROC_ID
||
1772 tline
->text
[1] != '!'))) {
1773 nasm_error(ERR_NONFATAL
,
1774 "`%s' expects environment variable names",
1779 if (tline
->type
== TOK_PREPROC_ID
)
1780 p
+= 2; /* Skip leading %! */
1781 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1782 nasm_unquote_cstr(p
, ct
);
1785 tline
= tline
->next
;
1791 tline
= expand_smacro(tline
);
1793 while (tok_isnt_(tt
, ","))
1796 nasm_error(ERR_NONFATAL
,
1797 "`%s' expects two comma-separated arguments",
1802 j
= true; /* assume equality unless proved not */
1803 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1804 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1805 nasm_error(ERR_NONFATAL
, "`%s': more than one comma on line",
1809 if (t
->type
== TOK_WHITESPACE
) {
1813 if (tt
->type
== TOK_WHITESPACE
) {
1817 if (tt
->type
!= t
->type
) {
1818 j
= false; /* found mismatching tokens */
1821 /* When comparing strings, need to unquote them first */
1822 if (t
->type
== TOK_STRING
) {
1823 size_t l1
= nasm_unquote(t
->text
, NULL
);
1824 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1830 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1834 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1835 j
= false; /* found mismatching tokens */
1842 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1843 j
= false; /* trailing gunk on one end or other */
1849 MMacro searching
, *mmac
;
1852 tline
= expand_id(tline
);
1853 if (!tok_type_(tline
, TOK_ID
)) {
1854 nasm_error(ERR_NONFATAL
,
1855 "`%s' expects a macro name", pp_directives
[ct
]);
1858 searching
.name
= nasm_strdup(tline
->text
);
1859 searching
.casesense
= true;
1860 searching
.plus
= false;
1861 searching
.nolist
= false;
1862 searching
.in_progress
= 0;
1863 searching
.max_depth
= 0;
1864 searching
.rep_nest
= NULL
;
1865 searching
.nparam_min
= 0;
1866 searching
.nparam_max
= INT_MAX
;
1867 tline
= expand_smacro(tline
->next
);
1870 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1871 nasm_error(ERR_NONFATAL
,
1872 "`%s' expects a parameter count or nothing",
1875 searching
.nparam_min
= searching
.nparam_max
=
1876 readnum(tline
->text
, &j
);
1878 nasm_error(ERR_NONFATAL
,
1879 "unable to parse parameter count `%s'",
1882 if (tline
&& tok_is_(tline
->next
, "-")) {
1883 tline
= tline
->next
->next
;
1884 if (tok_is_(tline
, "*"))
1885 searching
.nparam_max
= INT_MAX
;
1886 else if (!tok_type_(tline
, TOK_NUMBER
))
1887 nasm_error(ERR_NONFATAL
,
1888 "`%s' expects a parameter count after `-'",
1891 searching
.nparam_max
= readnum(tline
->text
, &j
);
1893 nasm_error(ERR_NONFATAL
,
1894 "unable to parse parameter count `%s'",
1896 if (searching
.nparam_min
> searching
.nparam_max
)
1897 nasm_error(ERR_NONFATAL
,
1898 "minimum parameter count exceeds maximum");
1901 if (tline
&& tok_is_(tline
->next
, "+")) {
1902 tline
= tline
->next
;
1903 searching
.plus
= true;
1905 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1907 if (!strcmp(mmac
->name
, searching
.name
) &&
1908 (mmac
->nparam_min
<= searching
.nparam_max
1910 && (searching
.nparam_min
<= mmac
->nparam_max
1917 if (tline
&& tline
->next
)
1918 nasm_error(ERR_WARNING
|ERR_PASS1
,
1919 "trailing garbage after %%ifmacro ignored");
1920 nasm_free(searching
.name
);
1929 needtype
= TOK_NUMBER
;
1932 needtype
= TOK_STRING
;
1936 t
= tline
= expand_smacro(tline
);
1938 while (tok_type_(t
, TOK_WHITESPACE
) ||
1939 (needtype
== TOK_NUMBER
&&
1940 tok_type_(t
, TOK_OTHER
) &&
1941 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1945 j
= tok_type_(t
, needtype
);
1949 t
= tline
= expand_smacro(tline
);
1950 while (tok_type_(t
, TOK_WHITESPACE
))
1955 t
= t
->next
; /* Skip the actual token */
1956 while (tok_type_(t
, TOK_WHITESPACE
))
1958 j
= !t
; /* Should be nothing left */
1963 t
= tline
= expand_smacro(tline
);
1964 while (tok_type_(t
, TOK_WHITESPACE
))
1967 j
= !t
; /* Should be empty */
1971 t
= tline
= expand_smacro(tline
);
1973 tokval
.t_type
= TOKEN_INVALID
;
1974 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1975 NULL
, pass
| CRITICAL
, NULL
);
1979 nasm_error(ERR_WARNING
|ERR_PASS1
,
1980 "trailing garbage after expression ignored");
1981 if (!is_simple(evalresult
)) {
1982 nasm_error(ERR_NONFATAL
,
1983 "non-constant value given to `%s'", pp_directives
[ct
]);
1986 j
= reloc_value(evalresult
) != 0;
1990 nasm_error(ERR_FATAL
,
1991 "preprocessor directive `%s' not yet implemented",
1996 free_tlist(origline
);
1997 return j
^ PP_NEGATIVE(ct
);
2000 free_tlist(origline
);
2005 * Common code for defining an smacro
2007 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
2008 int nparam
, Token
*expansion
)
2010 SMacro
*smac
, **smhead
;
2011 struct hash_table
*smtbl
;
2013 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
2015 nasm_error(ERR_WARNING
|ERR_PASS1
,
2016 "single-line macro `%s' defined both with and"
2017 " without parameters", mname
);
2019 * Some instances of the old code considered this a failure,
2020 * some others didn't. What is the right thing to do here?
2022 free_tlist(expansion
);
2023 return false; /* Failure */
2026 * We're redefining, so we have to take over an
2027 * existing SMacro structure. This means freeing
2028 * what was already in it.
2030 nasm_free(smac
->name
);
2031 free_tlist(smac
->expansion
);
2034 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2035 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
2036 smac
= nasm_malloc(sizeof(SMacro
));
2037 smac
->next
= *smhead
;
2040 smac
->name
= nasm_strdup(mname
);
2041 smac
->casesense
= casesense
;
2042 smac
->nparam
= nparam
;
2043 smac
->expansion
= expansion
;
2044 smac
->in_progress
= false;
2045 return true; /* Success */
2049 * Undefine an smacro
2051 static void undef_smacro(Context
*ctx
, const char *mname
)
2053 SMacro
**smhead
, *s
, **sp
;
2054 struct hash_table
*smtbl
;
2056 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2057 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2061 * We now have a macro name... go hunt for it.
2064 while ((s
= *sp
) != NULL
) {
2065 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2068 free_tlist(s
->expansion
);
2078 * Parse a mmacro specification.
2080 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2084 tline
= tline
->next
;
2086 tline
= expand_id(tline
);
2087 if (!tok_type_(tline
, TOK_ID
)) {
2088 nasm_error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2093 def
->name
= nasm_strdup(tline
->text
);
2095 def
->nolist
= false;
2096 def
->in_progress
= 0;
2097 def
->rep_nest
= NULL
;
2098 def
->nparam_min
= 0;
2099 def
->nparam_max
= 0;
2101 tline
= expand_smacro(tline
->next
);
2103 if (!tok_type_(tline
, TOK_NUMBER
)) {
2104 nasm_error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2106 def
->nparam_min
= def
->nparam_max
=
2107 readnum(tline
->text
, &err
);
2109 nasm_error(ERR_NONFATAL
,
2110 "unable to parse parameter count `%s'", tline
->text
);
2112 if (tline
&& tok_is_(tline
->next
, "-")) {
2113 tline
= tline
->next
->next
;
2114 if (tok_is_(tline
, "*")) {
2115 def
->nparam_max
= INT_MAX
;
2116 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2117 nasm_error(ERR_NONFATAL
,
2118 "`%s' expects a parameter count after `-'", directive
);
2120 def
->nparam_max
= readnum(tline
->text
, &err
);
2122 nasm_error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2125 if (def
->nparam_min
> def
->nparam_max
) {
2126 nasm_error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2130 if (tline
&& tok_is_(tline
->next
, "+")) {
2131 tline
= tline
->next
;
2134 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2135 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2136 tline
= tline
->next
;
2141 * Handle default parameters.
2143 if (tline
&& tline
->next
) {
2144 def
->dlist
= tline
->next
;
2146 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2149 def
->defaults
= NULL
;
2151 def
->expansion
= NULL
;
2153 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2155 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2156 "too many default macro parameters");
2163 * Decode a size directive
2165 static int parse_size(const char *str
) {
2166 static const char *size_names
[] =
2167 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2168 static const int sizes
[] =
2169 { 0, 1, 4, 16, 8, 10, 2, 32 };
2171 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2175 * find and process preprocessor directive in passed line
2176 * Find out if a line contains a preprocessor directive, and deal
2179 * If a directive _is_ found, it is the responsibility of this routine
2180 * (and not the caller) to free_tlist() the line.
2182 * @param tline a pointer to the current tokeninzed line linked list
2183 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2186 static int do_directive(Token
* tline
)
2188 enum preproc_token i
;
2196 char *p
, *pp
, *found_path
;
2201 MMacro
*mmac
, **mmhead
;
2202 Token
*t
= NULL
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2204 struct tokenval tokval
;
2206 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2214 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2215 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2216 || tline
->text
[1] == '!'))
2217 return NO_DIRECTIVE_FOUND
;
2219 i
= pp_token_hash(tline
->text
);
2222 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2223 * since they are known to be buggy at moment, we need to fix them
2224 * in future release (2.09-2.10)
2226 if (i
== PP_RMACRO
|| i
== PP_IRMACRO
|| i
== PP_EXITMACRO
) {
2227 nasm_error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2229 return NO_DIRECTIVE_FOUND
;
2233 * If we're in a non-emitting branch of a condition construct,
2234 * or walking to the end of an already terminated %rep block,
2235 * we should ignore all directives except for condition
2238 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2239 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2240 return NO_DIRECTIVE_FOUND
;
2244 * If we're defining a macro or reading a %rep block, we should
2245 * ignore all directives except for %macro/%imacro (which nest),
2246 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2247 * If we're in a %rep block, another %rep nests, so should be let through.
2249 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2250 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2251 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2252 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2253 return NO_DIRECTIVE_FOUND
;
2257 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2258 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2260 return NO_DIRECTIVE_FOUND
;
2261 } else if (nested_mac_count
> 0) {
2262 if (i
== PP_ENDMACRO
) {
2264 return NO_DIRECTIVE_FOUND
;
2267 if (!defining
->name
) {
2270 return NO_DIRECTIVE_FOUND
;
2271 } else if (nested_rep_count
> 0) {
2272 if (i
== PP_ENDREP
) {
2274 return NO_DIRECTIVE_FOUND
;
2282 nasm_error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2284 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2288 * Currently %pragma doesn't do anything; it is here for
2289 * forward compatibility with future versions of NASM.
2291 free_tlist(origline
);
2292 return DIRECTIVE_FOUND
;
2295 /* Directive to tell NASM what the default stack size is. The
2296 * default is for a 16-bit stack, and this can be overriden with
2299 tline
= tline
->next
;
2300 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2301 tline
= tline
->next
;
2302 if (!tline
|| tline
->type
!= TOK_ID
) {
2303 nasm_error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2304 free_tlist(origline
);
2305 return DIRECTIVE_FOUND
;
2307 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2308 /* All subsequent ARG directives are for a 32-bit stack */
2310 StackPointer
= "ebp";
2313 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2314 /* All subsequent ARG directives are for a 64-bit stack */
2316 StackPointer
= "rbp";
2319 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2320 /* All subsequent ARG directives are for a 16-bit stack,
2321 * far function call.
2324 StackPointer
= "bp";
2327 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2328 /* All subsequent ARG directives are for a 16-bit stack,
2329 * far function call. We don't support near functions.
2332 StackPointer
= "bp";
2336 nasm_error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2337 free_tlist(origline
);
2338 return DIRECTIVE_FOUND
;
2340 free_tlist(origline
);
2341 return DIRECTIVE_FOUND
;
2344 /* TASM like ARG directive to define arguments to functions, in
2345 * the following form:
2347 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2351 char *arg
, directive
[256];
2352 int size
= StackSize
;
2354 /* Find the argument name */
2355 tline
= tline
->next
;
2356 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2357 tline
= tline
->next
;
2358 if (!tline
|| tline
->type
!= TOK_ID
) {
2359 nasm_error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2360 free_tlist(origline
);
2361 return DIRECTIVE_FOUND
;
2365 /* Find the argument size type */
2366 tline
= tline
->next
;
2367 if (!tline
|| tline
->type
!= TOK_OTHER
2368 || tline
->text
[0] != ':') {
2369 nasm_error(ERR_NONFATAL
,
2370 "Syntax error processing `%%arg' directive");
2371 free_tlist(origline
);
2372 return DIRECTIVE_FOUND
;
2374 tline
= tline
->next
;
2375 if (!tline
|| tline
->type
!= TOK_ID
) {
2376 nasm_error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2377 free_tlist(origline
);
2378 return DIRECTIVE_FOUND
;
2381 /* Allow macro expansion of type parameter */
2382 tt
= tokenize(tline
->text
);
2383 tt
= expand_smacro(tt
);
2384 size
= parse_size(tt
->text
);
2386 nasm_error(ERR_NONFATAL
,
2387 "Invalid size type for `%%arg' missing directive");
2389 free_tlist(origline
);
2390 return DIRECTIVE_FOUND
;
2394 /* Round up to even stack slots */
2395 size
= ALIGN(size
, StackSize
);
2397 /* Now define the macro for the argument */
2398 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2399 arg
, StackPointer
, offset
);
2400 do_directive(tokenize(directive
));
2403 /* Move to the next argument in the list */
2404 tline
= tline
->next
;
2405 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2406 tline
= tline
->next
;
2407 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2409 free_tlist(origline
);
2410 return DIRECTIVE_FOUND
;
2413 /* TASM like LOCAL directive to define local variables for a
2414 * function, in the following form:
2416 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2418 * The '= LocalSize' at the end is ignored by NASM, but is
2419 * required by TASM to define the local parameter size (and used
2420 * by the TASM macro package).
2422 offset
= LocalOffset
;
2424 char *local
, directive
[256];
2425 int size
= StackSize
;
2427 /* Find the argument name */
2428 tline
= tline
->next
;
2429 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2430 tline
= tline
->next
;
2431 if (!tline
|| tline
->type
!= TOK_ID
) {
2432 nasm_error(ERR_NONFATAL
,
2433 "`%%local' missing argument parameter");
2434 free_tlist(origline
);
2435 return DIRECTIVE_FOUND
;
2437 local
= tline
->text
;
2439 /* Find the argument size type */
2440 tline
= tline
->next
;
2441 if (!tline
|| tline
->type
!= TOK_OTHER
2442 || tline
->text
[0] != ':') {
2443 nasm_error(ERR_NONFATAL
,
2444 "Syntax error processing `%%local' directive");
2445 free_tlist(origline
);
2446 return DIRECTIVE_FOUND
;
2448 tline
= tline
->next
;
2449 if (!tline
|| tline
->type
!= TOK_ID
) {
2450 nasm_error(ERR_NONFATAL
,
2451 "`%%local' missing size type parameter");
2452 free_tlist(origline
);
2453 return DIRECTIVE_FOUND
;
2456 /* Allow macro expansion of type parameter */
2457 tt
= tokenize(tline
->text
);
2458 tt
= expand_smacro(tt
);
2459 size
= parse_size(tt
->text
);
2461 nasm_error(ERR_NONFATAL
,
2462 "Invalid size type for `%%local' missing directive");
2464 free_tlist(origline
);
2465 return DIRECTIVE_FOUND
;
2469 /* Round up to even stack slots */
2470 size
= ALIGN(size
, StackSize
);
2472 offset
+= size
; /* Negative offset, increment before */
2474 /* Now define the macro for the argument */
2475 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2476 local
, StackPointer
, offset
);
2477 do_directive(tokenize(directive
));
2479 /* Now define the assign to setup the enter_c macro correctly */
2480 snprintf(directive
, sizeof(directive
),
2481 "%%assign %%$localsize %%$localsize+%d", size
);
2482 do_directive(tokenize(directive
));
2484 /* Move to the next argument in the list */
2485 tline
= tline
->next
;
2486 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2487 tline
= tline
->next
;
2488 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2489 LocalOffset
= offset
;
2490 free_tlist(origline
);
2491 return DIRECTIVE_FOUND
;
2495 nasm_error(ERR_WARNING
|ERR_PASS1
,
2496 "trailing garbage after `%%clear' ignored");
2499 free_tlist(origline
);
2500 return DIRECTIVE_FOUND
;
2503 t
= tline
->next
= expand_smacro(tline
->next
);
2505 if (!t
|| (t
->type
!= TOK_STRING
&&
2506 t
->type
!= TOK_INTERNAL_STRING
)) {
2507 nasm_error(ERR_NONFATAL
, "`%%depend' expects a file name");
2508 free_tlist(origline
);
2509 return DIRECTIVE_FOUND
; /* but we did _something_ */
2512 nasm_error(ERR_WARNING
|ERR_PASS1
,
2513 "trailing garbage after `%%depend' ignored");
2515 if (t
->type
!= TOK_INTERNAL_STRING
)
2516 nasm_unquote_cstr(p
, i
);
2517 if (dephead
&& !in_list(*dephead
, p
)) {
2518 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2522 deptail
= &sl
->next
;
2524 free_tlist(origline
);
2525 return DIRECTIVE_FOUND
;
2528 t
= tline
->next
= expand_smacro(tline
->next
);
2531 if (!t
|| (t
->type
!= TOK_STRING
&&
2532 t
->type
!= TOK_INTERNAL_STRING
)) {
2533 nasm_error(ERR_NONFATAL
, "`%%include' expects a file name");
2534 free_tlist(origline
);
2535 return DIRECTIVE_FOUND
; /* but we did _something_ */
2538 nasm_error(ERR_WARNING
|ERR_PASS1
,
2539 "trailing garbage after `%%include' ignored");
2541 if (t
->type
!= TOK_INTERNAL_STRING
)
2542 nasm_unquote_cstr(p
, i
);
2543 inc
= nasm_malloc(sizeof(Include
));
2547 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, &found_path
, pass
== 0, "r");
2549 /* -MG given but file not found */
2552 inc
->fname
= src_set_fname(found_path
? found_path
: p
);
2553 inc
->lineno
= src_set_linnum(0);
2555 inc
->expansion
= NULL
;
2558 lfmt
->uplevel(LIST_INCLUDE
);
2560 free_tlist(origline
);
2561 return DIRECTIVE_FOUND
;
2565 static macros_t
*use_pkg
;
2566 const char *pkg_macro
= NULL
;
2568 tline
= tline
->next
;
2570 tline
= expand_id(tline
);
2572 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2573 tline
->type
!= TOK_INTERNAL_STRING
&&
2574 tline
->type
!= TOK_ID
)) {
2575 nasm_error(ERR_NONFATAL
, "`%%use' expects a package name");
2576 free_tlist(origline
);
2577 return DIRECTIVE_FOUND
; /* but we did _something_ */
2580 nasm_error(ERR_WARNING
|ERR_PASS1
,
2581 "trailing garbage after `%%use' ignored");
2582 if (tline
->type
== TOK_STRING
)
2583 nasm_unquote_cstr(tline
->text
, i
);
2584 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2586 nasm_error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2588 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2589 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2590 /* Not already included, go ahead and include it */
2591 stdmacpos
= use_pkg
;
2593 free_tlist(origline
);
2594 return DIRECTIVE_FOUND
;
2599 tline
= tline
->next
;
2601 tline
= expand_id(tline
);
2603 if (!tok_type_(tline
, TOK_ID
)) {
2604 nasm_error(ERR_NONFATAL
, "`%s' expects a context identifier",
2606 free_tlist(origline
);
2607 return DIRECTIVE_FOUND
; /* but we did _something_ */
2610 nasm_error(ERR_WARNING
|ERR_PASS1
,
2611 "trailing garbage after `%s' ignored",
2613 p
= nasm_strdup(tline
->text
);
2615 p
= NULL
; /* Anonymous */
2619 ctx
= nasm_malloc(sizeof(Context
));
2621 hash_init(&ctx
->localmac
, HASH_SMALL
);
2623 ctx
->number
= unique
++;
2628 nasm_error(ERR_NONFATAL
, "`%s': context stack is empty",
2630 } else if (i
== PP_POP
) {
2631 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2632 nasm_error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2634 cstk
->name
? cstk
->name
: "anonymous", p
);
2639 nasm_free(cstk
->name
);
2645 free_tlist(origline
);
2646 return DIRECTIVE_FOUND
;
2648 severity
= ERR_FATAL
;
2651 severity
= ERR_NONFATAL
;
2654 severity
= ERR_WARNING
|ERR_WARN_USER
;
2659 /* Only error out if this is the final pass */
2660 if (pass
!= 2 && i
!= PP_FATAL
)
2661 return DIRECTIVE_FOUND
;
2663 tline
->next
= expand_smacro(tline
->next
);
2664 tline
= tline
->next
;
2666 t
= tline
? tline
->next
: NULL
;
2668 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2669 /* The line contains only a quoted string */
2671 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2672 nasm_error(severity
, "%s", p
);
2674 /* Not a quoted string, or more than a quoted string */
2675 p
= detoken(tline
, false);
2676 nasm_error(severity
, "%s", p
);
2679 free_tlist(origline
);
2680 return DIRECTIVE_FOUND
;
2684 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2687 j
= if_condition(tline
->next
, i
);
2688 tline
->next
= NULL
; /* it got freed */
2689 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2691 cond
= nasm_malloc(sizeof(Cond
));
2692 cond
->next
= istk
->conds
;
2696 istk
->mstk
->condcnt
++;
2697 free_tlist(origline
);
2698 return DIRECTIVE_FOUND
;
2702 nasm_error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2703 switch(istk
->conds
->state
) {
2705 istk
->conds
->state
= COND_DONE
;
2712 case COND_ELSE_TRUE
:
2713 case COND_ELSE_FALSE
:
2714 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2715 "`%%elif' after `%%else' ignored");
2716 istk
->conds
->state
= COND_NEVER
;
2721 * IMPORTANT: In the case of %if, we will already have
2722 * called expand_mmac_params(); however, if we're
2723 * processing an %elif we must have been in a
2724 * non-emitting mode, which would have inhibited
2725 * the normal invocation of expand_mmac_params().
2726 * Therefore, we have to do it explicitly here.
2728 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2729 tline
->next
= NULL
; /* it got freed */
2730 istk
->conds
->state
=
2731 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2734 free_tlist(origline
);
2735 return DIRECTIVE_FOUND
;
2739 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2740 "trailing garbage after `%%else' ignored");
2742 nasm_fatal(0, "`%%else: no matching `%%if'");
2743 switch(istk
->conds
->state
) {
2746 istk
->conds
->state
= COND_ELSE_FALSE
;
2753 istk
->conds
->state
= COND_ELSE_TRUE
;
2756 case COND_ELSE_TRUE
:
2757 case COND_ELSE_FALSE
:
2758 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2759 "`%%else' after `%%else' ignored.");
2760 istk
->conds
->state
= COND_NEVER
;
2763 free_tlist(origline
);
2764 return DIRECTIVE_FOUND
;
2768 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2769 "trailing garbage after `%%endif' ignored");
2771 nasm_error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2773 istk
->conds
= cond
->next
;
2776 istk
->mstk
->condcnt
--;
2777 free_tlist(origline
);
2778 return DIRECTIVE_FOUND
;
2785 nasm_error(ERR_FATAL
, "`%s': already defining a macro",
2787 return DIRECTIVE_FOUND
;
2789 defining
= nasm_zalloc(sizeof(MMacro
));
2790 defining
->max_depth
=
2791 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2792 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2793 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2794 nasm_free(defining
);
2796 return DIRECTIVE_FOUND
;
2799 src_get(&defining
->xline
, &defining
->fname
);
2801 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2803 if (!strcmp(mmac
->name
, defining
->name
) &&
2804 (mmac
->nparam_min
<= defining
->nparam_max
2806 && (defining
->nparam_min
<= mmac
->nparam_max
2808 nasm_error(ERR_WARNING
|ERR_PASS1
,
2809 "redefining multi-line macro `%s'", defining
->name
);
2810 return DIRECTIVE_FOUND
;
2814 free_tlist(origline
);
2815 return DIRECTIVE_FOUND
;
2819 if (! (defining
&& defining
->name
)) {
2820 nasm_error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2821 return DIRECTIVE_FOUND
;
2823 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2824 defining
->next
= *mmhead
;
2827 free_tlist(origline
);
2828 return DIRECTIVE_FOUND
;
2832 * We must search along istk->expansion until we hit a
2833 * macro-end marker for a macro with a name. Then we
2834 * bypass all lines between exitmacro and endmacro.
2836 list_for_each(l
, istk
->expansion
)
2837 if (l
->finishes
&& l
->finishes
->name
)
2842 * Remove all conditional entries relative to this
2843 * macro invocation. (safe to do in this context)
2845 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2847 istk
->conds
= cond
->next
;
2850 istk
->expansion
= l
;
2852 nasm_error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2854 free_tlist(origline
);
2855 return DIRECTIVE_FOUND
;
2863 spec
.casesense
= (i
== PP_UNMACRO
);
2864 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2865 return DIRECTIVE_FOUND
;
2867 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2868 while (mmac_p
&& *mmac_p
) {
2870 if (mmac
->casesense
== spec
.casesense
&&
2871 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2872 mmac
->nparam_min
== spec
.nparam_min
&&
2873 mmac
->nparam_max
== spec
.nparam_max
&&
2874 mmac
->plus
== spec
.plus
) {
2875 *mmac_p
= mmac
->next
;
2878 mmac_p
= &mmac
->next
;
2881 free_tlist(origline
);
2882 free_tlist(spec
.dlist
);
2883 return DIRECTIVE_FOUND
;
2887 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2888 tline
= tline
->next
;
2890 free_tlist(origline
);
2891 nasm_error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2892 return DIRECTIVE_FOUND
;
2894 t
= expand_smacro(tline
->next
);
2896 free_tlist(origline
);
2899 tokval
.t_type
= TOKEN_INVALID
;
2901 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
2904 return DIRECTIVE_FOUND
;
2906 nasm_error(ERR_WARNING
|ERR_PASS1
,
2907 "trailing garbage after expression ignored");
2908 if (!is_simple(evalresult
)) {
2909 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2910 return DIRECTIVE_FOUND
;
2913 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2914 mmac
= mmac
->next_active
;
2916 nasm_error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2917 } else if (mmac
->nparam
== 0) {
2918 nasm_error(ERR_NONFATAL
,
2919 "`%%rotate' invoked within macro without parameters");
2921 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2923 rotate
%= (int)mmac
->nparam
;
2925 rotate
+= mmac
->nparam
;
2927 mmac
->rotate
= rotate
;
2929 return DIRECTIVE_FOUND
;
2934 tline
= tline
->next
;
2935 } while (tok_type_(tline
, TOK_WHITESPACE
));
2937 if (tok_type_(tline
, TOK_ID
) &&
2938 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2941 tline
= tline
->next
;
2942 } while (tok_type_(tline
, TOK_WHITESPACE
));
2946 t
= expand_smacro(tline
);
2948 tokval
.t_type
= TOKEN_INVALID
;
2950 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
2952 free_tlist(origline
);
2953 return DIRECTIVE_FOUND
;
2956 nasm_error(ERR_WARNING
|ERR_PASS1
,
2957 "trailing garbage after expression ignored");
2958 if (!is_simple(evalresult
)) {
2959 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2960 return DIRECTIVE_FOUND
;
2962 count
= reloc_value(evalresult
);
2963 if (count
>= REP_LIMIT
) {
2964 nasm_error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2969 nasm_error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2972 free_tlist(origline
);
2974 tmp_defining
= defining
;
2975 defining
= nasm_malloc(sizeof(MMacro
));
2976 defining
->prev
= NULL
;
2977 defining
->name
= NULL
; /* flags this macro as a %rep block */
2978 defining
->casesense
= false;
2979 defining
->plus
= false;
2980 defining
->nolist
= nolist
;
2981 defining
->in_progress
= count
;
2982 defining
->max_depth
= 0;
2983 defining
->nparam_min
= defining
->nparam_max
= 0;
2984 defining
->defaults
= NULL
;
2985 defining
->dlist
= NULL
;
2986 defining
->expansion
= NULL
;
2987 defining
->next_active
= istk
->mstk
;
2988 defining
->rep_nest
= tmp_defining
;
2989 return DIRECTIVE_FOUND
;
2992 if (!defining
|| defining
->name
) {
2993 nasm_error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2994 return DIRECTIVE_FOUND
;
2998 * Now we have a "macro" defined - although it has no name
2999 * and we won't be entering it in the hash tables - we must
3000 * push a macro-end marker for it on to istk->expansion.
3001 * After that, it will take care of propagating itself (a
3002 * macro-end marker line for a macro which is really a %rep
3003 * block will cause the macro to be re-expanded, complete
3004 * with another macro-end marker to ensure the process
3005 * continues) until the whole expansion is forcibly removed
3006 * from istk->expansion by a %exitrep.
3008 l
= nasm_malloc(sizeof(Line
));
3009 l
->next
= istk
->expansion
;
3010 l
->finishes
= defining
;
3012 istk
->expansion
= l
;
3014 istk
->mstk
= defining
;
3016 lfmt
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
3017 tmp_defining
= defining
;
3018 defining
= defining
->rep_nest
;
3019 free_tlist(origline
);
3020 return DIRECTIVE_FOUND
;
3024 * We must search along istk->expansion until we hit a
3025 * macro-end marker for a macro with no name. Then we set
3026 * its `in_progress' flag to 0.
3028 list_for_each(l
, istk
->expansion
)
3029 if (l
->finishes
&& !l
->finishes
->name
)
3033 l
->finishes
->in_progress
= 1;
3035 nasm_error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
3036 free_tlist(origline
);
3037 return DIRECTIVE_FOUND
;
3043 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
3045 tline
= tline
->next
;
3047 tline
= expand_id(tline
);
3048 if (!tline
|| (tline
->type
!= TOK_ID
&&
3049 (tline
->type
!= TOK_PREPROC_ID
||
3050 tline
->text
[1] != '$'))) {
3051 nasm_error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3053 free_tlist(origline
);
3054 return DIRECTIVE_FOUND
;
3057 ctx
= get_ctx(tline
->text
, &mname
);
3059 param_start
= tline
= tline
->next
;
3062 /* Expand the macro definition now for %xdefine and %ixdefine */
3063 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3064 tline
= expand_smacro(tline
);
3066 if (tok_is_(tline
, "(")) {
3068 * This macro has parameters.
3071 tline
= tline
->next
;
3075 nasm_error(ERR_NONFATAL
, "parameter identifier expected");
3076 free_tlist(origline
);
3077 return DIRECTIVE_FOUND
;
3079 if (tline
->type
!= TOK_ID
) {
3080 nasm_error(ERR_NONFATAL
,
3081 "`%s': parameter identifier expected",
3083 free_tlist(origline
);
3084 return DIRECTIVE_FOUND
;
3086 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3087 tline
= tline
->next
;
3089 if (tok_is_(tline
, ",")) {
3090 tline
= tline
->next
;
3092 if (!tok_is_(tline
, ")")) {
3093 nasm_error(ERR_NONFATAL
,
3094 "`)' expected to terminate macro template");
3095 free_tlist(origline
);
3096 return DIRECTIVE_FOUND
;
3102 tline
= tline
->next
;
3104 if (tok_type_(tline
, TOK_WHITESPACE
))
3105 last
= tline
, tline
= tline
->next
;
3110 if (t
->type
== TOK_ID
) {
3111 list_for_each(tt
, param_start
)
3112 if (tt
->type
>= TOK_SMAC_PARAM
&&
3113 !strcmp(tt
->text
, t
->text
))
3117 t
->next
= macro_start
;
3122 * Good. We now have a macro name, a parameter count, and a
3123 * token list (in reverse order) for an expansion. We ought
3124 * to be OK just to create an SMacro, store it, and let
3125 * free_tlist have the rest of the line (which we have
3126 * carefully re-terminated after chopping off the expansion
3129 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3130 free_tlist(origline
);
3131 return DIRECTIVE_FOUND
;
3134 tline
= tline
->next
;
3136 tline
= expand_id(tline
);
3137 if (!tline
|| (tline
->type
!= TOK_ID
&&
3138 (tline
->type
!= TOK_PREPROC_ID
||
3139 tline
->text
[1] != '$'))) {
3140 nasm_error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3141 free_tlist(origline
);
3142 return DIRECTIVE_FOUND
;
3145 nasm_error(ERR_WARNING
|ERR_PASS1
,
3146 "trailing garbage after macro name ignored");
3149 /* Find the context that symbol belongs to */
3150 ctx
= get_ctx(tline
->text
, &mname
);
3151 undef_smacro(ctx
, mname
);
3152 free_tlist(origline
);
3153 return DIRECTIVE_FOUND
;
3157 casesense
= (i
== PP_DEFSTR
);
3159 tline
= tline
->next
;
3161 tline
= expand_id(tline
);
3162 if (!tline
|| (tline
->type
!= TOK_ID
&&
3163 (tline
->type
!= TOK_PREPROC_ID
||
3164 tline
->text
[1] != '$'))) {
3165 nasm_error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3167 free_tlist(origline
);
3168 return DIRECTIVE_FOUND
;
3171 ctx
= get_ctx(tline
->text
, &mname
);
3173 tline
= expand_smacro(tline
->next
);
3176 while (tok_type_(tline
, TOK_WHITESPACE
))
3177 tline
= delete_Token(tline
);
3179 p
= detoken(tline
, false);
3180 macro_start
= nasm_malloc(sizeof(*macro_start
));
3181 macro_start
->next
= NULL
;
3182 macro_start
->text
= nasm_quote(p
, strlen(p
));
3183 macro_start
->type
= TOK_STRING
;
3184 macro_start
->a
.mac
= NULL
;
3188 * We now have a macro name, an implicit parameter count of
3189 * zero, and a string token to use as an expansion. Create
3190 * and store an SMacro.
3192 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3193 free_tlist(origline
);
3194 return DIRECTIVE_FOUND
;
3198 casesense
= (i
== PP_DEFTOK
);
3200 tline
= tline
->next
;
3202 tline
= expand_id(tline
);
3203 if (!tline
|| (tline
->type
!= TOK_ID
&&
3204 (tline
->type
!= TOK_PREPROC_ID
||
3205 tline
->text
[1] != '$'))) {
3206 nasm_error(ERR_NONFATAL
,
3207 "`%s' expects a macro identifier as first parameter",
3209 free_tlist(origline
);
3210 return DIRECTIVE_FOUND
;
3212 ctx
= get_ctx(tline
->text
, &mname
);
3214 tline
= expand_smacro(tline
->next
);
3218 while (tok_type_(t
, TOK_WHITESPACE
))
3220 /* t should now point to the string */
3221 if (!tok_type_(t
, TOK_STRING
)) {
3222 nasm_error(ERR_NONFATAL
,
3223 "`%s` requires string as second parameter",
3226 free_tlist(origline
);
3227 return DIRECTIVE_FOUND
;
3231 * Convert the string to a token stream. Note that smacros
3232 * are stored with the token stream reversed, so we have to
3233 * reverse the output of tokenize().
3235 nasm_unquote_cstr(t
->text
, i
);
3236 macro_start
= reverse_tokens(tokenize(t
->text
));
3239 * We now have a macro name, an implicit parameter count of
3240 * zero, and a numeric token to use as an expansion. Create
3241 * and store an SMacro.
3243 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3245 free_tlist(origline
);
3246 return DIRECTIVE_FOUND
;
3251 StrList
*xsl
= NULL
;
3252 StrList
**xst
= &xsl
;
3256 tline
= tline
->next
;
3258 tline
= expand_id(tline
);
3259 if (!tline
|| (tline
->type
!= TOK_ID
&&
3260 (tline
->type
!= TOK_PREPROC_ID
||
3261 tline
->text
[1] != '$'))) {
3262 nasm_error(ERR_NONFATAL
,
3263 "`%%pathsearch' expects a macro identifier as first parameter");
3264 free_tlist(origline
);
3265 return DIRECTIVE_FOUND
;
3267 ctx
= get_ctx(tline
->text
, &mname
);
3269 tline
= expand_smacro(tline
->next
);
3273 while (tok_type_(t
, TOK_WHITESPACE
))
3276 if (!t
|| (t
->type
!= TOK_STRING
&&
3277 t
->type
!= TOK_INTERNAL_STRING
)) {
3278 nasm_error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3280 free_tlist(origline
);
3281 return DIRECTIVE_FOUND
; /* but we did _something_ */
3284 nasm_error(ERR_WARNING
|ERR_PASS1
,
3285 "trailing garbage after `%%pathsearch' ignored");
3287 if (t
->type
!= TOK_INTERNAL_STRING
)
3288 nasm_unquote(p
, NULL
);
3290 fp
= inc_fopen(p
, &xsl
, &xst
, NULL
, true, "r");
3293 fclose(fp
); /* Don't actually care about the file */
3295 macro_start
= nasm_malloc(sizeof(*macro_start
));
3296 macro_start
->next
= NULL
;
3297 macro_start
->text
= nasm_quote(p
, strlen(p
));
3298 macro_start
->type
= TOK_STRING
;
3299 macro_start
->a
.mac
= NULL
;
3304 * We now have a macro name, an implicit parameter count of
3305 * zero, and a string token to use as an expansion. Create
3306 * and store an SMacro.
3308 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3310 free_tlist(origline
);
3311 return DIRECTIVE_FOUND
;
3317 tline
= tline
->next
;
3319 tline
= expand_id(tline
);
3320 if (!tline
|| (tline
->type
!= TOK_ID
&&
3321 (tline
->type
!= TOK_PREPROC_ID
||
3322 tline
->text
[1] != '$'))) {
3323 nasm_error(ERR_NONFATAL
,
3324 "`%%strlen' expects a macro identifier as first parameter");
3325 free_tlist(origline
);
3326 return DIRECTIVE_FOUND
;
3328 ctx
= get_ctx(tline
->text
, &mname
);
3330 tline
= expand_smacro(tline
->next
);
3334 while (tok_type_(t
, TOK_WHITESPACE
))
3336 /* t should now point to the string */
3337 if (!tok_type_(t
, TOK_STRING
)) {
3338 nasm_error(ERR_NONFATAL
,
3339 "`%%strlen` requires string as second parameter");
3341 free_tlist(origline
);
3342 return DIRECTIVE_FOUND
;
3345 macro_start
= nasm_malloc(sizeof(*macro_start
));
3346 macro_start
->next
= NULL
;
3347 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3348 macro_start
->a
.mac
= NULL
;
3351 * We now have a macro name, an implicit parameter count of
3352 * zero, and a numeric token to use as an expansion. Create
3353 * and store an SMacro.
3355 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3357 free_tlist(origline
);
3358 return DIRECTIVE_FOUND
;
3363 tline
= tline
->next
;
3365 tline
= expand_id(tline
);
3366 if (!tline
|| (tline
->type
!= TOK_ID
&&
3367 (tline
->type
!= TOK_PREPROC_ID
||
3368 tline
->text
[1] != '$'))) {
3369 nasm_error(ERR_NONFATAL
,
3370 "`%%strcat' expects a macro identifier as first parameter");
3371 free_tlist(origline
);
3372 return DIRECTIVE_FOUND
;
3374 ctx
= get_ctx(tline
->text
, &mname
);
3376 tline
= expand_smacro(tline
->next
);
3380 list_for_each(t
, tline
) {
3382 case TOK_WHITESPACE
:
3385 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3388 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3390 /* else fall through */
3392 nasm_error(ERR_NONFATAL
,
3393 "non-string passed to `%%strcat' (%d)", t
->type
);
3395 free_tlist(origline
);
3396 return DIRECTIVE_FOUND
;
3400 p
= pp
= nasm_malloc(len
);
3401 list_for_each(t
, tline
) {
3402 if (t
->type
== TOK_STRING
) {
3403 memcpy(p
, t
->text
, t
->a
.len
);
3409 * We now have a macro name, an implicit parameter count of
3410 * zero, and a numeric token to use as an expansion. Create
3411 * and store an SMacro.
3413 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3414 macro_start
->text
= nasm_quote(pp
, len
);
3416 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3418 free_tlist(origline
);
3419 return DIRECTIVE_FOUND
;
3423 int64_t start
, count
;
3428 tline
= tline
->next
;
3430 tline
= expand_id(tline
);
3431 if (!tline
|| (tline
->type
!= TOK_ID
&&
3432 (tline
->type
!= TOK_PREPROC_ID
||
3433 tline
->text
[1] != '$'))) {
3434 nasm_error(ERR_NONFATAL
,
3435 "`%%substr' expects a macro identifier as first parameter");
3436 free_tlist(origline
);
3437 return DIRECTIVE_FOUND
;
3439 ctx
= get_ctx(tline
->text
, &mname
);
3441 tline
= expand_smacro(tline
->next
);
3444 if (tline
) /* skip expanded id */
3446 while (tok_type_(t
, TOK_WHITESPACE
))
3449 /* t should now point to the string */
3450 if (!tok_type_(t
, TOK_STRING
)) {
3451 nasm_error(ERR_NONFATAL
,
3452 "`%%substr` requires string as second parameter");
3454 free_tlist(origline
);
3455 return DIRECTIVE_FOUND
;
3460 tokval
.t_type
= TOKEN_INVALID
;
3461 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3464 free_tlist(origline
);
3465 return DIRECTIVE_FOUND
;
3466 } else if (!is_simple(evalresult
)) {
3467 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3469 free_tlist(origline
);
3470 return DIRECTIVE_FOUND
;
3472 start
= evalresult
->value
- 1;
3474 while (tok_type_(tt
, TOK_WHITESPACE
))
3477 count
= 1; /* Backwards compatibility: one character */
3479 tokval
.t_type
= TOKEN_INVALID
;
3480 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3483 free_tlist(origline
);
3484 return DIRECTIVE_FOUND
;
3485 } else if (!is_simple(evalresult
)) {
3486 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3488 free_tlist(origline
);
3489 return DIRECTIVE_FOUND
;
3491 count
= evalresult
->value
;
3494 len
= nasm_unquote(t
->text
, NULL
);
3496 /* make start and count being in range */
3500 count
= len
+ count
+ 1 - start
;
3501 if (start
+ count
> (int64_t)len
)
3502 count
= len
- start
;
3503 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3504 start
= -1, count
= 0; /* empty string */
3506 macro_start
= nasm_malloc(sizeof(*macro_start
));
3507 macro_start
->next
= NULL
;
3508 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3509 macro_start
->type
= TOK_STRING
;
3510 macro_start
->a
.mac
= NULL
;
3513 * We now have a macro name, an implicit parameter count of
3514 * zero, and a numeric token to use as an expansion. Create
3515 * and store an SMacro.
3517 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3519 free_tlist(origline
);
3520 return DIRECTIVE_FOUND
;
3525 casesense
= (i
== PP_ASSIGN
);
3527 tline
= tline
->next
;
3529 tline
= expand_id(tline
);
3530 if (!tline
|| (tline
->type
!= TOK_ID
&&
3531 (tline
->type
!= TOK_PREPROC_ID
||
3532 tline
->text
[1] != '$'))) {
3533 nasm_error(ERR_NONFATAL
,
3534 "`%%%sassign' expects a macro identifier",
3535 (i
== PP_IASSIGN
? "i" : ""));
3536 free_tlist(origline
);
3537 return DIRECTIVE_FOUND
;
3539 ctx
= get_ctx(tline
->text
, &mname
);
3541 tline
= expand_smacro(tline
->next
);
3546 tokval
.t_type
= TOKEN_INVALID
;
3547 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3550 free_tlist(origline
);
3551 return DIRECTIVE_FOUND
;
3555 nasm_error(ERR_WARNING
|ERR_PASS1
,
3556 "trailing garbage after expression ignored");
3558 if (!is_simple(evalresult
)) {
3559 nasm_error(ERR_NONFATAL
,
3560 "non-constant value given to `%%%sassign'",
3561 (i
== PP_IASSIGN
? "i" : ""));
3562 free_tlist(origline
);
3563 return DIRECTIVE_FOUND
;
3566 macro_start
= nasm_malloc(sizeof(*macro_start
));
3567 macro_start
->next
= NULL
;
3568 make_tok_num(macro_start
, reloc_value(evalresult
));
3569 macro_start
->a
.mac
= NULL
;
3572 * We now have a macro name, an implicit parameter count of
3573 * zero, and a numeric token to use as an expansion. Create
3574 * and store an SMacro.
3576 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3577 free_tlist(origline
);
3578 return DIRECTIVE_FOUND
;
3582 * Syntax is `%line nnn[+mmm] [filename]'
3584 tline
= tline
->next
;
3586 if (!tok_type_(tline
, TOK_NUMBER
)) {
3587 nasm_error(ERR_NONFATAL
, "`%%line' expects line number");
3588 free_tlist(origline
);
3589 return DIRECTIVE_FOUND
;
3591 k
= readnum(tline
->text
, &err
);
3593 tline
= tline
->next
;
3594 if (tok_is_(tline
, "+")) {
3595 tline
= tline
->next
;
3596 if (!tok_type_(tline
, TOK_NUMBER
)) {
3597 nasm_error(ERR_NONFATAL
, "`%%line' expects line increment");
3598 free_tlist(origline
);
3599 return DIRECTIVE_FOUND
;
3601 m
= readnum(tline
->text
, &err
);
3602 tline
= tline
->next
;
3608 char *fname
= detoken(tline
, false);
3609 src_set_fname(fname
);
3612 free_tlist(origline
);
3613 return DIRECTIVE_FOUND
;
3616 nasm_error(ERR_FATAL
,
3617 "preprocessor directive `%s' not yet implemented",
3619 return DIRECTIVE_FOUND
;
3624 * Ensure that a macro parameter contains a condition code and
3625 * nothing else. Return the condition code index if so, or -1
3628 static int find_cc(Token
* t
)
3633 return -1; /* Probably a %+ without a space */
3636 if (t
->type
!= TOK_ID
)
3640 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3643 return bsii(t
->text
, (const char **)conditions
, ARRAY_SIZE(conditions
));
3647 * This routines walks over tokens strem and hadnles tokens
3648 * pasting, if @handle_explicit passed then explicit pasting
3649 * term is handled, otherwise -- implicit pastings only.
3651 static bool paste_tokens(Token
**head
, const struct tokseq_match
*m
,
3652 size_t mnum
, bool handle_explicit
)
3654 Token
*tok
, *next
, **prev_next
, **prev_nonspace
;
3655 bool pasted
= false;
3660 * The last token before pasting. We need it
3661 * to be able to connect new handled tokens.
3662 * In other words if there were a tokens stream
3666 * and we've joined tokens B and C, the resulting
3674 if (!tok_type_(tok
, TOK_WHITESPACE
) && !tok_type_(tok
, TOK_PASTE
))
3675 prev_nonspace
= head
;
3677 prev_nonspace
= NULL
;
3679 while (tok
&& (next
= tok
->next
)) {
3681 switch (tok
->type
) {
3682 case TOK_WHITESPACE
:
3683 /* Zap redundant whitespaces */
3684 while (tok_type_(next
, TOK_WHITESPACE
))
3685 next
= delete_Token(next
);
3690 /* Explicit pasting */
3691 if (!handle_explicit
)
3693 next
= delete_Token(tok
);
3695 while (tok_type_(next
, TOK_WHITESPACE
))
3696 next
= delete_Token(next
);
3701 /* Left pasting token is start of line */
3703 nasm_error(ERR_FATAL
, "No lvalue found on pasting");
3706 * No ending token, this might happen in two
3709 * 1) There indeed no right token at all
3710 * 2) There is a bare "%define ID" statement,
3711 * and @ID does expand to whitespace.
3713 * So technically we need to do a grammar analysis
3714 * in another stage of parsing, but for now lets don't
3715 * change the behaviour people used to. Simply allow
3716 * whitespace after paste token.
3720 * Zap ending space tokens and that's all.
3722 tok
= (*prev_nonspace
)->next
;
3723 while (tok_type_(tok
, TOK_WHITESPACE
))
3724 tok
= delete_Token(tok
);
3725 tok
= *prev_nonspace
;
3730 tok
= *prev_nonspace
;
3731 while (tok_type_(tok
, TOK_WHITESPACE
))
3732 tok
= delete_Token(tok
);
3733 len
= strlen(tok
->text
);
3734 len
+= strlen(next
->text
);
3736 p
= buf
= nasm_malloc(len
+ 1);
3737 strcpy(p
, tok
->text
);
3738 p
= strchr(p
, '\0');
3739 strcpy(p
, next
->text
);
3743 tok
= tokenize(buf
);
3746 *prev_nonspace
= tok
;
3747 while (tok
&& tok
->next
)
3750 tok
->next
= delete_Token(next
);
3752 /* Restart from pasted tokens head */
3753 tok
= *prev_nonspace
;
3757 /* implicit pasting */
3758 for (i
= 0; i
< mnum
; i
++) {
3759 if (!(PP_CONCAT_MATCH(tok
, m
[i
].mask_head
)))
3763 while (next
&& PP_CONCAT_MATCH(next
, m
[i
].mask_tail
)) {
3764 len
+= strlen(next
->text
);
3772 len
+= strlen(tok
->text
);
3773 p
= buf
= nasm_malloc(len
+ 1);
3775 while (tok
!= next
) {
3776 strcpy(p
, tok
->text
);
3777 p
= strchr(p
, '\0');
3778 tok
= delete_Token(tok
);
3781 tok
= tokenize(buf
);
3790 * Connect pasted into original stream,
3791 * ie A -> new-tokens -> B
3793 while (tok
&& tok
->next
)
3800 /* Restart from pasted tokens head */
3801 tok
= prev_next
? *prev_next
: *head
;
3807 prev_next
= &tok
->next
;
3810 !tok_type_(tok
->next
, TOK_WHITESPACE
) &&
3811 !tok_type_(tok
->next
, TOK_PASTE
))
3812 prev_nonspace
= prev_next
;
3821 * expands to a list of tokens from %{x:y}
3823 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3825 Token
*t
= tline
, **tt
, *tm
, *head
;
3829 pos
= strchr(tline
->text
, ':');
3832 lst
= atoi(pos
+ 1);
3833 fst
= atoi(tline
->text
+ 1);
3836 * only macros params are accounted so
3837 * if someone passes %0 -- we reject such
3840 if (lst
== 0 || fst
== 0)
3843 /* the values should be sane */
3844 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3845 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3848 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3849 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3851 /* counted from zero */
3855 * It will be at least one token. Note we
3856 * need to scan params until separator, otherwise
3857 * only first token will be passed.
3859 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3860 head
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3861 tt
= &head
->next
, tm
= tm
->next
;
3862 while (tok_isnt_(tm
, ",")) {
3863 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3864 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3868 for (i
= fst
+ 1; i
<= lst
; i
++) {
3869 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3870 *tt
= t
, tt
= &t
->next
;
3871 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3872 tm
= mac
->params
[j
];
3873 while (tok_isnt_(tm
, ",")) {
3874 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3875 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3879 for (i
= fst
- 1; i
>= lst
; i
--) {
3880 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3881 *tt
= t
, tt
= &t
->next
;
3882 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3883 tm
= mac
->params
[j
];
3884 while (tok_isnt_(tm
, ",")) {
3885 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3886 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3895 nasm_error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3901 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3902 * %-n) and MMacro-local identifiers (%%foo) as well as
3903 * macro indirection (%[...]) and range (%{..:..}).
3905 static Token
*expand_mmac_params(Token
* tline
)
3907 Token
*t
, *tt
, **tail
, *thead
;
3908 bool changed
= false;
3915 if (tline
->type
== TOK_PREPROC_ID
&&
3916 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3917 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3918 tline
->text
[1] == '%')) {
3920 int type
= 0, cc
; /* type = 0 to placate optimisers */
3927 tline
= tline
->next
;
3930 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3931 mac
= mac
->next_active
;
3933 nasm_error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3935 pos
= strchr(t
->text
, ':');
3937 switch (t
->text
[1]) {
3939 * We have to make a substitution of one of the
3940 * forms %1, %-1, %+1, %%foo, %0.
3944 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3945 text
= nasm_strdup(tmpbuf
);
3949 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3951 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3954 n
= atoi(t
->text
+ 2) - 1;
3955 if (n
>= mac
->nparam
)
3958 if (mac
->nparam
> 1)
3959 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3960 tt
= mac
->params
[n
];
3964 nasm_error(ERR_NONFATAL
,
3965 "macro parameter %d is not a condition code",
3970 if (inverse_ccs
[cc
] == -1) {
3971 nasm_error(ERR_NONFATAL
,
3972 "condition code `%s' is not invertible",
3976 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3980 n
= atoi(t
->text
+ 2) - 1;
3981 if (n
>= mac
->nparam
)
3984 if (mac
->nparam
> 1)
3985 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3986 tt
= mac
->params
[n
];
3990 nasm_error(ERR_NONFATAL
,
3991 "macro parameter %d is not a condition code",
3996 text
= nasm_strdup(conditions
[cc
]);
4000 n
= atoi(t
->text
+ 1) - 1;
4001 if (n
>= mac
->nparam
)
4004 if (mac
->nparam
> 1)
4005 n
= (n
+ mac
->rotate
) % mac
->nparam
;
4006 tt
= mac
->params
[n
];
4009 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
4010 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
4011 tail
= &(*tail
)->next
;
4015 text
= NULL
; /* we've done it here */
4020 * seems we have a parameters range here
4022 Token
*head
, **last
;
4023 head
= expand_mmac_params_range(mac
, t
, &last
);
4044 } else if (tline
->type
== TOK_INDIRECT
) {
4046 tline
= tline
->next
;
4047 tt
= tokenize(t
->text
);
4048 tt
= expand_mmac_params(tt
);
4049 tt
= expand_smacro(tt
);
4052 tt
->a
.mac
= NULL
; /* Necessary? */
4060 tline
= tline
->next
;
4068 const struct tokseq_match t
[] = {
4070 PP_CONCAT_MASK(TOK_ID
) |
4071 PP_CONCAT_MASK(TOK_FLOAT
), /* head */
4072 PP_CONCAT_MASK(TOK_ID
) |
4073 PP_CONCAT_MASK(TOK_NUMBER
) |
4074 PP_CONCAT_MASK(TOK_FLOAT
) |
4075 PP_CONCAT_MASK(TOK_OTHER
) /* tail */
4078 PP_CONCAT_MASK(TOK_NUMBER
), /* head */
4079 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4082 paste_tokens(&thead
, t
, ARRAY_SIZE(t
), false);
4089 * Expand all single-line macro calls made in the given line.
4090 * Return the expanded version of the line. The original is deemed
4091 * to be destroyed in the process. (In reality we'll just move
4092 * Tokens from input to output a lot of the time, rather than
4093 * actually bothering to destroy and replicate.)
4096 static Token
*expand_smacro(Token
* tline
)
4098 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4099 SMacro
*head
= NULL
, *m
;
4102 unsigned int nparam
, sparam
;
4104 Token
*org_tline
= tline
;
4107 int deadman
= DEADMAN_LIMIT
;
4111 * Trick: we should avoid changing the start token pointer since it can
4112 * be contained in "next" field of other token. Because of this
4113 * we allocate a copy of first token and work with it; at the end of
4114 * routine we copy it back
4117 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4118 org_tline
->text
, 0);
4119 tline
->a
.mac
= org_tline
->a
.mac
;
4120 nasm_free(org_tline
->text
);
4121 org_tline
->text
= NULL
;
4124 expanded
= true; /* Always expand %+ at least once */
4130 while (tline
) { /* main token loop */
4132 nasm_error(ERR_NONFATAL
, "interminable macro recursion");
4136 if ((mname
= tline
->text
)) {
4137 /* if this token is a local macro, look in local context */
4138 if (tline
->type
== TOK_ID
) {
4139 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4140 } else if (tline
->type
== TOK_PREPROC_ID
) {
4141 ctx
= get_ctx(mname
, &mname
);
4142 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4147 * We've hit an identifier. As in is_mmacro below, we first
4148 * check whether the identifier is a single-line macro at
4149 * all, then think about checking for parameters if
4152 list_for_each(m
, head
)
4153 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4159 if (m
->nparam
== 0) {
4161 * Simple case: the macro is parameterless. Discard the
4162 * one token that the macro call took, and push the
4163 * expansion back on the to-do stack.
4165 if (!m
->expansion
) {
4166 if (!strcmp("__FILE__", m
->name
)) {
4167 const char *file
= src_get_fname();
4168 /* nasm_free(tline->text); here? */
4169 tline
->text
= nasm_quote(file
, strlen(file
));
4170 tline
->type
= TOK_STRING
;
4173 if (!strcmp("__LINE__", m
->name
)) {
4174 nasm_free(tline
->text
);
4175 make_tok_num(tline
, src_get_linnum());
4178 if (!strcmp("__BITS__", m
->name
)) {
4179 nasm_free(tline
->text
);
4180 make_tok_num(tline
, globalbits
);
4183 tline
= delete_Token(tline
);
4188 * Complicated case: at least one macro with this name
4189 * exists and takes parameters. We must find the
4190 * parameters in the call, count them, find the SMacro
4191 * that corresponds to that form of the macro call, and
4192 * substitute for the parameters when we expand. What a
4195 /*tline = tline->next;
4196 skip_white_(tline); */
4199 while (tok_type_(t
, TOK_SMAC_END
)) {
4200 t
->a
.mac
->in_progress
= false;
4202 t
= tline
->next
= delete_Token(t
);
4205 } while (tok_type_(tline
, TOK_WHITESPACE
));
4206 if (!tok_is_(tline
, "(")) {
4208 * This macro wasn't called with parameters: ignore
4209 * the call. (Behaviour borrowed from gnu cpp.)
4218 sparam
= PARAM_DELTA
;
4219 params
= nasm_malloc(sparam
* sizeof(Token
*));
4220 params
[0] = tline
->next
;
4221 paramsize
= nasm_malloc(sparam
* sizeof(int));
4223 while (true) { /* parameter loop */
4225 * For some unusual expansions
4226 * which concatenates function call
4229 while (tok_type_(t
, TOK_SMAC_END
)) {
4230 t
->a
.mac
->in_progress
= false;
4232 t
= tline
->next
= delete_Token(t
);
4237 nasm_error(ERR_NONFATAL
,
4238 "macro call expects terminating `)'");
4241 if (tline
->type
== TOK_WHITESPACE
4243 if (paramsize
[nparam
])
4246 params
[nparam
] = tline
->next
;
4247 continue; /* parameter loop */
4249 if (tline
->type
== TOK_OTHER
4250 && tline
->text
[1] == 0) {
4251 char ch
= tline
->text
[0];
4252 if (ch
== ',' && !paren
&& brackets
<= 0) {
4253 if (++nparam
>= sparam
) {
4254 sparam
+= PARAM_DELTA
;
4255 params
= nasm_realloc(params
,
4256 sparam
* sizeof(Token
*));
4257 paramsize
= nasm_realloc(paramsize
,
4258 sparam
* sizeof(int));
4260 params
[nparam
] = tline
->next
;
4261 paramsize
[nparam
] = 0;
4263 continue; /* parameter loop */
4266 (brackets
> 0 || (brackets
== 0 &&
4267 !paramsize
[nparam
])))
4269 if (!(brackets
++)) {
4270 params
[nparam
] = tline
->next
;
4271 continue; /* parameter loop */
4274 if (ch
== '}' && brackets
> 0)
4275 if (--brackets
== 0) {
4277 continue; /* parameter loop */
4279 if (ch
== '(' && !brackets
)
4281 if (ch
== ')' && brackets
<= 0)
4287 nasm_error(ERR_NONFATAL
, "braces do not "
4288 "enclose all of macro parameter");
4290 paramsize
[nparam
] += white
+ 1;
4292 } /* parameter loop */
4294 while (m
&& (m
->nparam
!= nparam
||
4295 mstrcmp(m
->name
, mname
,
4299 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4300 "macro `%s' exists, "
4301 "but not taking %d parameters",
4302 mstart
->text
, nparam
);
4305 if (m
&& m
->in_progress
)
4307 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4309 * Design question: should we handle !tline, which
4310 * indicates missing ')' here, or expand those
4311 * macros anyway, which requires the (t) test a few
4315 nasm_free(paramsize
);
4319 * Expand the macro: we are placed on the last token of the
4320 * call, so that we can easily split the call from the
4321 * following tokens. We also start by pushing an SMAC_END
4322 * token for the cycle removal.
4329 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4331 m
->in_progress
= true;
4333 list_for_each(t
, m
->expansion
) {
4334 if (t
->type
>= TOK_SMAC_PARAM
) {
4335 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4339 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4340 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4342 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4348 } else if (t
->type
== TOK_PREPROC_Q
) {
4349 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4351 } else if (t
->type
== TOK_PREPROC_QQ
) {
4352 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4355 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4361 * Having done that, get rid of the macro call, and clean
4362 * up the parameters.
4365 nasm_free(paramsize
);
4368 continue; /* main token loop */
4373 if (tline
->type
== TOK_SMAC_END
) {
4374 tline
->a
.mac
->in_progress
= false;
4375 tline
= delete_Token(tline
);
4378 tline
= tline
->next
;
4386 * Now scan the entire line and look for successive TOK_IDs that resulted
4387 * after expansion (they can't be produced by tokenize()). The successive
4388 * TOK_IDs should be concatenated.
4389 * Also we look for %+ tokens and concatenate the tokens before and after
4390 * them (without white spaces in between).
4393 const struct tokseq_match t
[] = {
4395 PP_CONCAT_MASK(TOK_ID
) |
4396 PP_CONCAT_MASK(TOK_PREPROC_ID
), /* head */
4397 PP_CONCAT_MASK(TOK_ID
) |
4398 PP_CONCAT_MASK(TOK_PREPROC_ID
) |
4399 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4402 if (paste_tokens(&thead
, t
, ARRAY_SIZE(t
), true)) {
4404 * If we concatenated something, *and* we had previously expanded
4405 * an actual macro, scan the lines again for macros...
4416 *org_tline
= *thead
;
4417 /* since we just gave text to org_line, don't free it */
4419 delete_Token(thead
);
4421 /* the expression expanded to empty line;
4422 we can't return NULL for some reasons
4423 we just set the line to a single WHITESPACE token. */
4424 memset(org_tline
, 0, sizeof(*org_tline
));
4425 org_tline
->text
= NULL
;
4426 org_tline
->type
= TOK_WHITESPACE
;
4435 * Similar to expand_smacro but used exclusively with macro identifiers
4436 * right before they are fetched in. The reason is that there can be
4437 * identifiers consisting of several subparts. We consider that if there
4438 * are more than one element forming the name, user wants a expansion,
4439 * otherwise it will be left as-is. Example:
4443 * the identifier %$abc will be left as-is so that the handler for %define
4444 * will suck it and define the corresponding value. Other case:
4446 * %define _%$abc cde
4448 * In this case user wants name to be expanded *before* %define starts
4449 * working, so we'll expand %$abc into something (if it has a value;
4450 * otherwise it will be left as-is) then concatenate all successive
4453 static Token
*expand_id(Token
* tline
)
4455 Token
*cur
, *oldnext
= NULL
;
4457 if (!tline
|| !tline
->next
)
4462 (cur
->next
->type
== TOK_ID
||
4463 cur
->next
->type
== TOK_PREPROC_ID
4464 || cur
->next
->type
== TOK_NUMBER
))
4467 /* If identifier consists of just one token, don't expand */
4472 oldnext
= cur
->next
; /* Detach the tail past identifier */
4473 cur
->next
= NULL
; /* so that expand_smacro stops here */
4476 tline
= expand_smacro(tline
);
4479 /* expand_smacro possibly changhed tline; re-scan for EOL */
4481 while (cur
&& cur
->next
)
4484 cur
->next
= oldnext
;
4491 * Determine whether the given line constitutes a multi-line macro
4492 * call, and return the MMacro structure called if so. Doesn't have
4493 * to check for an initial label - that's taken care of in
4494 * expand_mmacro - but must check numbers of parameters. Guaranteed
4495 * to be called with tline->type == TOK_ID, so the putative macro
4496 * name is easy to find.
4498 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4504 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4507 * Efficiency: first we see if any macro exists with the given
4508 * name. If not, we can return NULL immediately. _Then_ we
4509 * count the parameters, and then we look further along the
4510 * list if necessary to find the proper MMacro.
4512 list_for_each(m
, head
)
4513 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4519 * OK, we have a potential macro. Count and demarcate the
4522 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4525 * So we know how many parameters we've got. Find the MMacro
4526 * structure that handles this number.
4529 if (m
->nparam_min
<= nparam
4530 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4532 * This one is right. Just check if cycle removal
4533 * prohibits us using it before we actually celebrate...
4535 if (m
->in_progress
> m
->max_depth
) {
4536 if (m
->max_depth
> 0) {
4537 nasm_error(ERR_WARNING
,
4538 "reached maximum recursion depth of %i",
4545 * It's right, and we can use it. Add its default
4546 * parameters to the end of our list if necessary.
4548 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4550 nasm_realloc(params
,
4551 ((m
->nparam_min
+ m
->ndefs
+
4552 1) * sizeof(*params
)));
4553 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4554 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4559 * If we've gone over the maximum parameter count (and
4560 * we're in Plus mode), ignore parameters beyond
4563 if (m
->plus
&& nparam
> m
->nparam_max
)
4564 nparam
= m
->nparam_max
;
4566 * Then terminate the parameter list, and leave.
4568 if (!params
) { /* need this special case */
4569 params
= nasm_malloc(sizeof(*params
));
4572 params
[nparam
] = NULL
;
4573 *params_array
= params
;
4577 * This one wasn't right: look for the next one with the
4580 list_for_each(m
, m
->next
)
4581 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4586 * After all that, we didn't find one with the right number of
4587 * parameters. Issue a warning, and fail to expand the macro.
4589 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4590 "macro `%s' exists, but not taking %d parameters",
4591 tline
->text
, nparam
);
4598 * Save MMacro invocation specific fields in
4599 * preparation for a recursive macro expansion
4601 static void push_mmacro(MMacro
*m
)
4603 MMacroInvocation
*i
;
4605 i
= nasm_malloc(sizeof(MMacroInvocation
));
4607 i
->params
= m
->params
;
4608 i
->iline
= m
->iline
;
4609 i
->nparam
= m
->nparam
;
4610 i
->rotate
= m
->rotate
;
4611 i
->paramlen
= m
->paramlen
;
4612 i
->unique
= m
->unique
;
4613 i
->condcnt
= m
->condcnt
;
4619 * Restore MMacro invocation specific fields that were
4620 * saved during a previous recursive macro expansion
4622 static void pop_mmacro(MMacro
*m
)
4624 MMacroInvocation
*i
;
4629 m
->params
= i
->params
;
4630 m
->iline
= i
->iline
;
4631 m
->nparam
= i
->nparam
;
4632 m
->rotate
= i
->rotate
;
4633 m
->paramlen
= i
->paramlen
;
4634 m
->unique
= i
->unique
;
4635 m
->condcnt
= i
->condcnt
;
4642 * Expand the multi-line macro call made by the given line, if
4643 * there is one to be expanded. If there is, push the expansion on
4644 * istk->expansion and return 1. Otherwise return 0.
4646 static int expand_mmacro(Token
* tline
)
4648 Token
*startline
= tline
;
4649 Token
*label
= NULL
;
4650 int dont_prepend
= 0;
4651 Token
**params
, *t
, *tt
;
4654 int i
, nparam
, *paramlen
;
4659 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4660 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4662 m
= is_mmacro(t
, ¶ms
);
4668 * We have an id which isn't a macro call. We'll assume
4669 * it might be a label; we'll also check to see if a
4670 * colon follows it. Then, if there's another id after
4671 * that lot, we'll check it again for macro-hood.
4675 if (tok_type_(t
, TOK_WHITESPACE
))
4676 last
= t
, t
= t
->next
;
4677 if (tok_is_(t
, ":")) {
4679 last
= t
, t
= t
->next
;
4680 if (tok_type_(t
, TOK_WHITESPACE
))
4681 last
= t
, t
= t
->next
;
4683 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4691 * Fix up the parameters: this involves stripping leading and
4692 * trailing whitespace, then stripping braces if they are
4695 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4696 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4698 for (i
= 0; params
[i
]; i
++) {
4700 int comma
= (!m
->plus
|| i
< nparam
- 1);
4704 if (tok_is_(t
, "{"))
4705 t
= t
->next
, brace
++, comma
= false;
4709 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4710 break; /* ... because we have hit a comma */
4711 if (comma
&& t
->type
== TOK_WHITESPACE
4712 && tok_is_(t
->next
, ","))
4713 break; /* ... or a space then a comma */
4714 if (brace
&& t
->type
== TOK_OTHER
) {
4715 if (t
->text
[0] == '{')
4716 brace
++; /* ... or a nested opening brace */
4717 else if (t
->text
[0] == '}')
4719 break; /* ... or a brace */
4725 nasm_error(ERR_NONFATAL
, "macro params should be enclosed in braces");
4729 * OK, we have a MMacro structure together with a set of
4730 * parameters. We must now go through the expansion and push
4731 * copies of each Line on to istk->expansion. Substitution of
4732 * parameter tokens and macro-local tokens doesn't get done
4733 * until the single-line macro substitution process; this is
4734 * because delaying them allows us to change the semantics
4735 * later through %rotate.
4737 * First, push an end marker on to istk->expansion, mark this
4738 * macro as in progress, and set up its invocation-specific
4741 ll
= nasm_malloc(sizeof(Line
));
4742 ll
->next
= istk
->expansion
;
4745 istk
->expansion
= ll
;
4748 * Save the previous MMacro expansion in the case of
4751 if (m
->max_depth
&& m
->in_progress
)
4759 m
->paramlen
= paramlen
;
4760 m
->unique
= unique
++;
4764 m
->next_active
= istk
->mstk
;
4767 list_for_each(l
, m
->expansion
) {
4770 ll
= nasm_malloc(sizeof(Line
));
4771 ll
->finishes
= NULL
;
4772 ll
->next
= istk
->expansion
;
4773 istk
->expansion
= ll
;
4776 list_for_each(t
, l
->first
) {
4780 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4782 case TOK_PREPROC_QQ
:
4783 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4785 case TOK_PREPROC_ID
:
4786 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4794 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4803 * If we had a label, push it on as the first line of
4804 * the macro expansion.
4807 if (dont_prepend
< 0)
4808 free_tlist(startline
);
4810 ll
= nasm_malloc(sizeof(Line
));
4811 ll
->finishes
= NULL
;
4812 ll
->next
= istk
->expansion
;
4813 istk
->expansion
= ll
;
4814 ll
->first
= startline
;
4815 if (!dont_prepend
) {
4817 label
= label
->next
;
4818 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4823 lfmt
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4829 * This function adds macro names to error messages, and suppresses
4830 * them if necessary.
4832 static void pp_verror(int severity
, const char *fmt
, va_list arg
)
4835 MMacro
*mmac
= NULL
;
4839 * If we're in a dead branch of IF or something like it, ignore the error.
4840 * However, because %else etc are evaluated in the state context
4841 * of the previous branch, errors might get lost:
4842 * %if 0 ... %else trailing garbage ... %endif
4843 * So %else etc should set the ERR_PP_PRECOND flag.
4845 if ((severity
& ERR_MASK
) < ERR_FATAL
&&
4846 istk
&& istk
->conds
&&
4847 ((severity
& ERR_PP_PRECOND
) ?
4848 istk
->conds
->state
== COND_NEVER
:
4849 !emitting(istk
->conds
->state
)))
4852 /* get %macro name */
4853 if (!(severity
& ERR_NOFILE
) && istk
&& istk
->mstk
) {
4855 /* but %rep blocks should be skipped */
4856 while (mmac
&& !mmac
->name
)
4857 mmac
= mmac
->next_active
, delta
++;
4861 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4863 nasm_set_verror(real_verror
);
4864 nasm_error(severity
, "(%s:%d) %s",
4865 mmac
->name
, mmac
->lineno
- delta
, buff
);
4866 nasm_set_verror(pp_verror
);
4868 real_verror(severity
, fmt
, arg
);
4873 pp_reset(char *file
, int apass
, StrList
**deplist
)
4878 istk
= nasm_malloc(sizeof(Include
));
4881 istk
->expansion
= NULL
;
4883 istk
->fp
= fopen(file
, "r");
4888 nasm_fatal(ERR_NOFILE
, "unable to open input file `%s'", file
);
4890 nested_mac_count
= 0;
4891 nested_rep_count
= 0;
4894 if (tasm_compatible_mode
) {
4895 stdmacpos
= nasm_stdmac
;
4897 stdmacpos
= nasm_stdmac_after_tasm
;
4899 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4903 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4904 * The caller, however, will also pass in 3 for preprocess-only so
4905 * we can set __PASS__ accordingly.
4907 pass
= apass
> 2 ? 2 : apass
;
4909 dephead
= deptail
= deplist
;
4911 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4913 strcpy(sl
->str
, file
);
4915 deptail
= &sl
->next
;
4919 * Define the __PASS__ macro. This is defined here unlike
4920 * all the other builtins, because it is special -- it varies between
4923 t
= nasm_malloc(sizeof(*t
));
4925 make_tok_num(t
, apass
);
4927 define_smacro(NULL
, "__PASS__", true, 0, t
);
4930 static char *pp_getline(void)
4935 real_verror
= nasm_set_verror(pp_verror
);
4939 * Fetch a tokenized line, either from the macro-expansion
4940 * buffer or from the input file.
4943 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4944 Line
*l
= istk
->expansion
;
4945 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4949 * This is a macro-end marker for a macro with no
4950 * name, which means it's not really a macro at all
4951 * but a %rep block, and the `in_progress' field is
4952 * more than 1, meaning that we still need to
4953 * repeat. (1 means the natural last repetition; 0
4954 * means termination by %exitrep.) We have
4955 * therefore expanded up to the %endrep, and must
4956 * push the whole block on to the expansion buffer
4957 * again. We don't bother to remove the macro-end
4958 * marker: we'd only have to generate another one
4961 l
->finishes
->in_progress
--;
4962 list_for_each(l
, l
->finishes
->expansion
) {
4963 Token
*t
, *tt
, **tail
;
4965 ll
= nasm_malloc(sizeof(Line
));
4966 ll
->next
= istk
->expansion
;
4967 ll
->finishes
= NULL
;
4971 list_for_each(t
, l
->first
) {
4972 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4973 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4978 istk
->expansion
= ll
;
4982 * Check whether a `%rep' was started and not ended
4983 * within this macro expansion. This can happen and
4984 * should be detected. It's a fatal error because
4985 * I'm too confused to work out how to recover
4990 nasm_panic(0, "defining with name in expansion");
4991 else if (istk
->mstk
->name
)
4992 nasm_fatal(0, "`%%rep' without `%%endrep' within"
4993 " expansion of macro `%s'",
4998 * FIXME: investigate the relationship at this point between
4999 * istk->mstk and l->finishes
5002 MMacro
*m
= istk
->mstk
;
5003 istk
->mstk
= m
->next_active
;
5006 * This was a real macro call, not a %rep, and
5007 * therefore the parameter information needs to
5012 l
->finishes
->in_progress
--;
5014 nasm_free(m
->params
);
5015 free_tlist(m
->iline
);
5016 nasm_free(m
->paramlen
);
5017 l
->finishes
->in_progress
= 0;
5022 istk
->expansion
= l
->next
;
5024 lfmt
->downlevel(LIST_MACRO
);
5027 while (1) { /* until we get a line we can use */
5029 if (istk
->expansion
) { /* from a macro expansion */
5031 Line
*l
= istk
->expansion
;
5033 istk
->mstk
->lineno
++;
5035 istk
->expansion
= l
->next
;
5037 p
= detoken(tline
, false);
5038 lfmt
->line(LIST_MACRO
, p
);
5043 if (line
) { /* from the current input file */
5044 line
= prepreproc(line
);
5045 tline
= tokenize(line
);
5050 * The current file has ended; work down the istk
5056 /* nasm_error can't be conditionally suppressed */
5058 "expected `%%endif' before end of file");
5060 /* only set line and file name if there's a next node */
5062 src_set(i
->lineno
, i
->fname
);
5064 lfmt
->downlevel(LIST_INCLUDE
);
5070 if (istk
->expansion
&& istk
->expansion
->finishes
)
5076 * We must expand MMacro parameters and MMacro-local labels
5077 * _before_ we plunge into directive processing, to cope
5078 * with things like `%define something %1' such as STRUC
5079 * uses. Unless we're _defining_ a MMacro, in which case
5080 * those tokens should be left alone to go into the
5081 * definition; and unless we're in a non-emitting
5082 * condition, in which case we don't want to meddle with
5085 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
5086 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
5087 tline
= expand_mmac_params(tline
);
5091 * Check the line to see if it's a preprocessor directive.
5093 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5095 } else if (defining
) {
5097 * We're defining a multi-line macro. We emit nothing
5099 * shove the tokenized line on to the macro definition.
5101 Line
*l
= nasm_malloc(sizeof(Line
));
5102 l
->next
= defining
->expansion
;
5105 defining
->expansion
= l
;
5107 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
5109 * We're in a non-emitting branch of a condition block.
5110 * Emit nothing at all, not even a blank line: when we
5111 * emerge from the condition we'll give a line-number
5112 * directive so we keep our place correctly.
5116 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
5118 * We're in a %rep block which has been terminated, so
5119 * we're walking through to the %endrep without
5120 * emitting anything. Emit nothing at all, not even a
5121 * blank line: when we emerge from the %rep block we'll
5122 * give a line-number directive so we keep our place
5128 tline
= expand_smacro(tline
);
5129 if (!expand_mmacro(tline
)) {
5131 * De-tokenize the line again, and emit it.
5133 line
= detoken(tline
, true);
5137 continue; /* expand_mmacro calls free_tlist */
5143 nasm_set_verror(real_verror
);
5147 static void pp_cleanup(int pass
)
5149 real_verror
= nasm_set_verror(pp_verror
);
5152 if (defining
->name
) {
5153 nasm_error(ERR_NONFATAL
,
5154 "end of file while still defining macro `%s'",
5157 nasm_error(ERR_NONFATAL
, "end of file while still in %%rep");
5160 free_mmacro(defining
);
5164 nasm_set_verror(real_verror
);
5177 src_set_fname(NULL
);
5184 while ((i
= ipath
)) {
5193 static void pp_include_path(char *path
)
5197 i
= nasm_malloc(sizeof(IncPath
));
5198 i
->path
= path
? nasm_strdup(path
) : NULL
;
5211 static void pp_pre_include(char *fname
)
5213 Token
*inc
, *space
, *name
;
5216 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5217 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5218 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5220 l
= nasm_malloc(sizeof(Line
));
5227 static void pp_pre_define(char *definition
)
5233 real_verror
= nasm_set_verror(pp_verror
);
5235 equals
= strchr(definition
, '=');
5236 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5237 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5240 space
->next
= tokenize(definition
);
5244 if (space
->next
->type
!= TOK_PREPROC_ID
&&
5245 space
->next
->type
!= TOK_ID
)
5246 nasm_error(ERR_WARNING
, "pre-defining non ID `%s\'\n", definition
);
5248 l
= nasm_malloc(sizeof(Line
));
5254 nasm_set_verror(real_verror
);
5257 static void pp_pre_undefine(char *definition
)
5262 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5263 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5264 space
->next
= tokenize(definition
);
5266 l
= nasm_malloc(sizeof(Line
));
5273 static void pp_extra_stdmac(macros_t
*macros
)
5275 extrastdmac
= macros
;
5278 static void make_tok_num(Token
* tok
, int64_t val
)
5281 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5282 tok
->text
= nasm_strdup(numbuf
);
5283 tok
->type
= TOK_NUMBER
;
5286 static void pp_list_one_macro(MMacro
*m
, int severity
)
5291 /* We need to print the next_active list in reverse order */
5292 pp_list_one_macro(m
->next_active
, severity
);
5294 if (m
->name
&& !m
->nolist
) {
5295 src_set(m
->xline
+ m
->lineno
, m
->fname
);
5296 nasm_error(severity
, "... from macro `%s' defined here", m
->name
);
5300 static void pp_error_list_macros(int severity
)
5303 const char *saved_fname
= NULL
;
5305 severity
|= ERR_PP_LISTMACRO
| ERR_NO_SEVERITY
;
5306 src_get(&saved_line
, &saved_fname
);
5309 pp_list_one_macro(istk
->mstk
, severity
);
5311 src_set(saved_line
, saved_fname
);
5314 const struct preproc_ops nasmpp
= {
5323 pp_error_list_macros
,