1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2010 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
84 typedef struct SMacro SMacro
;
85 typedef struct MMacro MMacro
;
86 typedef struct MMacroInvocation MMacroInvocation
;
87 typedef struct Context Context
;
88 typedef struct Token Token
;
89 typedef struct Blocks Blocks
;
90 typedef struct Line Line
;
91 typedef struct Include Include
;
92 typedef struct Cond Cond
;
93 typedef struct IncPath IncPath
;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
117 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
135 MMacroInvocation
*prev
; /* previous invocation */
137 int nparam_min
, nparam_max
;
139 bool plus
; /* is the last parameter greedy? */
140 bool nolist
; /* is this macro listing-inhibited? */
141 int64_t in_progress
; /* is this macro currently being expanded? */
142 int32_t max_depth
; /* maximum number of recursive expansions allowed */
143 Token
*dlist
; /* All defaults as one list */
144 Token
**defaults
; /* Parameter default pointers */
145 int ndefs
; /* number of default parameters */
149 MMacro
*rep_nest
; /* used for nesting %rep */
150 Token
**params
; /* actual parameters */
151 Token
*iline
; /* invocation line */
152 unsigned int nparam
, rotate
;
155 int lineno
; /* Current line number on expansion */
156 uint64_t condcnt
; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation
{
164 MMacroInvocation
*prev
; /* previous invocation */
165 Token
**params
; /* actual parameters */
166 Token
*iline
; /* invocation line */
167 unsigned int nparam
, rotate
;
175 * The context stack is composed of a linked list of these.
180 struct hash_table localmac
;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
204 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
205 TOK_PREPROC_ID
, TOK_STRING
,
206 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
208 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
210 TOK_INDIRECT
, /* %[...] */
211 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
219 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
220 size_t len
; /* scratch length field */
221 } a
; /* Auxiliary data */
222 enum pp_token_type type
;
226 * Multi-line macro definitions are stored as a linked list of
227 * these, which is essentially a container to allow several linked
230 * Note that in this module, linked lists are treated as stacks
231 * wherever possible. For this reason, Lines are _pushed_ on to the
232 * `expansion' field in MMacro structures, so that the linked list,
233 * if walked, would give the macro lines in reverse order; this
234 * means that we can walk the list when expanding a macro, and thus
235 * push the lines on to the `expansion' field in _istk_ in reverse
236 * order (so that when popped back off they are in the right
237 * order). It may seem cockeyed, and it relies on my design having
238 * an even number of steps in, but it works...
240 * Some of these structures, rather than being actual lines, are
241 * markers delimiting the end of the expansion of a given macro.
242 * This is for use in the cycle-tracking and %rep-handling code.
243 * Such structures have `finishes' non-NULL, and `first' NULL. All
244 * others have `finishes' NULL, but `first' may still be NULL if
254 * To handle an arbitrary level of file inclusion, we maintain a
255 * stack (ie linked list) of these things.
264 MMacro
*mstk
; /* stack of active macros/reps */
268 * Include search path. This is simply a list of strings which get
269 * prepended, in turn, to the name of an include file, in an
270 * attempt to find the file if it's not in the current directory.
278 * Conditional assembly: we maintain a separate stack of these for
279 * each level of file inclusion. (The only reason we keep the
280 * stacks separate is to ensure that a stray `%endif' in a file
281 * included from within the true branch of a `%if' won't terminate
282 * it and cause confusion: instead, rightly, it'll cause an error.)
290 * These states are for use just after %if or %elif: IF_TRUE
291 * means the condition has evaluated to truth so we are
292 * currently emitting, whereas IF_FALSE means we are not
293 * currently emitting but will start doing so if a %else comes
294 * up. In these states, all directives are admissible: %elif,
295 * %else and %endif. (And of course %if.)
297 COND_IF_TRUE
, COND_IF_FALSE
,
299 * These states come up after a %else: ELSE_TRUE means we're
300 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
301 * any %elif or %else will cause an error.
303 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
305 * These states mean that we're not emitting now, and also that
306 * nothing until %endif will be emitted at all. COND_DONE is
307 * used when we've had our moment of emission
308 * and have now started seeing %elifs. COND_NEVER is used when
309 * the condition construct in question is contained within a
310 * non-emitting branch of a larger condition construct,
311 * or if there is an error.
313 COND_DONE
, COND_NEVER
315 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
318 * These defines are used as the possible return values for do_directive
320 #define NO_DIRECTIVE_FOUND 0
321 #define DIRECTIVE_FOUND 1
324 * This define sets the upper limit for smacro and recursive mmacro
327 #define DEADMAN_LIMIT (1 << 20)
330 #define REP_LIMIT ((INT64_C(1) << 62))
333 * Condition codes. Note that we use c_ prefix not C_ because C_ is
334 * used in nasm.h for the "real" condition codes. At _this_ level,
335 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
336 * ones, so we need a different enum...
338 static const char * const conditions
[] = {
339 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
340 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
341 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
344 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
345 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
346 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
349 static const enum pp_conds inverse_ccs
[] = {
350 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
351 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
,
352 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
358 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
359 static int is_condition(enum preproc_token arg
)
361 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
364 /* For TASM compatibility we need to be able to recognise TASM compatible
365 * conditional compilation directives. Using the NASM pre-processor does
366 * not work, so we look for them specifically from the following list and
367 * then jam in the equivalent NASM directive into the input stream.
371 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
372 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
375 static const char * const tasm_directives
[] = {
376 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
377 "ifndef", "include", "local"
380 static int StackSize
= 4;
381 static char *StackPointer
= "ebp";
382 static int ArgOffset
= 8;
383 static int LocalOffset
= 0;
385 static Context
*cstk
;
386 static Include
*istk
;
387 static IncPath
*ipath
= NULL
;
389 static int pass
; /* HACK: pass 0 = generate dependencies only */
390 static StrList
**dephead
, **deptail
; /* Dependency list */
392 static uint64_t unique
; /* unique identifier numbers */
394 static Line
*predef
= NULL
;
395 static bool do_predef
;
397 static ListGen
*list
;
400 * The current set of multi-line macros we have defined.
402 static struct hash_table mmacros
;
405 * The current set of single-line macros we have defined.
407 static struct hash_table smacros
;
410 * The multi-line macro we are currently defining, or the %rep
411 * block we are currently reading, if any.
413 static MMacro
*defining
;
415 static uint64_t nested_mac_count
;
416 static uint64_t nested_rep_count
;
419 * The number of macro parameters to allocate space for at a time.
421 #define PARAM_DELTA 16
424 * The standard macro set: defined in macros.c in the array nasm_stdmac.
425 * This gives our position in the macro set, when we're processing it.
427 static macros_t
*stdmacpos
;
430 * The extra standard macros that come from the object format, if
433 static macros_t
*extrastdmac
= NULL
;
434 static bool any_extrastdmac
;
437 * Tokens are allocated in blocks to improve speed
439 #define TOKEN_BLOCKSIZE 4096
440 static Token
*freeTokens
= NULL
;
446 static Blocks blocks
= { NULL
, NULL
};
449 * Forward declarations.
451 static Token
*expand_mmac_params(Token
* tline
);
452 static Token
*expand_smacro(Token
* tline
);
453 static Token
*expand_id(Token
* tline
);
454 static Context
*get_ctx(const char *name
, const char **namep
,
456 static void make_tok_num(Token
* tok
, int64_t val
);
457 static void error(int severity
, const char *fmt
, ...);
458 static void error_precond(int severity
, const char *fmt
, ...);
459 static void *new_Block(size_t size
);
460 static void delete_Blocks(void);
461 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
462 const char *text
, int txtlen
);
463 static Token
*delete_Token(Token
* t
);
466 * Macros for safe checking of token pointers, avoid *(NULL)
468 #define tok_type_(x,t) ((x) && (x)->type == (t))
469 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
470 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
471 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
474 * nasm_unquote with error if the string contains NUL characters.
475 * If the string contains NUL characters, issue an error and return
476 * the C len, i.e. truncate at the NUL.
478 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
480 size_t len
= nasm_unquote(qstr
, NULL
);
481 size_t clen
= strlen(qstr
);
484 error(ERR_NONFATAL
, "NUL character in `%s' directive",
485 pp_directives
[directive
]);
491 * In-place reverse a list of tokens.
493 static Token
*reverse_tokens(Token
*t
)
509 * Handle TASM specific directives, which do not contain a % in
510 * front of them. We do it here because I could not find any other
511 * place to do it for the moment, and it is a hack (ideally it would
512 * be nice to be able to use the NASM pre-processor to do it).
514 static char *check_tasm_directive(char *line
)
516 int32_t i
, j
, k
, m
, len
;
517 char *p
, *q
, *oldline
, oldchar
;
519 p
= nasm_skip_spaces(line
);
521 /* Binary search for the directive name */
523 j
= ARRAY_SIZE(tasm_directives
);
524 q
= nasm_skip_word(p
);
531 m
= nasm_stricmp(p
, tasm_directives
[k
]);
533 /* We have found a directive, so jam a % in front of it
534 * so that NASM will then recognise it as one if it's own.
539 line
= nasm_malloc(len
+ 2);
541 if (k
== TM_IFDIFI
) {
543 * NASM does not recognise IFDIFI, so we convert
544 * it to %if 0. This is not used in NASM
545 * compatible code, but does need to parse for the
546 * TASM macro package.
548 strcpy(line
+ 1, "if 0");
550 memcpy(line
+ 1, p
, len
+ 1);
565 * The pre-preprocessing stage... This function translates line
566 * number indications as they emerge from GNU cpp (`# lineno "file"
567 * flags') into NASM preprocessor line number indications (`%line
570 static char *prepreproc(char *line
)
573 char *fname
, *oldline
;
575 if (line
[0] == '#' && line
[1] == ' ') {
578 lineno
= atoi(fname
);
579 fname
+= strspn(fname
, "0123456789 ");
582 fnlen
= strcspn(fname
, "\"");
583 line
= nasm_malloc(20 + fnlen
);
584 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
587 if (tasm_compatible_mode
)
588 return check_tasm_directive(line
);
593 * Free a linked list of tokens.
595 static void free_tlist(Token
* list
)
598 list
= delete_Token(list
);
602 * Free a linked list of lines.
604 static void free_llist(Line
* list
)
607 list_for_each_safe(l
, tmp
, list
) {
608 free_tlist(l
->first
);
616 static void free_mmacro(MMacro
* m
)
619 free_tlist(m
->dlist
);
620 nasm_free(m
->defaults
);
621 free_llist(m
->expansion
);
626 * Free all currently defined macros, and free the hash tables
628 static void free_smacro_table(struct hash_table
*smt
)
632 struct hash_tbl_node
*it
= NULL
;
634 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
635 nasm_free((void *)key
);
636 list_for_each_safe(s
, tmp
, s
) {
638 free_tlist(s
->expansion
);
645 static void free_mmacro_table(struct hash_table
*mmt
)
649 struct hash_tbl_node
*it
= NULL
;
652 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
653 nasm_free((void *)key
);
654 list_for_each_safe(m
,tmp
, m
)
660 static void free_macros(void)
662 free_smacro_table(&smacros
);
663 free_mmacro_table(&mmacros
);
667 * Initialize the hash tables
669 static void init_macros(void)
671 hash_init(&smacros
, HASH_LARGE
);
672 hash_init(&mmacros
, HASH_LARGE
);
676 * Pop the context stack.
678 static void ctx_pop(void)
683 free_smacro_table(&c
->localmac
);
689 * Search for a key in the hash index; adding it if necessary
690 * (in which case we initialize the data pointer to NULL.)
693 hash_findi_add(struct hash_table
*hash
, const char *str
)
695 struct hash_insert hi
;
699 r
= hash_findi(hash
, str
, &hi
);
703 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
704 return hash_add(&hi
, strx
, NULL
);
708 * Like hash_findi, but returns the data element rather than a pointer
709 * to it. Used only when not adding a new element, hence no third
713 hash_findix(struct hash_table
*hash
, const char *str
)
717 p
= hash_findi(hash
, str
, NULL
);
718 return p
? *p
: NULL
;
722 * read line from standart macros set,
723 * if there no more left -- return NULL
725 static char *line_from_stdmac(void)
728 const unsigned char *p
= stdmacpos
;
737 len
+= pp_directives_len
[c
- 0x80] + 1;
742 line
= nasm_malloc(len
+ 1);
744 while ((c
= *stdmacpos
++)) {
746 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
747 q
+= pp_directives_len
[c
- 0x80];
757 /* This was the last of the standard macro chain... */
759 if (any_extrastdmac
) {
760 stdmacpos
= extrastdmac
;
761 any_extrastdmac
= false;
762 } else if (do_predef
) {
764 Token
*head
, **tail
, *t
;
767 * Nasty hack: here we push the contents of
768 * `predef' on to the top-level expansion stack,
769 * since this is the most convenient way to
770 * implement the pre-include and pre-define
773 list_for_each(pd
, predef
) {
776 list_for_each(t
, pd
->first
) {
777 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
778 tail
= &(*tail
)->next
;
781 l
= nasm_malloc(sizeof(Line
));
782 l
->next
= istk
->expansion
;
795 #define BUF_DELTA 512
797 * Read a line from the top file in istk, handling multiple CR/LFs
798 * at the end of the line read, and handling spurious ^Zs. Will
799 * return lines from the standard macro set if this has not already
802 static char *read_line(void)
804 char *buffer
, *p
, *q
;
805 int bufsize
, continued_count
;
808 * standart macros set (predefined) goes first
810 p
= line_from_stdmac();
815 * regular read from a file
818 buffer
= nasm_malloc(BUF_DELTA
);
822 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
826 if (p
> buffer
&& p
[-1] == '\n') {
828 * Convert backslash-CRLF line continuation sequences into
829 * nothing at all (for DOS and Windows)
831 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
837 * Also convert backslash-LF line continuation sequences into
838 * nothing at all (for Unix)
840 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
848 if (p
- buffer
> bufsize
- 10) {
849 int32_t offset
= p
- buffer
;
850 bufsize
+= BUF_DELTA
;
851 buffer
= nasm_realloc(buffer
, bufsize
);
852 p
= buffer
+ offset
; /* prevent stale-pointer problems */
856 if (!q
&& p
== buffer
) {
861 src_set_linnum(src_get_linnum() + istk
->lineinc
+
862 (continued_count
* istk
->lineinc
));
865 * Play safe: remove CRs as well as LFs, if any of either are
866 * present at the end of the line.
868 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
872 * Handle spurious ^Z, which may be inserted into source files
873 * by some file transfer utilities.
875 buffer
[strcspn(buffer
, "\032")] = '\0';
877 list
->line(LIST_READ
, buffer
);
883 * Tokenize a line of text. This is a very simple process since we
884 * don't need to parse the value out of e.g. numeric tokens: we
885 * simply split one string into many.
887 static Token
*tokenize(char *line
)
890 enum pp_token_type type
;
892 Token
*t
, **tail
= &list
;
898 if (*p
== '+' && !nasm_isdigit(p
[1])) {
901 } else if (nasm_isdigit(*p
) ||
902 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
906 while (nasm_isdigit(*p
));
907 type
= TOK_PREPROC_ID
;
908 } else if (*p
== '{') {
917 error(ERR_WARNING
| ERR_PASS1
, "unterminated %{ construct");
921 type
= TOK_PREPROC_ID
;
922 } else if (*p
== '[') {
924 line
+= 2; /* Skip the leading %[ */
926 while (lvl
&& (c
= *p
++)) {
938 p
= nasm_skip_string(p
- 1) + 1;
948 error(ERR_NONFATAL
, "unterminated %[ construct");
950 } else if (*p
== '?') {
951 type
= TOK_PREPROC_Q
; /* %? */
954 type
= TOK_PREPROC_QQ
; /* %?? */
957 } else if (*p
== '!') {
958 type
= TOK_PREPROC_ID
;
964 while (isidchar(*p
));
965 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
966 p
= nasm_skip_string(p
);
970 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
972 /* %! without string or identifier */
973 type
= TOK_OTHER
; /* Legacy behavior... */
975 } else if (isidchar(*p
) ||
976 ((*p
== '!' || *p
== '%' || *p
== '$') &&
981 while (isidchar(*p
));
982 type
= TOK_PREPROC_ID
;
988 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
991 while (*p
&& isidchar(*p
))
993 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
998 p
= nasm_skip_string(p
);
1003 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1004 /* Handling unterminated strings by UNV */
1007 } else if (p
[0] == '$' && p
[1] == '$') {
1008 type
= TOK_OTHER
; /* TOKEN_BASE */
1010 } else if (isnumstart(*p
)) {
1011 bool is_hex
= false;
1012 bool is_float
= false;
1028 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1030 if (*p
== '+' || *p
== '-') {
1032 * e can only be followed by +/- if it is either a
1033 * prefixed hex number or a floating-point number
1038 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1040 } else if (c
== 'P' || c
== 'p') {
1042 if (*p
== '+' || *p
== '-')
1044 } else if (isnumchar(c
) || c
== '_')
1045 ; /* just advance */
1046 else if (c
== '.') {
1048 * we need to deal with consequences of the legacy
1049 * parser, like "1.nolist" being two tokens
1050 * (TOK_NUMBER, TOK_ID) here; at least give it
1051 * a shot for now. In the future, we probably need
1052 * a flex-based scanner with proper pattern matching
1053 * to do it as well as it can be done. Nothing in
1054 * the world is going to help the person who wants
1055 * 0x123.p16 interpreted as two tokens, though.
1061 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1062 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1063 (*r
== 'p' || *r
== 'P')) {
1067 break; /* Terminate the token */
1071 p
--; /* Point to first character beyond number */
1073 if (p
== line
+1 && *line
== '$') {
1074 type
= TOK_OTHER
; /* TOKEN_HERE */
1076 if (has_e
&& !is_hex
) {
1077 /* 1e13 is floating-point, but 1e13h is not */
1081 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1083 } else if (nasm_isspace(*p
)) {
1084 type
= TOK_WHITESPACE
;
1085 p
= nasm_skip_spaces(p
);
1087 * Whitespace just before end-of-line is discarded by
1088 * pretending it's a comment; whitespace just before a
1089 * comment gets lumped into the comment.
1091 if (!*p
|| *p
== ';') {
1096 } else if (*p
== ';') {
1102 * Anything else is an operator of some kind. We check
1103 * for all the double-character operators (>>, <<, //,
1104 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1105 * else is a single-character operator.
1108 if ((p
[0] == '>' && p
[1] == '>') ||
1109 (p
[0] == '<' && p
[1] == '<') ||
1110 (p
[0] == '/' && p
[1] == '/') ||
1111 (p
[0] == '<' && p
[1] == '=') ||
1112 (p
[0] == '>' && p
[1] == '=') ||
1113 (p
[0] == '=' && p
[1] == '=') ||
1114 (p
[0] == '!' && p
[1] == '=') ||
1115 (p
[0] == '<' && p
[1] == '>') ||
1116 (p
[0] == '&' && p
[1] == '&') ||
1117 (p
[0] == '|' && p
[1] == '|') ||
1118 (p
[0] == '^' && p
[1] == '^')) {
1124 /* Handling unterminated string by UNV */
1127 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1128 t->text[p-line] = *line;
1132 if (type
!= TOK_COMMENT
) {
1133 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1142 * this function allocates a new managed block of memory and
1143 * returns a pointer to the block. The managed blocks are
1144 * deleted only all at once by the delete_Blocks function.
1146 static void *new_Block(size_t size
)
1148 Blocks
*b
= &blocks
;
1150 /* first, get to the end of the linked list */
1153 /* now allocate the requested chunk */
1154 b
->chunk
= nasm_malloc(size
);
1156 /* now allocate a new block for the next request */
1157 b
->next
= nasm_malloc(sizeof(Blocks
));
1158 /* and initialize the contents of the new block */
1159 b
->next
->next
= NULL
;
1160 b
->next
->chunk
= NULL
;
1165 * this function deletes all managed blocks of memory
1167 static void delete_Blocks(void)
1169 Blocks
*a
, *b
= &blocks
;
1172 * keep in mind that the first block, pointed to by blocks
1173 * is a static and not dynamically allocated, so we don't
1178 nasm_free(b
->chunk
);
1187 * this function creates a new Token and passes a pointer to it
1188 * back to the caller. It sets the type and text elements, and
1189 * also the a.mac and next elements to NULL.
1191 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1192 const char *text
, int txtlen
)
1198 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1199 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1200 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1201 freeTokens
[i
].next
= NULL
;
1204 freeTokens
= t
->next
;
1208 if (type
== TOK_WHITESPACE
|| !text
) {
1212 txtlen
= strlen(text
);
1213 t
->text
= nasm_malloc(txtlen
+1);
1214 memcpy(t
->text
, text
, txtlen
);
1215 t
->text
[txtlen
] = '\0';
1220 static Token
*delete_Token(Token
* t
)
1222 Token
*next
= t
->next
;
1224 t
->next
= freeTokens
;
1230 * Convert a line of tokens back into text.
1231 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1232 * will be transformed into ..@ctxnum.xxx
1234 static char *detoken(Token
* tlist
, bool expand_locals
)
1241 list_for_each(t
, tlist
) {
1242 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1247 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1248 size_t len
= nasm_unquote(v
, NULL
);
1249 size_t clen
= strlen(v
);
1252 error(ERR_NONFATAL
| ERR_PASS1
,
1253 "NUL character in %! string");
1259 char *p
= getenv(v
);
1261 error(ERR_NONFATAL
| ERR_PASS1
,
1262 "nonexistent environment variable `%s'", v
);
1265 t
->text
= nasm_strdup(p
);
1270 /* Expand local macros here and not during preprocessing */
1271 if (expand_locals
&&
1272 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1273 t
->text
[0] == '%' && t
->text
[1] == '$') {
1276 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1279 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1280 p
= nasm_strcat(buffer
, q
);
1285 if (t
->type
== TOK_WHITESPACE
)
1288 len
+= strlen(t
->text
);
1291 p
= line
= nasm_malloc(len
+ 1);
1293 list_for_each(t
, tlist
) {
1294 if (t
->type
== TOK_WHITESPACE
) {
1296 } else if (t
->text
) {
1308 * A scanner, suitable for use by the expression evaluator, which
1309 * operates on a line of Tokens. Expects a pointer to a pointer to
1310 * the first token in the line to be passed in as its private_data
1313 * FIX: This really needs to be unified with stdscan.
1315 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1317 Token
**tlineptr
= private_data
;
1319 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1323 *tlineptr
= tline
? tline
->next
: NULL
;
1324 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1325 tline
->type
== TOK_COMMENT
));
1328 return tokval
->t_type
= TOKEN_EOS
;
1330 tokval
->t_charptr
= tline
->text
;
1332 if (tline
->text
[0] == '$' && !tline
->text
[1])
1333 return tokval
->t_type
= TOKEN_HERE
;
1334 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1335 return tokval
->t_type
= TOKEN_BASE
;
1337 if (tline
->type
== TOK_ID
) {
1338 p
= tokval
->t_charptr
= tline
->text
;
1340 tokval
->t_charptr
++;
1341 return tokval
->t_type
= TOKEN_ID
;
1344 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1345 if (r
>= p
+MAX_KEYWORD
)
1346 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1347 *s
++ = nasm_tolower(*r
);
1350 /* right, so we have an identifier sitting in temp storage. now,
1351 * is it actually a register or instruction name, or what? */
1352 return nasm_token_hash(ourcopy
, tokval
);
1355 if (tline
->type
== TOK_NUMBER
) {
1357 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1358 tokval
->t_charptr
= tline
->text
;
1360 return tokval
->t_type
= TOKEN_ERRNUM
;
1362 return tokval
->t_type
= TOKEN_NUM
;
1365 if (tline
->type
== TOK_FLOAT
) {
1366 return tokval
->t_type
= TOKEN_FLOAT
;
1369 if (tline
->type
== TOK_STRING
) {
1372 bq
= tline
->text
[0];
1373 tokval
->t_charptr
= tline
->text
;
1374 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1376 if (ep
[0] != bq
|| ep
[1] != '\0')
1377 return tokval
->t_type
= TOKEN_ERRSTR
;
1379 return tokval
->t_type
= TOKEN_STR
;
1382 if (tline
->type
== TOK_OTHER
) {
1383 if (!strcmp(tline
->text
, "<<"))
1384 return tokval
->t_type
= TOKEN_SHL
;
1385 if (!strcmp(tline
->text
, ">>"))
1386 return tokval
->t_type
= TOKEN_SHR
;
1387 if (!strcmp(tline
->text
, "//"))
1388 return tokval
->t_type
= TOKEN_SDIV
;
1389 if (!strcmp(tline
->text
, "%%"))
1390 return tokval
->t_type
= TOKEN_SMOD
;
1391 if (!strcmp(tline
->text
, "=="))
1392 return tokval
->t_type
= TOKEN_EQ
;
1393 if (!strcmp(tline
->text
, "<>"))
1394 return tokval
->t_type
= TOKEN_NE
;
1395 if (!strcmp(tline
->text
, "!="))
1396 return tokval
->t_type
= TOKEN_NE
;
1397 if (!strcmp(tline
->text
, "<="))
1398 return tokval
->t_type
= TOKEN_LE
;
1399 if (!strcmp(tline
->text
, ">="))
1400 return tokval
->t_type
= TOKEN_GE
;
1401 if (!strcmp(tline
->text
, "&&"))
1402 return tokval
->t_type
= TOKEN_DBL_AND
;
1403 if (!strcmp(tline
->text
, "^^"))
1404 return tokval
->t_type
= TOKEN_DBL_XOR
;
1405 if (!strcmp(tline
->text
, "||"))
1406 return tokval
->t_type
= TOKEN_DBL_OR
;
1410 * We have no other options: just return the first character of
1413 return tokval
->t_type
= tline
->text
[0];
1417 * Compare a string to the name of an existing macro; this is a
1418 * simple wrapper which calls either strcmp or nasm_stricmp
1419 * depending on the value of the `casesense' parameter.
1421 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1423 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1427 * Compare a string to the name of an existing macro; this is a
1428 * simple wrapper which calls either strcmp or nasm_stricmp
1429 * depending on the value of the `casesense' parameter.
1431 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1433 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1437 * Return the Context structure associated with a %$ token. Return
1438 * NULL, having _already_ reported an error condition, if the
1439 * context stack isn't deep enough for the supplied number of $
1441 * If all_contexts == true, contexts that enclose current are
1442 * also scanned for such smacro, until it is found; if not -
1443 * only the context that directly results from the number of $'s
1444 * in variable's name.
1446 * If "namep" is non-NULL, set it to the pointer to the macro name
1447 * tail, i.e. the part beyond %$...
1449 static Context
*get_ctx(const char *name
, const char **namep
,
1459 if (!name
|| name
[0] != '%' || name
[1] != '$')
1463 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1470 while (ctx
&& *name
== '$') {
1476 error(ERR_NONFATAL
, "`%s': context stack is only"
1477 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1488 * NOTE: In 2.10 we will not need lookup in extarnal
1489 * contexts, so this is a gentle way to inform users
1490 * about their source code need to be updated
1493 /* first round -- check the current context */
1494 m
= hash_findix(&ctx
->localmac
, name
);
1496 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1501 /* second round - external contexts */
1502 while ((ctx
= ctx
->next
)) {
1503 /* Search for this smacro in found context */
1504 m
= hash_findix(&ctx
->localmac
, name
);
1506 if (!mstrcmp(m
->name
, name
, m
->casesense
)) {
1507 /* NOTE: deprecated as of 2.10 */
1508 static int once
= 0;
1510 error(ERR_WARNING
, "context-local macro expansion"
1511 " fall-through (automatic searching of outer"
1512 " contexts) will be deprecated starting in"
1513 " NASM 2.10, please see the NASM Manual for"
1514 " more information");
1517 error(ERR_WARNING
, "`%s': context-local macro expansion fall-through", name
);
1528 * Check to see if a file is already in a string list
1530 static bool in_list(const StrList
*list
, const char *str
)
1533 if (!strcmp(list
->str
, str
))
1541 * Open an include file. This routine must always return a valid
1542 * file pointer if it returns - it's responsible for throwing an
1543 * ERR_FATAL and bombing out completely if not. It should also try
1544 * the include path one by one until it finds the file or reaches
1545 * the end of the path.
1547 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1552 IncPath
*ip
= ipath
;
1553 int len
= strlen(file
);
1554 size_t prefix_len
= 0;
1558 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1559 memcpy(sl
->str
, prefix
, prefix_len
);
1560 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1561 fp
= fopen(sl
->str
, "r");
1562 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1580 prefix_len
= strlen(prefix
);
1582 /* -MG given and file not found */
1583 if (dhead
&& !in_list(*dhead
, file
)) {
1584 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1586 strcpy(sl
->str
, file
);
1594 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1599 * Determine if we should warn on defining a single-line macro of
1600 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1601 * return true if _any_ single-line macro of that name is defined.
1602 * Otherwise, will return true if a single-line macro with either
1603 * `nparam' or no parameters is defined.
1605 * If a macro with precisely the right number of parameters is
1606 * defined, or nparam is -1, the address of the definition structure
1607 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1608 * is NULL, no action will be taken regarding its contents, and no
1611 * Note that this is also called with nparam zero to resolve
1614 * If you already know which context macro belongs to, you can pass
1615 * the context pointer as first parameter; if you won't but name begins
1616 * with %$ the context will be automatically computed. If all_contexts
1617 * is true, macro will be searched in outer contexts as well.
1620 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1623 struct hash_table
*smtbl
;
1627 smtbl
= &ctx
->localmac
;
1628 } else if (name
[0] == '%' && name
[1] == '$') {
1630 ctx
= get_ctx(name
, &name
, false);
1632 return false; /* got to return _something_ */
1633 smtbl
= &ctx
->localmac
;
1637 m
= (SMacro
*) hash_findix(smtbl
, name
);
1640 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1641 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1643 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1657 * Count and mark off the parameters in a multi-line macro call.
1658 * This is called both from within the multi-line macro expansion
1659 * code, and also to mark off the default parameters when provided
1660 * in a %macro definition line.
1662 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1664 int paramsize
, brace
;
1666 *nparam
= paramsize
= 0;
1669 /* +1: we need space for the final NULL */
1670 if (*nparam
+1 >= paramsize
) {
1671 paramsize
+= PARAM_DELTA
;
1672 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1676 if (tok_is_(t
, "{"))
1678 (*params
)[(*nparam
)++] = t
;
1679 while (tok_isnt_(t
, brace
? "}" : ","))
1681 if (t
) { /* got a comma/brace */
1685 * Now we've found the closing brace, look further
1689 if (tok_isnt_(t
, ",")) {
1691 "braces do not enclose all of macro parameter");
1692 while (tok_isnt_(t
, ","))
1696 t
= t
->next
; /* eat the comma */
1703 * Determine whether one of the various `if' conditions is true or
1706 * We must free the tline we get passed.
1708 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1710 enum pp_conditional i
= PP_COND(ct
);
1712 Token
*t
, *tt
, **tptr
, *origline
;
1713 struct tokenval tokval
;
1715 enum pp_token_type needtype
;
1722 j
= false; /* have we matched yet? */
1727 if (tline
->type
!= TOK_ID
) {
1729 "`%s' expects context identifiers", pp_directives
[ct
]);
1730 free_tlist(origline
);
1733 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1735 tline
= tline
->next
;
1740 j
= false; /* have we matched yet? */
1743 if (!tline
|| (tline
->type
!= TOK_ID
&&
1744 (tline
->type
!= TOK_PREPROC_ID
||
1745 tline
->text
[1] != '$'))) {
1747 "`%s' expects macro identifiers", pp_directives
[ct
]);
1750 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1752 tline
= tline
->next
;
1757 tline
= expand_smacro(tline
);
1758 j
= false; /* have we matched yet? */
1761 if (!tline
|| (tline
->type
!= TOK_ID
&&
1762 tline
->type
!= TOK_STRING
&&
1763 (tline
->type
!= TOK_PREPROC_ID
||
1764 tline
->text
[1] != '!'))) {
1766 "`%s' expects environment variable names",
1771 if (tline
->type
== TOK_PREPROC_ID
)
1772 p
+= 2; /* Skip leading %! */
1773 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1774 nasm_unquote_cstr(p
, ct
);
1777 tline
= tline
->next
;
1783 tline
= expand_smacro(tline
);
1785 while (tok_isnt_(tt
, ","))
1789 "`%s' expects two comma-separated arguments",
1794 j
= true; /* assume equality unless proved not */
1795 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1796 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1797 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1801 if (t
->type
== TOK_WHITESPACE
) {
1805 if (tt
->type
== TOK_WHITESPACE
) {
1809 if (tt
->type
!= t
->type
) {
1810 j
= false; /* found mismatching tokens */
1813 /* When comparing strings, need to unquote them first */
1814 if (t
->type
== TOK_STRING
) {
1815 size_t l1
= nasm_unquote(t
->text
, NULL
);
1816 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1822 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1826 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1827 j
= false; /* found mismatching tokens */
1834 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1835 j
= false; /* trailing gunk on one end or other */
1841 MMacro searching
, *mmac
;
1844 tline
= expand_id(tline
);
1845 if (!tok_type_(tline
, TOK_ID
)) {
1847 "`%s' expects a macro name", pp_directives
[ct
]);
1850 searching
.name
= nasm_strdup(tline
->text
);
1851 searching
.casesense
= true;
1852 searching
.plus
= false;
1853 searching
.nolist
= false;
1854 searching
.in_progress
= 0;
1855 searching
.max_depth
= 0;
1856 searching
.rep_nest
= NULL
;
1857 searching
.nparam_min
= 0;
1858 searching
.nparam_max
= INT_MAX
;
1859 tline
= expand_smacro(tline
->next
);
1862 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1864 "`%s' expects a parameter count or nothing",
1867 searching
.nparam_min
= searching
.nparam_max
=
1868 readnum(tline
->text
, &j
);
1871 "unable to parse parameter count `%s'",
1874 if (tline
&& tok_is_(tline
->next
, "-")) {
1875 tline
= tline
->next
->next
;
1876 if (tok_is_(tline
, "*"))
1877 searching
.nparam_max
= INT_MAX
;
1878 else if (!tok_type_(tline
, TOK_NUMBER
))
1880 "`%s' expects a parameter count after `-'",
1883 searching
.nparam_max
= readnum(tline
->text
, &j
);
1886 "unable to parse parameter count `%s'",
1888 if (searching
.nparam_min
> searching
.nparam_max
)
1890 "minimum parameter count exceeds maximum");
1893 if (tline
&& tok_is_(tline
->next
, "+")) {
1894 tline
= tline
->next
;
1895 searching
.plus
= true;
1897 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1899 if (!strcmp(mmac
->name
, searching
.name
) &&
1900 (mmac
->nparam_min
<= searching
.nparam_max
1902 && (searching
.nparam_min
<= mmac
->nparam_max
1909 if (tline
&& tline
->next
)
1910 error(ERR_WARNING
|ERR_PASS1
,
1911 "trailing garbage after %%ifmacro ignored");
1912 nasm_free(searching
.name
);
1921 needtype
= TOK_NUMBER
;
1924 needtype
= TOK_STRING
;
1928 t
= tline
= expand_smacro(tline
);
1930 while (tok_type_(t
, TOK_WHITESPACE
) ||
1931 (needtype
== TOK_NUMBER
&&
1932 tok_type_(t
, TOK_OTHER
) &&
1933 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1937 j
= tok_type_(t
, needtype
);
1941 t
= tline
= expand_smacro(tline
);
1942 while (tok_type_(t
, TOK_WHITESPACE
))
1947 t
= t
->next
; /* Skip the actual token */
1948 while (tok_type_(t
, TOK_WHITESPACE
))
1950 j
= !t
; /* Should be nothing left */
1955 t
= tline
= expand_smacro(tline
);
1956 while (tok_type_(t
, TOK_WHITESPACE
))
1959 j
= !t
; /* Should be empty */
1963 t
= tline
= expand_smacro(tline
);
1965 tokval
.t_type
= TOKEN_INVALID
;
1966 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1967 NULL
, pass
| CRITICAL
, error
, NULL
);
1971 error(ERR_WARNING
|ERR_PASS1
,
1972 "trailing garbage after expression ignored");
1973 if (!is_simple(evalresult
)) {
1975 "non-constant value given to `%s'", pp_directives
[ct
]);
1978 j
= reloc_value(evalresult
) != 0;
1983 "preprocessor directive `%s' not yet implemented",
1988 free_tlist(origline
);
1989 return j
^ PP_NEGATIVE(ct
);
1992 free_tlist(origline
);
1997 * Common code for defining an smacro
1999 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
2000 int nparam
, Token
*expansion
)
2002 SMacro
*smac
, **smhead
;
2003 struct hash_table
*smtbl
;
2005 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
2007 error(ERR_WARNING
|ERR_PASS1
,
2008 "single-line macro `%s' defined both with and"
2009 " without parameters", mname
);
2011 * Some instances of the old code considered this a failure,
2012 * some others didn't. What is the right thing to do here?
2014 free_tlist(expansion
);
2015 return false; /* Failure */
2018 * We're redefining, so we have to take over an
2019 * existing SMacro structure. This means freeing
2020 * what was already in it.
2022 nasm_free(smac
->name
);
2023 free_tlist(smac
->expansion
);
2026 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2027 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
2028 smac
= nasm_malloc(sizeof(SMacro
));
2029 smac
->next
= *smhead
;
2032 smac
->name
= nasm_strdup(mname
);
2033 smac
->casesense
= casesense
;
2034 smac
->nparam
= nparam
;
2035 smac
->expansion
= expansion
;
2036 smac
->in_progress
= false;
2037 return true; /* Success */
2041 * Undefine an smacro
2043 static void undef_smacro(Context
*ctx
, const char *mname
)
2045 SMacro
**smhead
, *s
, **sp
;
2046 struct hash_table
*smtbl
;
2048 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2049 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2053 * We now have a macro name... go hunt for it.
2056 while ((s
= *sp
) != NULL
) {
2057 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2060 free_tlist(s
->expansion
);
2070 * Parse a mmacro specification.
2072 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2076 tline
= tline
->next
;
2078 tline
= expand_id(tline
);
2079 if (!tok_type_(tline
, TOK_ID
)) {
2080 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2085 def
->name
= nasm_strdup(tline
->text
);
2087 def
->nolist
= false;
2088 def
->in_progress
= 0;
2089 def
->rep_nest
= NULL
;
2090 def
->nparam_min
= 0;
2091 def
->nparam_max
= 0;
2093 tline
= expand_smacro(tline
->next
);
2095 if (!tok_type_(tline
, TOK_NUMBER
)) {
2096 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2098 def
->nparam_min
= def
->nparam_max
=
2099 readnum(tline
->text
, &err
);
2102 "unable to parse parameter count `%s'", tline
->text
);
2104 if (tline
&& tok_is_(tline
->next
, "-")) {
2105 tline
= tline
->next
->next
;
2106 if (tok_is_(tline
, "*")) {
2107 def
->nparam_max
= INT_MAX
;
2108 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2110 "`%s' expects a parameter count after `-'", directive
);
2112 def
->nparam_max
= readnum(tline
->text
, &err
);
2114 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2117 if (def
->nparam_min
> def
->nparam_max
) {
2118 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2122 if (tline
&& tok_is_(tline
->next
, "+")) {
2123 tline
= tline
->next
;
2126 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2127 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2128 tline
= tline
->next
;
2133 * Handle default parameters.
2135 if (tline
&& tline
->next
) {
2136 def
->dlist
= tline
->next
;
2138 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2141 def
->defaults
= NULL
;
2143 def
->expansion
= NULL
;
2145 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2147 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2148 "too many default macro parameters");
2155 * Decode a size directive
2157 static int parse_size(const char *str
) {
2158 static const char *size_names
[] =
2159 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2160 static const int sizes
[] =
2161 { 0, 1, 4, 16, 8, 10, 2, 32 };
2163 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2167 * find and process preprocessor directive in passed line
2168 * Find out if a line contains a preprocessor directive, and deal
2171 * If a directive _is_ found, it is the responsibility of this routine
2172 * (and not the caller) to free_tlist() the line.
2174 * @param tline a pointer to the current tokeninzed line linked list
2175 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2178 static int do_directive(Token
* tline
)
2180 enum preproc_token i
;
2193 MMacro
*mmac
, **mmhead
;
2194 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2196 struct tokenval tokval
;
2198 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2206 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2207 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2208 || tline
->text
[1] == '!'))
2209 return NO_DIRECTIVE_FOUND
;
2211 i
= pp_token_hash(tline
->text
);
2214 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2215 * since they are known to be buggy at moment, we need to fix them
2216 * in future release (2.09-2.10)
2218 if (i
== PP_RMACRO
|| i
== PP_RMACRO
|| i
== PP_EXITMACRO
) {
2219 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2221 return NO_DIRECTIVE_FOUND
;
2225 * If we're in a non-emitting branch of a condition construct,
2226 * or walking to the end of an already terminated %rep block,
2227 * we should ignore all directives except for condition
2230 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2231 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2232 return NO_DIRECTIVE_FOUND
;
2236 * If we're defining a macro or reading a %rep block, we should
2237 * ignore all directives except for %macro/%imacro (which nest),
2238 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2239 * If we're in a %rep block, another %rep nests, so should be let through.
2241 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2242 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2243 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2244 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2245 return NO_DIRECTIVE_FOUND
;
2249 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2250 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2252 return NO_DIRECTIVE_FOUND
;
2253 } else if (nested_mac_count
> 0) {
2254 if (i
== PP_ENDMACRO
) {
2256 return NO_DIRECTIVE_FOUND
;
2259 if (!defining
->name
) {
2262 return NO_DIRECTIVE_FOUND
;
2263 } else if (nested_rep_count
> 0) {
2264 if (i
== PP_ENDREP
) {
2266 return NO_DIRECTIVE_FOUND
;
2274 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2276 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2279 /* Directive to tell NASM what the default stack size is. The
2280 * default is for a 16-bit stack, and this can be overriden with
2283 tline
= tline
->next
;
2284 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2285 tline
= tline
->next
;
2286 if (!tline
|| tline
->type
!= TOK_ID
) {
2287 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2288 free_tlist(origline
);
2289 return DIRECTIVE_FOUND
;
2291 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2292 /* All subsequent ARG directives are for a 32-bit stack */
2294 StackPointer
= "ebp";
2297 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2298 /* All subsequent ARG directives are for a 64-bit stack */
2300 StackPointer
= "rbp";
2303 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2304 /* All subsequent ARG directives are for a 16-bit stack,
2305 * far function call.
2308 StackPointer
= "bp";
2311 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2312 /* All subsequent ARG directives are for a 16-bit stack,
2313 * far function call. We don't support near functions.
2316 StackPointer
= "bp";
2320 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2321 free_tlist(origline
);
2322 return DIRECTIVE_FOUND
;
2324 free_tlist(origline
);
2325 return DIRECTIVE_FOUND
;
2328 /* TASM like ARG directive to define arguments to functions, in
2329 * the following form:
2331 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2335 char *arg
, directive
[256];
2336 int size
= StackSize
;
2338 /* Find the argument name */
2339 tline
= tline
->next
;
2340 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2341 tline
= tline
->next
;
2342 if (!tline
|| tline
->type
!= TOK_ID
) {
2343 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2344 free_tlist(origline
);
2345 return DIRECTIVE_FOUND
;
2349 /* Find the argument size type */
2350 tline
= tline
->next
;
2351 if (!tline
|| tline
->type
!= TOK_OTHER
2352 || tline
->text
[0] != ':') {
2354 "Syntax error processing `%%arg' directive");
2355 free_tlist(origline
);
2356 return DIRECTIVE_FOUND
;
2358 tline
= tline
->next
;
2359 if (!tline
|| tline
->type
!= TOK_ID
) {
2360 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2361 free_tlist(origline
);
2362 return DIRECTIVE_FOUND
;
2365 /* Allow macro expansion of type parameter */
2366 tt
= tokenize(tline
->text
);
2367 tt
= expand_smacro(tt
);
2368 size
= parse_size(tt
->text
);
2371 "Invalid size type for `%%arg' missing directive");
2373 free_tlist(origline
);
2374 return DIRECTIVE_FOUND
;
2378 /* Round up to even stack slots */
2379 size
= ALIGN(size
, StackSize
);
2381 /* Now define the macro for the argument */
2382 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2383 arg
, StackPointer
, offset
);
2384 do_directive(tokenize(directive
));
2387 /* Move to the next argument in the list */
2388 tline
= tline
->next
;
2389 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2390 tline
= tline
->next
;
2391 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2393 free_tlist(origline
);
2394 return DIRECTIVE_FOUND
;
2397 /* TASM like LOCAL directive to define local variables for a
2398 * function, in the following form:
2400 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2402 * The '= LocalSize' at the end is ignored by NASM, but is
2403 * required by TASM to define the local parameter size (and used
2404 * by the TASM macro package).
2406 offset
= LocalOffset
;
2408 char *local
, directive
[256];
2409 int size
= StackSize
;
2411 /* Find the argument name */
2412 tline
= tline
->next
;
2413 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2414 tline
= tline
->next
;
2415 if (!tline
|| tline
->type
!= TOK_ID
) {
2417 "`%%local' missing argument parameter");
2418 free_tlist(origline
);
2419 return DIRECTIVE_FOUND
;
2421 local
= tline
->text
;
2423 /* Find the argument size type */
2424 tline
= tline
->next
;
2425 if (!tline
|| tline
->type
!= TOK_OTHER
2426 || tline
->text
[0] != ':') {
2428 "Syntax error processing `%%local' directive");
2429 free_tlist(origline
);
2430 return DIRECTIVE_FOUND
;
2432 tline
= tline
->next
;
2433 if (!tline
|| tline
->type
!= TOK_ID
) {
2435 "`%%local' missing size type parameter");
2436 free_tlist(origline
);
2437 return DIRECTIVE_FOUND
;
2440 /* Allow macro expansion of type parameter */
2441 tt
= tokenize(tline
->text
);
2442 tt
= expand_smacro(tt
);
2443 size
= parse_size(tt
->text
);
2446 "Invalid size type for `%%local' missing directive");
2448 free_tlist(origline
);
2449 return DIRECTIVE_FOUND
;
2453 /* Round up to even stack slots */
2454 size
= ALIGN(size
, StackSize
);
2456 offset
+= size
; /* Negative offset, increment before */
2458 /* Now define the macro for the argument */
2459 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2460 local
, StackPointer
, offset
);
2461 do_directive(tokenize(directive
));
2463 /* Now define the assign to setup the enter_c macro correctly */
2464 snprintf(directive
, sizeof(directive
),
2465 "%%assign %%$localsize %%$localsize+%d", size
);
2466 do_directive(tokenize(directive
));
2468 /* Move to the next argument in the list */
2469 tline
= tline
->next
;
2470 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2471 tline
= tline
->next
;
2472 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2473 LocalOffset
= offset
;
2474 free_tlist(origline
);
2475 return DIRECTIVE_FOUND
;
2479 error(ERR_WARNING
|ERR_PASS1
,
2480 "trailing garbage after `%%clear' ignored");
2483 free_tlist(origline
);
2484 return DIRECTIVE_FOUND
;
2487 t
= tline
->next
= expand_smacro(tline
->next
);
2489 if (!t
|| (t
->type
!= TOK_STRING
&&
2490 t
->type
!= TOK_INTERNAL_STRING
)) {
2491 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2492 free_tlist(origline
);
2493 return DIRECTIVE_FOUND
; /* but we did _something_ */
2496 error(ERR_WARNING
|ERR_PASS1
,
2497 "trailing garbage after `%%depend' ignored");
2499 if (t
->type
!= TOK_INTERNAL_STRING
)
2500 nasm_unquote_cstr(p
, i
);
2501 if (dephead
&& !in_list(*dephead
, p
)) {
2502 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2506 deptail
= &sl
->next
;
2508 free_tlist(origline
);
2509 return DIRECTIVE_FOUND
;
2512 t
= tline
->next
= expand_smacro(tline
->next
);
2515 if (!t
|| (t
->type
!= TOK_STRING
&&
2516 t
->type
!= TOK_INTERNAL_STRING
)) {
2517 error(ERR_NONFATAL
, "`%%include' expects a file name");
2518 free_tlist(origline
);
2519 return DIRECTIVE_FOUND
; /* but we did _something_ */
2522 error(ERR_WARNING
|ERR_PASS1
,
2523 "trailing garbage after `%%include' ignored");
2525 if (t
->type
!= TOK_INTERNAL_STRING
)
2526 nasm_unquote_cstr(p
, i
);
2527 inc
= nasm_malloc(sizeof(Include
));
2530 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2532 /* -MG given but file not found */
2535 inc
->fname
= src_set_fname(nasm_strdup(p
));
2536 inc
->lineno
= src_set_linnum(0);
2538 inc
->expansion
= NULL
;
2541 list
->uplevel(LIST_INCLUDE
);
2543 free_tlist(origline
);
2544 return DIRECTIVE_FOUND
;
2548 static macros_t
*use_pkg
;
2549 const char *pkg_macro
= NULL
;
2551 tline
= tline
->next
;
2553 tline
= expand_id(tline
);
2555 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2556 tline
->type
!= TOK_INTERNAL_STRING
&&
2557 tline
->type
!= TOK_ID
)) {
2558 error(ERR_NONFATAL
, "`%%use' expects a package name");
2559 free_tlist(origline
);
2560 return DIRECTIVE_FOUND
; /* but we did _something_ */
2563 error(ERR_WARNING
|ERR_PASS1
,
2564 "trailing garbage after `%%use' ignored");
2565 if (tline
->type
== TOK_STRING
)
2566 nasm_unquote_cstr(tline
->text
, i
);
2567 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2569 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2571 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2572 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2573 /* Not already included, go ahead and include it */
2574 stdmacpos
= use_pkg
;
2576 free_tlist(origline
);
2577 return DIRECTIVE_FOUND
;
2582 tline
= tline
->next
;
2584 tline
= expand_id(tline
);
2586 if (!tok_type_(tline
, TOK_ID
)) {
2587 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2589 free_tlist(origline
);
2590 return DIRECTIVE_FOUND
; /* but we did _something_ */
2593 error(ERR_WARNING
|ERR_PASS1
,
2594 "trailing garbage after `%s' ignored",
2596 p
= nasm_strdup(tline
->text
);
2598 p
= NULL
; /* Anonymous */
2602 ctx
= nasm_malloc(sizeof(Context
));
2604 hash_init(&ctx
->localmac
, HASH_SMALL
);
2606 ctx
->number
= unique
++;
2611 error(ERR_NONFATAL
, "`%s': context stack is empty",
2613 } else if (i
== PP_POP
) {
2614 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2615 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2617 cstk
->name
? cstk
->name
: "anonymous", p
);
2622 nasm_free(cstk
->name
);
2628 free_tlist(origline
);
2629 return DIRECTIVE_FOUND
;
2631 severity
= ERR_FATAL
;
2634 severity
= ERR_NONFATAL
;
2637 severity
= ERR_WARNING
|ERR_WARN_USER
;
2642 /* Only error out if this is the final pass */
2643 if (pass
!= 2 && i
!= PP_FATAL
)
2644 return DIRECTIVE_FOUND
;
2646 tline
->next
= expand_smacro(tline
->next
);
2647 tline
= tline
->next
;
2649 t
= tline
? tline
->next
: NULL
;
2651 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2652 /* The line contains only a quoted string */
2654 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2655 error(severity
, "%s", p
);
2657 /* Not a quoted string, or more than a quoted string */
2658 p
= detoken(tline
, false);
2659 error(severity
, "%s", p
);
2662 free_tlist(origline
);
2663 return DIRECTIVE_FOUND
;
2667 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2670 j
= if_condition(tline
->next
, i
);
2671 tline
->next
= NULL
; /* it got freed */
2672 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2674 cond
= nasm_malloc(sizeof(Cond
));
2675 cond
->next
= istk
->conds
;
2679 istk
->mstk
->condcnt
++;
2680 free_tlist(origline
);
2681 return DIRECTIVE_FOUND
;
2685 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2686 switch(istk
->conds
->state
) {
2688 istk
->conds
->state
= COND_DONE
;
2695 case COND_ELSE_TRUE
:
2696 case COND_ELSE_FALSE
:
2697 error_precond(ERR_WARNING
|ERR_PASS1
,
2698 "`%%elif' after `%%else' ignored");
2699 istk
->conds
->state
= COND_NEVER
;
2704 * IMPORTANT: In the case of %if, we will already have
2705 * called expand_mmac_params(); however, if we're
2706 * processing an %elif we must have been in a
2707 * non-emitting mode, which would have inhibited
2708 * the normal invocation of expand_mmac_params().
2709 * Therefore, we have to do it explicitly here.
2711 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2712 tline
->next
= NULL
; /* it got freed */
2713 istk
->conds
->state
=
2714 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2717 free_tlist(origline
);
2718 return DIRECTIVE_FOUND
;
2722 error_precond(ERR_WARNING
|ERR_PASS1
,
2723 "trailing garbage after `%%else' ignored");
2725 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2726 switch(istk
->conds
->state
) {
2729 istk
->conds
->state
= COND_ELSE_FALSE
;
2736 istk
->conds
->state
= COND_ELSE_TRUE
;
2739 case COND_ELSE_TRUE
:
2740 case COND_ELSE_FALSE
:
2741 error_precond(ERR_WARNING
|ERR_PASS1
,
2742 "`%%else' after `%%else' ignored.");
2743 istk
->conds
->state
= COND_NEVER
;
2746 free_tlist(origline
);
2747 return DIRECTIVE_FOUND
;
2751 error_precond(ERR_WARNING
|ERR_PASS1
,
2752 "trailing garbage after `%%endif' ignored");
2754 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2756 istk
->conds
= cond
->next
;
2759 istk
->mstk
->condcnt
--;
2760 free_tlist(origline
);
2761 return DIRECTIVE_FOUND
;
2768 error(ERR_FATAL
, "`%s': already defining a macro",
2770 return DIRECTIVE_FOUND
;
2772 defining
= nasm_malloc(sizeof(MMacro
));
2773 defining
->max_depth
=
2774 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2775 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2776 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2777 nasm_free(defining
);
2779 return DIRECTIVE_FOUND
;
2782 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2784 if (!strcmp(mmac
->name
, defining
->name
) &&
2785 (mmac
->nparam_min
<= defining
->nparam_max
2787 && (defining
->nparam_min
<= mmac
->nparam_max
2789 error(ERR_WARNING
|ERR_PASS1
,
2790 "redefining multi-line macro `%s'", defining
->name
);
2791 return DIRECTIVE_FOUND
;
2795 free_tlist(origline
);
2796 return DIRECTIVE_FOUND
;
2800 if (! (defining
&& defining
->name
)) {
2801 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2802 return DIRECTIVE_FOUND
;
2804 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2805 defining
->next
= *mmhead
;
2808 free_tlist(origline
);
2809 return DIRECTIVE_FOUND
;
2813 * We must search along istk->expansion until we hit a
2814 * macro-end marker for a macro with a name. Then we
2815 * bypass all lines between exitmacro and endmacro.
2817 list_for_each(l
, istk
->expansion
)
2818 if (l
->finishes
&& l
->finishes
->name
)
2823 * Remove all conditional entries relative to this
2824 * macro invocation. (safe to do in this context)
2826 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2828 istk
->conds
= cond
->next
;
2831 istk
->expansion
= l
;
2833 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2835 free_tlist(origline
);
2836 return DIRECTIVE_FOUND
;
2844 spec
.casesense
= (i
== PP_UNMACRO
);
2845 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2846 return DIRECTIVE_FOUND
;
2848 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2849 while (mmac_p
&& *mmac_p
) {
2851 if (mmac
->casesense
== spec
.casesense
&&
2852 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2853 mmac
->nparam_min
== spec
.nparam_min
&&
2854 mmac
->nparam_max
== spec
.nparam_max
&&
2855 mmac
->plus
== spec
.plus
) {
2856 *mmac_p
= mmac
->next
;
2859 mmac_p
= &mmac
->next
;
2862 free_tlist(origline
);
2863 free_tlist(spec
.dlist
);
2864 return DIRECTIVE_FOUND
;
2868 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2869 tline
= tline
->next
;
2871 free_tlist(origline
);
2872 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2873 return DIRECTIVE_FOUND
;
2875 t
= expand_smacro(tline
->next
);
2877 free_tlist(origline
);
2880 tokval
.t_type
= TOKEN_INVALID
;
2882 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2885 return DIRECTIVE_FOUND
;
2887 error(ERR_WARNING
|ERR_PASS1
,
2888 "trailing garbage after expression ignored");
2889 if (!is_simple(evalresult
)) {
2890 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2891 return DIRECTIVE_FOUND
;
2894 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2895 mmac
= mmac
->next_active
;
2897 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2898 } else if (mmac
->nparam
== 0) {
2900 "`%%rotate' invoked within macro without parameters");
2902 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2904 rotate
%= (int)mmac
->nparam
;
2906 rotate
+= mmac
->nparam
;
2908 mmac
->rotate
= rotate
;
2910 return DIRECTIVE_FOUND
;
2915 tline
= tline
->next
;
2916 } while (tok_type_(tline
, TOK_WHITESPACE
));
2918 if (tok_type_(tline
, TOK_ID
) &&
2919 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2922 tline
= tline
->next
;
2923 } while (tok_type_(tline
, TOK_WHITESPACE
));
2927 t
= expand_smacro(tline
);
2929 tokval
.t_type
= TOKEN_INVALID
;
2931 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2933 free_tlist(origline
);
2934 return DIRECTIVE_FOUND
;
2937 error(ERR_WARNING
|ERR_PASS1
,
2938 "trailing garbage after expression ignored");
2939 if (!is_simple(evalresult
)) {
2940 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2941 return DIRECTIVE_FOUND
;
2943 count
= reloc_value(evalresult
);
2944 if (count
>= REP_LIMIT
) {
2945 error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2950 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2953 free_tlist(origline
);
2955 tmp_defining
= defining
;
2956 defining
= nasm_malloc(sizeof(MMacro
));
2957 defining
->prev
= NULL
;
2958 defining
->name
= NULL
; /* flags this macro as a %rep block */
2959 defining
->casesense
= false;
2960 defining
->plus
= false;
2961 defining
->nolist
= nolist
;
2962 defining
->in_progress
= count
;
2963 defining
->max_depth
= 0;
2964 defining
->nparam_min
= defining
->nparam_max
= 0;
2965 defining
->defaults
= NULL
;
2966 defining
->dlist
= NULL
;
2967 defining
->expansion
= NULL
;
2968 defining
->next_active
= istk
->mstk
;
2969 defining
->rep_nest
= tmp_defining
;
2970 return DIRECTIVE_FOUND
;
2973 if (!defining
|| defining
->name
) {
2974 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2975 return DIRECTIVE_FOUND
;
2979 * Now we have a "macro" defined - although it has no name
2980 * and we won't be entering it in the hash tables - we must
2981 * push a macro-end marker for it on to istk->expansion.
2982 * After that, it will take care of propagating itself (a
2983 * macro-end marker line for a macro which is really a %rep
2984 * block will cause the macro to be re-expanded, complete
2985 * with another macro-end marker to ensure the process
2986 * continues) until the whole expansion is forcibly removed
2987 * from istk->expansion by a %exitrep.
2989 l
= nasm_malloc(sizeof(Line
));
2990 l
->next
= istk
->expansion
;
2991 l
->finishes
= defining
;
2993 istk
->expansion
= l
;
2995 istk
->mstk
= defining
;
2997 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2998 tmp_defining
= defining
;
2999 defining
= defining
->rep_nest
;
3000 free_tlist(origline
);
3001 return DIRECTIVE_FOUND
;
3005 * We must search along istk->expansion until we hit a
3006 * macro-end marker for a macro with no name. Then we set
3007 * its `in_progress' flag to 0.
3009 list_for_each(l
, istk
->expansion
)
3010 if (l
->finishes
&& !l
->finishes
->name
)
3014 l
->finishes
->in_progress
= 1;
3016 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
3017 free_tlist(origline
);
3018 return DIRECTIVE_FOUND
;
3024 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
3026 tline
= tline
->next
;
3028 tline
= expand_id(tline
);
3029 if (!tline
|| (tline
->type
!= TOK_ID
&&
3030 (tline
->type
!= TOK_PREPROC_ID
||
3031 tline
->text
[1] != '$'))) {
3032 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3034 free_tlist(origline
);
3035 return DIRECTIVE_FOUND
;
3038 ctx
= get_ctx(tline
->text
, &mname
, false);
3040 param_start
= tline
= tline
->next
;
3043 /* Expand the macro definition now for %xdefine and %ixdefine */
3044 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3045 tline
= expand_smacro(tline
);
3047 if (tok_is_(tline
, "(")) {
3049 * This macro has parameters.
3052 tline
= tline
->next
;
3056 error(ERR_NONFATAL
, "parameter identifier expected");
3057 free_tlist(origline
);
3058 return DIRECTIVE_FOUND
;
3060 if (tline
->type
!= TOK_ID
) {
3062 "`%s': parameter identifier expected",
3064 free_tlist(origline
);
3065 return DIRECTIVE_FOUND
;
3067 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3068 tline
= tline
->next
;
3070 if (tok_is_(tline
, ",")) {
3071 tline
= tline
->next
;
3073 if (!tok_is_(tline
, ")")) {
3075 "`)' expected to terminate macro template");
3076 free_tlist(origline
);
3077 return DIRECTIVE_FOUND
;
3083 tline
= tline
->next
;
3085 if (tok_type_(tline
, TOK_WHITESPACE
))
3086 last
= tline
, tline
= tline
->next
;
3091 if (t
->type
== TOK_ID
) {
3092 list_for_each(tt
, param_start
)
3093 if (tt
->type
>= TOK_SMAC_PARAM
&&
3094 !strcmp(tt
->text
, t
->text
))
3098 t
->next
= macro_start
;
3103 * Good. We now have a macro name, a parameter count, and a
3104 * token list (in reverse order) for an expansion. We ought
3105 * to be OK just to create an SMacro, store it, and let
3106 * free_tlist have the rest of the line (which we have
3107 * carefully re-terminated after chopping off the expansion
3110 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3111 free_tlist(origline
);
3112 return DIRECTIVE_FOUND
;
3115 tline
= tline
->next
;
3117 tline
= expand_id(tline
);
3118 if (!tline
|| (tline
->type
!= TOK_ID
&&
3119 (tline
->type
!= TOK_PREPROC_ID
||
3120 tline
->text
[1] != '$'))) {
3121 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3122 free_tlist(origline
);
3123 return DIRECTIVE_FOUND
;
3126 error(ERR_WARNING
|ERR_PASS1
,
3127 "trailing garbage after macro name ignored");
3130 /* Find the context that symbol belongs to */
3131 ctx
= get_ctx(tline
->text
, &mname
, false);
3132 undef_smacro(ctx
, mname
);
3133 free_tlist(origline
);
3134 return DIRECTIVE_FOUND
;
3138 casesense
= (i
== PP_DEFSTR
);
3140 tline
= tline
->next
;
3142 tline
= expand_id(tline
);
3143 if (!tline
|| (tline
->type
!= TOK_ID
&&
3144 (tline
->type
!= TOK_PREPROC_ID
||
3145 tline
->text
[1] != '$'))) {
3146 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3148 free_tlist(origline
);
3149 return DIRECTIVE_FOUND
;
3152 ctx
= get_ctx(tline
->text
, &mname
, false);
3154 tline
= expand_smacro(tline
->next
);
3157 while (tok_type_(tline
, TOK_WHITESPACE
))
3158 tline
= delete_Token(tline
);
3160 p
= detoken(tline
, false);
3161 macro_start
= nasm_malloc(sizeof(*macro_start
));
3162 macro_start
->next
= NULL
;
3163 macro_start
->text
= nasm_quote(p
, strlen(p
));
3164 macro_start
->type
= TOK_STRING
;
3165 macro_start
->a
.mac
= NULL
;
3169 * We now have a macro name, an implicit parameter count of
3170 * zero, and a string token to use as an expansion. Create
3171 * and store an SMacro.
3173 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3174 free_tlist(origline
);
3175 return DIRECTIVE_FOUND
;
3179 casesense
= (i
== PP_DEFTOK
);
3181 tline
= tline
->next
;
3183 tline
= expand_id(tline
);
3184 if (!tline
|| (tline
->type
!= TOK_ID
&&
3185 (tline
->type
!= TOK_PREPROC_ID
||
3186 tline
->text
[1] != '$'))) {
3188 "`%s' expects a macro identifier as first parameter",
3190 free_tlist(origline
);
3191 return DIRECTIVE_FOUND
;
3193 ctx
= get_ctx(tline
->text
, &mname
, false);
3195 tline
= expand_smacro(tline
->next
);
3199 while (tok_type_(t
, TOK_WHITESPACE
))
3201 /* t should now point to the string */
3202 if (!tok_type_(t
, TOK_STRING
)) {
3204 "`%s` requires string as second parameter",
3207 free_tlist(origline
);
3208 return DIRECTIVE_FOUND
;
3212 * Convert the string to a token stream. Note that smacros
3213 * are stored with the token stream reversed, so we have to
3214 * reverse the output of tokenize().
3216 nasm_unquote_cstr(t
->text
, i
);
3217 macro_start
= reverse_tokens(tokenize(t
->text
));
3220 * We now have a macro name, an implicit parameter count of
3221 * zero, and a numeric token to use as an expansion. Create
3222 * and store an SMacro.
3224 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3226 free_tlist(origline
);
3227 return DIRECTIVE_FOUND
;
3232 StrList
*xsl
= NULL
;
3233 StrList
**xst
= &xsl
;
3237 tline
= tline
->next
;
3239 tline
= expand_id(tline
);
3240 if (!tline
|| (tline
->type
!= TOK_ID
&&
3241 (tline
->type
!= TOK_PREPROC_ID
||
3242 tline
->text
[1] != '$'))) {
3244 "`%%pathsearch' expects a macro identifier as first parameter");
3245 free_tlist(origline
);
3246 return DIRECTIVE_FOUND
;
3248 ctx
= get_ctx(tline
->text
, &mname
, false);
3250 tline
= expand_smacro(tline
->next
);
3254 while (tok_type_(t
, TOK_WHITESPACE
))
3257 if (!t
|| (t
->type
!= TOK_STRING
&&
3258 t
->type
!= TOK_INTERNAL_STRING
)) {
3259 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3261 free_tlist(origline
);
3262 return DIRECTIVE_FOUND
; /* but we did _something_ */
3265 error(ERR_WARNING
|ERR_PASS1
,
3266 "trailing garbage after `%%pathsearch' ignored");
3268 if (t
->type
!= TOK_INTERNAL_STRING
)
3269 nasm_unquote(p
, NULL
);
3271 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3274 fclose(fp
); /* Don't actually care about the file */
3276 macro_start
= nasm_malloc(sizeof(*macro_start
));
3277 macro_start
->next
= NULL
;
3278 macro_start
->text
= nasm_quote(p
, strlen(p
));
3279 macro_start
->type
= TOK_STRING
;
3280 macro_start
->a
.mac
= NULL
;
3285 * We now have a macro name, an implicit parameter count of
3286 * zero, and a string token to use as an expansion. Create
3287 * and store an SMacro.
3289 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3291 free_tlist(origline
);
3292 return DIRECTIVE_FOUND
;
3298 tline
= tline
->next
;
3300 tline
= expand_id(tline
);
3301 if (!tline
|| (tline
->type
!= TOK_ID
&&
3302 (tline
->type
!= TOK_PREPROC_ID
||
3303 tline
->text
[1] != '$'))) {
3305 "`%%strlen' expects a macro identifier as first parameter");
3306 free_tlist(origline
);
3307 return DIRECTIVE_FOUND
;
3309 ctx
= get_ctx(tline
->text
, &mname
, false);
3311 tline
= expand_smacro(tline
->next
);
3315 while (tok_type_(t
, TOK_WHITESPACE
))
3317 /* t should now point to the string */
3318 if (!tok_type_(t
, TOK_STRING
)) {
3320 "`%%strlen` requires string as second parameter");
3322 free_tlist(origline
);
3323 return DIRECTIVE_FOUND
;
3326 macro_start
= nasm_malloc(sizeof(*macro_start
));
3327 macro_start
->next
= NULL
;
3328 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3329 macro_start
->a
.mac
= NULL
;
3332 * We now have a macro name, an implicit parameter count of
3333 * zero, and a numeric token to use as an expansion. Create
3334 * and store an SMacro.
3336 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3338 free_tlist(origline
);
3339 return DIRECTIVE_FOUND
;
3344 tline
= tline
->next
;
3346 tline
= expand_id(tline
);
3347 if (!tline
|| (tline
->type
!= TOK_ID
&&
3348 (tline
->type
!= TOK_PREPROC_ID
||
3349 tline
->text
[1] != '$'))) {
3351 "`%%strcat' expects a macro identifier as first parameter");
3352 free_tlist(origline
);
3353 return DIRECTIVE_FOUND
;
3355 ctx
= get_ctx(tline
->text
, &mname
, false);
3357 tline
= expand_smacro(tline
->next
);
3361 list_for_each(t
, tline
) {
3363 case TOK_WHITESPACE
:
3366 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3369 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3371 /* else fall through */
3374 "non-string passed to `%%strcat' (%d)", t
->type
);
3376 free_tlist(origline
);
3377 return DIRECTIVE_FOUND
;
3381 p
= pp
= nasm_malloc(len
);
3382 list_for_each(t
, tline
) {
3383 if (t
->type
== TOK_STRING
) {
3384 memcpy(p
, t
->text
, t
->a
.len
);
3390 * We now have a macro name, an implicit parameter count of
3391 * zero, and a numeric token to use as an expansion. Create
3392 * and store an SMacro.
3394 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3395 macro_start
->text
= nasm_quote(pp
, len
);
3397 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3399 free_tlist(origline
);
3400 return DIRECTIVE_FOUND
;
3404 int64_t start
, count
;
3409 tline
= tline
->next
;
3411 tline
= expand_id(tline
);
3412 if (!tline
|| (tline
->type
!= TOK_ID
&&
3413 (tline
->type
!= TOK_PREPROC_ID
||
3414 tline
->text
[1] != '$'))) {
3416 "`%%substr' expects a macro identifier as first parameter");
3417 free_tlist(origline
);
3418 return DIRECTIVE_FOUND
;
3420 ctx
= get_ctx(tline
->text
, &mname
, false);
3422 tline
= expand_smacro(tline
->next
);
3425 if (tline
) /* skip expanded id */
3427 while (tok_type_(t
, TOK_WHITESPACE
))
3430 /* t should now point to the string */
3431 if (!tok_type_(t
, TOK_STRING
)) {
3433 "`%%substr` requires string as second parameter");
3435 free_tlist(origline
);
3436 return DIRECTIVE_FOUND
;
3441 tokval
.t_type
= TOKEN_INVALID
;
3442 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3446 free_tlist(origline
);
3447 return DIRECTIVE_FOUND
;
3448 } else if (!is_simple(evalresult
)) {
3449 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3451 free_tlist(origline
);
3452 return DIRECTIVE_FOUND
;
3454 start
= evalresult
->value
- 1;
3456 while (tok_type_(tt
, TOK_WHITESPACE
))
3459 count
= 1; /* Backwards compatibility: one character */
3461 tokval
.t_type
= TOKEN_INVALID
;
3462 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3466 free_tlist(origline
);
3467 return DIRECTIVE_FOUND
;
3468 } else if (!is_simple(evalresult
)) {
3469 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3471 free_tlist(origline
);
3472 return DIRECTIVE_FOUND
;
3474 count
= evalresult
->value
;
3477 len
= nasm_unquote(t
->text
, NULL
);
3479 /* make start and count being in range */
3483 count
= len
+ count
+ 1 - start
;
3484 if (start
+ count
> (int64_t)len
)
3485 count
= len
- start
;
3486 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3487 start
= -1, count
= 0; /* empty string */
3489 macro_start
= nasm_malloc(sizeof(*macro_start
));
3490 macro_start
->next
= NULL
;
3491 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3492 macro_start
->type
= TOK_STRING
;
3493 macro_start
->a
.mac
= NULL
;
3496 * We now have a macro name, an implicit parameter count of
3497 * zero, and a numeric token to use as an expansion. Create
3498 * and store an SMacro.
3500 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3502 free_tlist(origline
);
3503 return DIRECTIVE_FOUND
;
3508 casesense
= (i
== PP_ASSIGN
);
3510 tline
= tline
->next
;
3512 tline
= expand_id(tline
);
3513 if (!tline
|| (tline
->type
!= TOK_ID
&&
3514 (tline
->type
!= TOK_PREPROC_ID
||
3515 tline
->text
[1] != '$'))) {
3517 "`%%%sassign' expects a macro identifier",
3518 (i
== PP_IASSIGN
? "i" : ""));
3519 free_tlist(origline
);
3520 return DIRECTIVE_FOUND
;
3522 ctx
= get_ctx(tline
->text
, &mname
, false);
3524 tline
= expand_smacro(tline
->next
);
3529 tokval
.t_type
= TOKEN_INVALID
;
3531 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3534 free_tlist(origline
);
3535 return DIRECTIVE_FOUND
;
3539 error(ERR_WARNING
|ERR_PASS1
,
3540 "trailing garbage after expression ignored");
3542 if (!is_simple(evalresult
)) {
3544 "non-constant value given to `%%%sassign'",
3545 (i
== PP_IASSIGN
? "i" : ""));
3546 free_tlist(origline
);
3547 return DIRECTIVE_FOUND
;
3550 macro_start
= nasm_malloc(sizeof(*macro_start
));
3551 macro_start
->next
= NULL
;
3552 make_tok_num(macro_start
, reloc_value(evalresult
));
3553 macro_start
->a
.mac
= NULL
;
3556 * We now have a macro name, an implicit parameter count of
3557 * zero, and a numeric token to use as an expansion. Create
3558 * and store an SMacro.
3560 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3561 free_tlist(origline
);
3562 return DIRECTIVE_FOUND
;
3566 * Syntax is `%line nnn[+mmm] [filename]'
3568 tline
= tline
->next
;
3570 if (!tok_type_(tline
, TOK_NUMBER
)) {
3571 error(ERR_NONFATAL
, "`%%line' expects line number");
3572 free_tlist(origline
);
3573 return DIRECTIVE_FOUND
;
3575 k
= readnum(tline
->text
, &err
);
3577 tline
= tline
->next
;
3578 if (tok_is_(tline
, "+")) {
3579 tline
= tline
->next
;
3580 if (!tok_type_(tline
, TOK_NUMBER
)) {
3581 error(ERR_NONFATAL
, "`%%line' expects line increment");
3582 free_tlist(origline
);
3583 return DIRECTIVE_FOUND
;
3585 m
= readnum(tline
->text
, &err
);
3586 tline
= tline
->next
;
3592 nasm_free(src_set_fname(detoken(tline
, false)));
3594 free_tlist(origline
);
3595 return DIRECTIVE_FOUND
;
3599 "preprocessor directive `%s' not yet implemented",
3601 return DIRECTIVE_FOUND
;
3606 * Ensure that a macro parameter contains a condition code and
3607 * nothing else. Return the condition code index if so, or -1
3610 static int find_cc(Token
* t
)
3616 return -1; /* Probably a %+ without a space */
3619 if (t
->type
!= TOK_ID
)
3623 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3627 j
= ARRAY_SIZE(conditions
);
3630 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3645 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3647 Token
**tail
, *t
, *tt
;
3649 bool did_paste
= false;
3652 /* Now handle token pasting... */
3655 while ((t
= *tail
) && (tt
= t
->next
)) {
3657 case TOK_WHITESPACE
:
3658 if (tt
->type
== TOK_WHITESPACE
) {
3659 /* Zap adjacent whitespace tokens */
3660 t
->next
= delete_Token(tt
);
3662 /* Do not advance paste_head here */
3667 case TOK_PREPROC_ID
:
3674 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3675 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3676 tt
->type
== TOK_OTHER
)) {
3677 len
+= strlen(tt
->text
);
3682 * Now tt points to the first token after
3683 * the potential paste area...
3685 if (tt
!= t
->next
) {
3686 /* We have at least two tokens... */
3687 len
+= strlen(t
->text
);
3688 p
= tmp
= nasm_malloc(len
+1);
3692 p
= strchr(p
, '\0');
3693 t
= delete_Token(t
);
3696 t
= *tail
= tokenize(tmp
);
3703 t
->next
= tt
; /* Attach the remaining token chain */
3711 case TOK_PASTE
: /* %+ */
3712 if (handle_paste_tokens
) {
3713 /* Zap %+ and whitespace tokens to the right */
3714 while (t
&& (t
->type
== TOK_WHITESPACE
||
3715 t
->type
== TOK_PASTE
))
3716 t
= *tail
= delete_Token(t
);
3717 if (!paste_head
|| !t
)
3718 break; /* Nothing to paste with */
3722 while (tok_type_(tt
, TOK_WHITESPACE
))
3723 tt
= t
->next
= delete_Token(tt
);
3726 tmp
= nasm_strcat(t
->text
, tt
->text
);
3728 tt
= delete_Token(tt
);
3729 t
= *tail
= tokenize(tmp
);
3735 t
->next
= tt
; /* Attach the remaining token chain */
3742 /* else fall through */
3745 if (!tok_type_(t
->next
, TOK_WHITESPACE
))
3754 * expands to a list of tokens from %{x:y}
3756 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3758 Token
*t
= tline
, **tt
, *tm
, *head
;
3762 pos
= strchr(tline
->text
, ':');
3765 lst
= atoi(pos
+ 1);
3766 fst
= atoi(tline
->text
+ 1);
3769 * only macros params are accounted so
3770 * if someone passes %0 -- we reject such
3773 if (lst
== 0 || fst
== 0)
3776 /* the values should be sane */
3777 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3778 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3781 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3782 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3784 /* counted from zero */
3788 * it will be at least one token
3790 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3791 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3792 head
= t
, tt
= &t
->next
;
3794 for (i
= fst
+ 1; i
<= lst
; i
++) {
3795 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3796 *tt
= t
, tt
= &t
->next
;
3797 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3798 tm
= mac
->params
[j
];
3799 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3800 *tt
= t
, tt
= &t
->next
;
3803 for (i
= fst
- 1; i
>= lst
; i
--) {
3804 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3805 *tt
= t
, tt
= &t
->next
;
3806 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3807 tm
= mac
->params
[j
];
3808 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3809 *tt
= t
, tt
= &t
->next
;
3817 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3823 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3824 * %-n) and MMacro-local identifiers (%%foo) as well as
3825 * macro indirection (%[...]) and range (%{..:..}).
3827 static Token
*expand_mmac_params(Token
* tline
)
3829 Token
*t
, *tt
, **tail
, *thead
;
3830 bool changed
= false;
3837 if (tline
->type
== TOK_PREPROC_ID
&&
3838 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3839 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3840 tline
->text
[1] == '%')) {
3842 int type
= 0, cc
; /* type = 0 to placate optimisers */
3849 tline
= tline
->next
;
3852 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3853 mac
= mac
->next_active
;
3855 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3857 pos
= strchr(t
->text
, ':');
3859 switch (t
->text
[1]) {
3861 * We have to make a substitution of one of the
3862 * forms %1, %-1, %+1, %%foo, %0.
3866 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3867 text
= nasm_strdup(tmpbuf
);
3871 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3873 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3876 n
= atoi(t
->text
+ 2) - 1;
3877 if (n
>= mac
->nparam
)
3880 if (mac
->nparam
> 1)
3881 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3882 tt
= mac
->params
[n
];
3887 "macro parameter %d is not a condition code",
3892 if (inverse_ccs
[cc
] == -1) {
3894 "condition code `%s' is not invertible",
3898 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3902 n
= atoi(t
->text
+ 2) - 1;
3903 if (n
>= mac
->nparam
)
3906 if (mac
->nparam
> 1)
3907 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3908 tt
= mac
->params
[n
];
3913 "macro parameter %d is not a condition code",
3918 text
= nasm_strdup(conditions
[cc
]);
3922 n
= atoi(t
->text
+ 1) - 1;
3923 if (n
>= mac
->nparam
)
3926 if (mac
->nparam
> 1)
3927 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3928 tt
= mac
->params
[n
];
3931 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3932 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3933 tail
= &(*tail
)->next
;
3937 text
= NULL
; /* we've done it here */
3942 * seems we have a parameters range here
3944 Token
*head
, **last
;
3945 head
= expand_mmac_params_range(mac
, t
, &last
);
3966 } else if (tline
->type
== TOK_INDIRECT
) {
3968 tline
= tline
->next
;
3969 tt
= tokenize(t
->text
);
3970 tt
= expand_mmac_params(tt
);
3971 tt
= expand_smacro(tt
);
3974 tt
->a
.mac
= NULL
; /* Necessary? */
3980 } else if (tline
->type
== TOK_PREPROC_ID
&&
3981 tline
->text
[0] == '%' &&
3982 tline
->text
[1] == '$' &&
3983 !tok_type_(tline
->next
, TOK_WHITESPACE
) &&
3984 (tok_type_(tline
->next
, TOK_ID
) ||
3985 tok_type_(tline
->next
, TOK_PREPROC_ID
) ||
3986 tok_type_(tline
->next
, TOK_NUMBER
) ||
3987 tok_type_(tline
->next
, TOK_OTHER
) ||
3988 tok_type_(tline
->next
, TOK_FLOAT
))) {
3990 * In a sake of backward compatibility we allow
3991 * to expand local single macro that early before
3992 * pasting token code have place
3994 * NOTE: that new code MUST use %+ macro to obtain
3998 tline
= tline
->next
;
3999 tt
= tokenize(t
->text
);
4000 tt
= expand_smacro(tt
);
4011 tline
= tline
->next
;
4019 paste_tokens(&thead
, false);
4025 * Expand all single-line macro calls made in the given line.
4026 * Return the expanded version of the line. The original is deemed
4027 * to be destroyed in the process. (In reality we'll just move
4028 * Tokens from input to output a lot of the time, rather than
4029 * actually bothering to destroy and replicate.)
4032 static Token
*expand_smacro(Token
* tline
)
4034 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4035 SMacro
*head
= NULL
, *m
;
4038 unsigned int nparam
, sparam
;
4040 Token
*org_tline
= tline
;
4043 int deadman
= DEADMAN_LIMIT
;
4047 * Trick: we should avoid changing the start token pointer since it can
4048 * be contained in "next" field of other token. Because of this
4049 * we allocate a copy of first token and work with it; at the end of
4050 * routine we copy it back
4053 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4054 org_tline
->text
, 0);
4055 tline
->a
.mac
= org_tline
->a
.mac
;
4056 nasm_free(org_tline
->text
);
4057 org_tline
->text
= NULL
;
4060 expanded
= true; /* Always expand %+ at least once */
4066 while (tline
) { /* main token loop */
4068 error(ERR_NONFATAL
, "interminable macro recursion");
4072 if ((mname
= tline
->text
)) {
4073 /* if this token is a local macro, look in local context */
4074 if (tline
->type
== TOK_ID
) {
4075 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4076 } else if (tline
->type
== TOK_PREPROC_ID
) {
4077 ctx
= get_ctx(mname
, &mname
, true);
4078 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4083 * We've hit an identifier. As in is_mmacro below, we first
4084 * check whether the identifier is a single-line macro at
4085 * all, then think about checking for parameters if
4088 list_for_each(m
, head
)
4089 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4095 if (m
->nparam
== 0) {
4097 * Simple case: the macro is parameterless. Discard the
4098 * one token that the macro call took, and push the
4099 * expansion back on the to-do stack.
4101 if (!m
->expansion
) {
4102 if (!strcmp("__FILE__", m
->name
)) {
4105 src_get(&num
, &file
);
4106 tline
->text
= nasm_quote(file
, strlen(file
));
4107 tline
->type
= TOK_STRING
;
4111 if (!strcmp("__LINE__", m
->name
)) {
4112 nasm_free(tline
->text
);
4113 make_tok_num(tline
, src_get_linnum());
4116 if (!strcmp("__BITS__", m
->name
)) {
4117 nasm_free(tline
->text
);
4118 make_tok_num(tline
, globalbits
);
4121 tline
= delete_Token(tline
);
4126 * Complicated case: at least one macro with this name
4127 * exists and takes parameters. We must find the
4128 * parameters in the call, count them, find the SMacro
4129 * that corresponds to that form of the macro call, and
4130 * substitute for the parameters when we expand. What a
4133 /*tline = tline->next;
4134 skip_white_(tline); */
4137 while (tok_type_(t
, TOK_SMAC_END
)) {
4138 t
->a
.mac
->in_progress
= false;
4140 t
= tline
->next
= delete_Token(t
);
4143 } while (tok_type_(tline
, TOK_WHITESPACE
));
4144 if (!tok_is_(tline
, "(")) {
4146 * This macro wasn't called with parameters: ignore
4147 * the call. (Behaviour borrowed from gnu cpp.)
4156 sparam
= PARAM_DELTA
;
4157 params
= nasm_malloc(sparam
* sizeof(Token
*));
4158 params
[0] = tline
->next
;
4159 paramsize
= nasm_malloc(sparam
* sizeof(int));
4161 while (true) { /* parameter loop */
4163 * For some unusual expansions
4164 * which concatenates function call
4167 while (tok_type_(t
, TOK_SMAC_END
)) {
4168 t
->a
.mac
->in_progress
= false;
4170 t
= tline
->next
= delete_Token(t
);
4176 "macro call expects terminating `)'");
4179 if (tline
->type
== TOK_WHITESPACE
4181 if (paramsize
[nparam
])
4184 params
[nparam
] = tline
->next
;
4185 continue; /* parameter loop */
4187 if (tline
->type
== TOK_OTHER
4188 && tline
->text
[1] == 0) {
4189 char ch
= tline
->text
[0];
4190 if (ch
== ',' && !paren
&& brackets
<= 0) {
4191 if (++nparam
>= sparam
) {
4192 sparam
+= PARAM_DELTA
;
4193 params
= nasm_realloc(params
,
4194 sparam
* sizeof(Token
*));
4195 paramsize
= nasm_realloc(paramsize
,
4196 sparam
* sizeof(int));
4198 params
[nparam
] = tline
->next
;
4199 paramsize
[nparam
] = 0;
4201 continue; /* parameter loop */
4204 (brackets
> 0 || (brackets
== 0 &&
4205 !paramsize
[nparam
])))
4207 if (!(brackets
++)) {
4208 params
[nparam
] = tline
->next
;
4209 continue; /* parameter loop */
4212 if (ch
== '}' && brackets
> 0)
4213 if (--brackets
== 0) {
4215 continue; /* parameter loop */
4217 if (ch
== '(' && !brackets
)
4219 if (ch
== ')' && brackets
<= 0)
4225 error(ERR_NONFATAL
, "braces do not "
4226 "enclose all of macro parameter");
4228 paramsize
[nparam
] += white
+ 1;
4230 } /* parameter loop */
4232 while (m
&& (m
->nparam
!= nparam
||
4233 mstrcmp(m
->name
, mname
,
4237 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4238 "macro `%s' exists, "
4239 "but not taking %d parameters",
4240 mstart
->text
, nparam
);
4243 if (m
&& m
->in_progress
)
4245 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4247 * Design question: should we handle !tline, which
4248 * indicates missing ')' here, or expand those
4249 * macros anyway, which requires the (t) test a few
4253 nasm_free(paramsize
);
4257 * Expand the macro: we are placed on the last token of the
4258 * call, so that we can easily split the call from the
4259 * following tokens. We also start by pushing an SMAC_END
4260 * token for the cycle removal.
4267 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4269 m
->in_progress
= true;
4271 list_for_each(t
, m
->expansion
) {
4272 if (t
->type
>= TOK_SMAC_PARAM
) {
4273 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4277 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4278 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4280 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4286 } else if (t
->type
== TOK_PREPROC_Q
) {
4287 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4289 } else if (t
->type
== TOK_PREPROC_QQ
) {
4290 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4293 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4299 * Having done that, get rid of the macro call, and clean
4300 * up the parameters.
4303 nasm_free(paramsize
);
4306 continue; /* main token loop */
4311 if (tline
->type
== TOK_SMAC_END
) {
4312 tline
->a
.mac
->in_progress
= false;
4313 tline
= delete_Token(tline
);
4316 tline
= tline
->next
;
4324 * Now scan the entire line and look for successive TOK_IDs that resulted
4325 * after expansion (they can't be produced by tokenize()). The successive
4326 * TOK_IDs should be concatenated.
4327 * Also we look for %+ tokens and concatenate the tokens before and after
4328 * them (without white spaces in between).
4330 if (expanded
&& paste_tokens(&thead
, true)) {
4332 * If we concatenated something, *and* we had previously expanded
4333 * an actual macro, scan the lines again for macros...
4343 *org_tline
= *thead
;
4344 /* since we just gave text to org_line, don't free it */
4346 delete_Token(thead
);
4348 /* the expression expanded to empty line;
4349 we can't return NULL for some reasons
4350 we just set the line to a single WHITESPACE token. */
4351 memset(org_tline
, 0, sizeof(*org_tline
));
4352 org_tline
->text
= NULL
;
4353 org_tline
->type
= TOK_WHITESPACE
;
4362 * Similar to expand_smacro but used exclusively with macro identifiers
4363 * right before they are fetched in. The reason is that there can be
4364 * identifiers consisting of several subparts. We consider that if there
4365 * are more than one element forming the name, user wants a expansion,
4366 * otherwise it will be left as-is. Example:
4370 * the identifier %$abc will be left as-is so that the handler for %define
4371 * will suck it and define the corresponding value. Other case:
4373 * %define _%$abc cde
4375 * In this case user wants name to be expanded *before* %define starts
4376 * working, so we'll expand %$abc into something (if it has a value;
4377 * otherwise it will be left as-is) then concatenate all successive
4380 static Token
*expand_id(Token
* tline
)
4382 Token
*cur
, *oldnext
= NULL
;
4384 if (!tline
|| !tline
->next
)
4389 (cur
->next
->type
== TOK_ID
||
4390 cur
->next
->type
== TOK_PREPROC_ID
4391 || cur
->next
->type
== TOK_NUMBER
))
4394 /* If identifier consists of just one token, don't expand */
4399 oldnext
= cur
->next
; /* Detach the tail past identifier */
4400 cur
->next
= NULL
; /* so that expand_smacro stops here */
4403 tline
= expand_smacro(tline
);
4406 /* expand_smacro possibly changhed tline; re-scan for EOL */
4408 while (cur
&& cur
->next
)
4411 cur
->next
= oldnext
;
4418 * Determine whether the given line constitutes a multi-line macro
4419 * call, and return the MMacro structure called if so. Doesn't have
4420 * to check for an initial label - that's taken care of in
4421 * expand_mmacro - but must check numbers of parameters. Guaranteed
4422 * to be called with tline->type == TOK_ID, so the putative macro
4423 * name is easy to find.
4425 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4431 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4434 * Efficiency: first we see if any macro exists with the given
4435 * name. If not, we can return NULL immediately. _Then_ we
4436 * count the parameters, and then we look further along the
4437 * list if necessary to find the proper MMacro.
4439 list_for_each(m
, head
)
4440 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4446 * OK, we have a potential macro. Count and demarcate the
4449 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4452 * So we know how many parameters we've got. Find the MMacro
4453 * structure that handles this number.
4456 if (m
->nparam_min
<= nparam
4457 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4459 * This one is right. Just check if cycle removal
4460 * prohibits us using it before we actually celebrate...
4462 if (m
->in_progress
> m
->max_depth
) {
4463 if (m
->max_depth
> 0) {
4465 "reached maximum recursion depth of %i",
4472 * It's right, and we can use it. Add its default
4473 * parameters to the end of our list if necessary.
4475 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4477 nasm_realloc(params
,
4478 ((m
->nparam_min
+ m
->ndefs
+
4479 1) * sizeof(*params
)));
4480 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4481 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4486 * If we've gone over the maximum parameter count (and
4487 * we're in Plus mode), ignore parameters beyond
4490 if (m
->plus
&& nparam
> m
->nparam_max
)
4491 nparam
= m
->nparam_max
;
4493 * Then terminate the parameter list, and leave.
4495 if (!params
) { /* need this special case */
4496 params
= nasm_malloc(sizeof(*params
));
4499 params
[nparam
] = NULL
;
4500 *params_array
= params
;
4504 * This one wasn't right: look for the next one with the
4507 list_for_each(m
, m
->next
)
4508 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4513 * After all that, we didn't find one with the right number of
4514 * parameters. Issue a warning, and fail to expand the macro.
4516 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4517 "macro `%s' exists, but not taking %d parameters",
4518 tline
->text
, nparam
);
4525 * Save MMacro invocation specific fields in
4526 * preparation for a recursive macro expansion
4528 static void push_mmacro(MMacro
*m
)
4530 MMacroInvocation
*i
;
4532 i
= nasm_malloc(sizeof(MMacroInvocation
));
4534 i
->params
= m
->params
;
4535 i
->iline
= m
->iline
;
4536 i
->nparam
= m
->nparam
;
4537 i
->rotate
= m
->rotate
;
4538 i
->paramlen
= m
->paramlen
;
4539 i
->unique
= m
->unique
;
4540 i
->condcnt
= m
->condcnt
;
4546 * Restore MMacro invocation specific fields that were
4547 * saved during a previous recursive macro expansion
4549 static void pop_mmacro(MMacro
*m
)
4551 MMacroInvocation
*i
;
4556 m
->params
= i
->params
;
4557 m
->iline
= i
->iline
;
4558 m
->nparam
= i
->nparam
;
4559 m
->rotate
= i
->rotate
;
4560 m
->paramlen
= i
->paramlen
;
4561 m
->unique
= i
->unique
;
4562 m
->condcnt
= i
->condcnt
;
4569 * Expand the multi-line macro call made by the given line, if
4570 * there is one to be expanded. If there is, push the expansion on
4571 * istk->expansion and return 1. Otherwise return 0.
4573 static int expand_mmacro(Token
* tline
)
4575 Token
*startline
= tline
;
4576 Token
*label
= NULL
;
4577 int dont_prepend
= 0;
4578 Token
**params
, *t
, *mtok
, *tt
;
4581 int i
, nparam
, *paramlen
;
4586 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4587 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4590 m
= is_mmacro(t
, ¶ms
);
4596 * We have an id which isn't a macro call. We'll assume
4597 * it might be a label; we'll also check to see if a
4598 * colon follows it. Then, if there's another id after
4599 * that lot, we'll check it again for macro-hood.
4603 if (tok_type_(t
, TOK_WHITESPACE
))
4604 last
= t
, t
= t
->next
;
4605 if (tok_is_(t
, ":")) {
4607 last
= t
, t
= t
->next
;
4608 if (tok_type_(t
, TOK_WHITESPACE
))
4609 last
= t
, t
= t
->next
;
4611 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4619 * Fix up the parameters: this involves stripping leading and
4620 * trailing whitespace, then stripping braces if they are
4623 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4624 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4626 for (i
= 0; params
[i
]; i
++) {
4628 int comma
= (!m
->plus
|| i
< nparam
- 1);
4632 if (tok_is_(t
, "{"))
4633 t
= t
->next
, brace
= true, comma
= false;
4637 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4638 break; /* ... because we have hit a comma */
4639 if (comma
&& t
->type
== TOK_WHITESPACE
4640 && tok_is_(t
->next
, ","))
4641 break; /* ... or a space then a comma */
4642 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4643 break; /* ... or a brace */
4650 * OK, we have a MMacro structure together with a set of
4651 * parameters. We must now go through the expansion and push
4652 * copies of each Line on to istk->expansion. Substitution of
4653 * parameter tokens and macro-local tokens doesn't get done
4654 * until the single-line macro substitution process; this is
4655 * because delaying them allows us to change the semantics
4656 * later through %rotate.
4658 * First, push an end marker on to istk->expansion, mark this
4659 * macro as in progress, and set up its invocation-specific
4662 ll
= nasm_malloc(sizeof(Line
));
4663 ll
->next
= istk
->expansion
;
4666 istk
->expansion
= ll
;
4669 * Save the previous MMacro expansion in the case of
4672 if (m
->max_depth
&& m
->in_progress
)
4680 m
->paramlen
= paramlen
;
4681 m
->unique
= unique
++;
4685 m
->next_active
= istk
->mstk
;
4688 list_for_each(l
, m
->expansion
) {
4691 ll
= nasm_malloc(sizeof(Line
));
4692 ll
->finishes
= NULL
;
4693 ll
->next
= istk
->expansion
;
4694 istk
->expansion
= ll
;
4697 list_for_each(t
, l
->first
) {
4701 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4703 case TOK_PREPROC_QQ
:
4704 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4706 case TOK_PREPROC_ID
:
4707 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4715 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4724 * If we had a label, push it on as the first line of
4725 * the macro expansion.
4728 if (dont_prepend
< 0)
4729 free_tlist(startline
);
4731 ll
= nasm_malloc(sizeof(Line
));
4732 ll
->finishes
= NULL
;
4733 ll
->next
= istk
->expansion
;
4734 istk
->expansion
= ll
;
4735 ll
->first
= startline
;
4736 if (!dont_prepend
) {
4738 label
= label
->next
;
4739 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4744 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4749 /* The function that actually does the error reporting */
4750 static void verror(int severity
, const char *fmt
, va_list arg
)
4753 MMacro
*mmac
= NULL
;
4756 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4758 /* get %macro name */
4759 if (istk
&& istk
->mstk
) {
4761 /* but %rep blocks should be skipped */
4762 while (mmac
&& !mmac
->name
)
4763 mmac
= mmac
->next_active
, delta
++;
4767 nasm_error(severity
, "(%s:%d) %s",
4768 mmac
->name
, mmac
->lineno
- delta
, buff
);
4770 nasm_error(severity
, "%s", buff
);
4774 * Since preprocessor always operate only on the line that didn't
4775 * arrived yet, we should always use ERR_OFFBY1.
4777 static void error(int severity
, const char *fmt
, ...)
4781 /* If we're in a dead branch of IF or something like it, ignore the error */
4782 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4786 verror(severity
, fmt
, arg
);
4791 * Because %else etc are evaluated in the state context
4792 * of the previous branch, errors might get lost with error():
4793 * %if 0 ... %else trailing garbage ... %endif
4794 * So %else etc should report errors with this function.
4796 static void error_precond(int severity
, const char *fmt
, ...)
4800 /* Only ignore the error if it's really in a dead branch */
4801 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4805 verror(severity
, fmt
, arg
);
4810 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4815 istk
= nasm_malloc(sizeof(Include
));
4818 istk
->expansion
= NULL
;
4820 istk
->fp
= fopen(file
, "r");
4822 src_set_fname(nasm_strdup(file
));
4826 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4829 nested_mac_count
= 0;
4830 nested_rep_count
= 0;
4833 if (tasm_compatible_mode
) {
4834 stdmacpos
= nasm_stdmac
;
4836 stdmacpos
= nasm_stdmac_after_tasm
;
4838 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4843 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4844 * The caller, however, will also pass in 3 for preprocess-only so
4845 * we can set __PASS__ accordingly.
4847 pass
= apass
> 2 ? 2 : apass
;
4849 dephead
= deptail
= deplist
;
4851 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4853 strcpy(sl
->str
, file
);
4855 deptail
= &sl
->next
;
4859 * Define the __PASS__ macro. This is defined here unlike
4860 * all the other builtins, because it is special -- it varies between
4863 t
= nasm_malloc(sizeof(*t
));
4865 make_tok_num(t
, apass
);
4867 define_smacro(NULL
, "__PASS__", true, 0, t
);
4870 static char *pp_getline(void)
4877 * Fetch a tokenized line, either from the macro-expansion
4878 * buffer or from the input file.
4881 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4882 Line
*l
= istk
->expansion
;
4883 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4887 * This is a macro-end marker for a macro with no
4888 * name, which means it's not really a macro at all
4889 * but a %rep block, and the `in_progress' field is
4890 * more than 1, meaning that we still need to
4891 * repeat. (1 means the natural last repetition; 0
4892 * means termination by %exitrep.) We have
4893 * therefore expanded up to the %endrep, and must
4894 * push the whole block on to the expansion buffer
4895 * again. We don't bother to remove the macro-end
4896 * marker: we'd only have to generate another one
4899 l
->finishes
->in_progress
--;
4900 list_for_each(l
, l
->finishes
->expansion
) {
4901 Token
*t
, *tt
, **tail
;
4903 ll
= nasm_malloc(sizeof(Line
));
4904 ll
->next
= istk
->expansion
;
4905 ll
->finishes
= NULL
;
4909 list_for_each(t
, l
->first
) {
4910 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4911 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4916 istk
->expansion
= ll
;
4920 * Check whether a `%rep' was started and not ended
4921 * within this macro expansion. This can happen and
4922 * should be detected. It's a fatal error because
4923 * I'm too confused to work out how to recover
4929 "defining with name in expansion");
4930 else if (istk
->mstk
->name
)
4932 "`%%rep' without `%%endrep' within"
4933 " expansion of macro `%s'",
4938 * FIXME: investigate the relationship at this point between
4939 * istk->mstk and l->finishes
4942 MMacro
*m
= istk
->mstk
;
4943 istk
->mstk
= m
->next_active
;
4946 * This was a real macro call, not a %rep, and
4947 * therefore the parameter information needs to
4952 l
->finishes
->in_progress
--;
4954 nasm_free(m
->params
);
4955 free_tlist(m
->iline
);
4956 nasm_free(m
->paramlen
);
4957 l
->finishes
->in_progress
= 0;
4962 istk
->expansion
= l
->next
;
4964 list
->downlevel(LIST_MACRO
);
4967 while (1) { /* until we get a line we can use */
4969 if (istk
->expansion
) { /* from a macro expansion */
4971 Line
*l
= istk
->expansion
;
4973 istk
->mstk
->lineno
++;
4975 istk
->expansion
= l
->next
;
4977 p
= detoken(tline
, false);
4978 list
->line(LIST_MACRO
, p
);
4983 if (line
) { /* from the current input file */
4984 line
= prepreproc(line
);
4985 tline
= tokenize(line
);
4990 * The current file has ended; work down the istk
4996 /* nasm_error can't be conditionally suppressed */
4997 nasm_error(ERR_FATAL
,
4998 "expected `%%endif' before end of file");
5000 /* only set line and file name if there's a next node */
5002 src_set_linnum(i
->lineno
);
5003 nasm_free(src_set_fname(i
->fname
));
5006 list
->downlevel(LIST_INCLUDE
);
5010 if (istk
->expansion
&& istk
->expansion
->finishes
)
5016 * We must expand MMacro parameters and MMacro-local labels
5017 * _before_ we plunge into directive processing, to cope
5018 * with things like `%define something %1' such as STRUC
5019 * uses. Unless we're _defining_ a MMacro, in which case
5020 * those tokens should be left alone to go into the
5021 * definition; and unless we're in a non-emitting
5022 * condition, in which case we don't want to meddle with
5025 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
5026 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
5027 tline
= expand_mmac_params(tline
);
5031 * Check the line to see if it's a preprocessor directive.
5033 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5035 } else if (defining
) {
5037 * We're defining a multi-line macro. We emit nothing
5039 * shove the tokenized line on to the macro definition.
5041 Line
*l
= nasm_malloc(sizeof(Line
));
5042 l
->next
= defining
->expansion
;
5045 defining
->expansion
= l
;
5047 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
5049 * We're in a non-emitting branch of a condition block.
5050 * Emit nothing at all, not even a blank line: when we
5051 * emerge from the condition we'll give a line-number
5052 * directive so we keep our place correctly.
5056 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
5058 * We're in a %rep block which has been terminated, so
5059 * we're walking through to the %endrep without
5060 * emitting anything. Emit nothing at all, not even a
5061 * blank line: when we emerge from the %rep block we'll
5062 * give a line-number directive so we keep our place
5068 tline
= expand_smacro(tline
);
5069 if (!expand_mmacro(tline
)) {
5071 * De-tokenize the line again, and emit it.
5073 line
= detoken(tline
, true);
5077 continue; /* expand_mmacro calls free_tlist */
5085 static void pp_cleanup(int pass
)
5088 if (defining
->name
) {
5090 "end of file while still defining macro `%s'",
5093 error(ERR_NONFATAL
, "end of file while still in %%rep");
5096 free_mmacro(defining
);
5106 nasm_free(i
->fname
);
5111 nasm_free(src_set_fname(NULL
));
5116 while ((i
= ipath
)) {
5125 void pp_include_path(char *path
)
5129 i
= nasm_malloc(sizeof(IncPath
));
5130 i
->path
= path
? nasm_strdup(path
) : NULL
;
5143 void pp_pre_include(char *fname
)
5145 Token
*inc
, *space
, *name
;
5148 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5149 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5150 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5152 l
= nasm_malloc(sizeof(Line
));
5159 void pp_pre_define(char *definition
)
5165 equals
= strchr(definition
, '=');
5166 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5167 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5170 space
->next
= tokenize(definition
);
5174 l
= nasm_malloc(sizeof(Line
));
5181 void pp_pre_undefine(char *definition
)
5186 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5187 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5188 space
->next
= tokenize(definition
);
5190 l
= nasm_malloc(sizeof(Line
));
5198 * Added by Keith Kanios:
5200 * This function is used to assist with "runtime" preprocessor
5201 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5203 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5204 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5207 void pp_runtime(char *definition
)
5211 def
= tokenize(definition
);
5212 if (do_directive(def
) == NO_DIRECTIVE_FOUND
)
5217 void pp_extra_stdmac(macros_t
*macros
)
5219 extrastdmac
= macros
;
5222 static void make_tok_num(Token
* tok
, int64_t val
)
5225 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5226 tok
->text
= nasm_strdup(numbuf
);
5227 tok
->type
= TOK_NUMBER
;