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 * Condition codes. Note that we use c_ prefix not C_ because C_ is
331 * used in nasm.h for the "real" condition codes. At _this_ level,
332 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
333 * ones, so we need a different enum...
335 static const char * const conditions
[] = {
336 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
337 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
338 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
341 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
342 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
343 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
346 static const enum pp_conds inverse_ccs
[] = {
347 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
348 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
,
349 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
355 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
356 static int is_condition(enum preproc_token arg
)
358 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
361 /* For TASM compatibility we need to be able to recognise TASM compatible
362 * conditional compilation directives. Using the NASM pre-processor does
363 * not work, so we look for them specifically from the following list and
364 * then jam in the equivalent NASM directive into the input stream.
368 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
369 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
372 static const char * const tasm_directives
[] = {
373 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
374 "ifndef", "include", "local"
377 static int StackSize
= 4;
378 static char *StackPointer
= "ebp";
379 static int ArgOffset
= 8;
380 static int LocalOffset
= 0;
382 static Context
*cstk
;
383 static Include
*istk
;
384 static IncPath
*ipath
= NULL
;
386 static int pass
; /* HACK: pass 0 = generate dependencies only */
387 static StrList
**dephead
, **deptail
; /* Dependency list */
389 static uint64_t unique
; /* unique identifier numbers */
391 static Line
*predef
= NULL
;
392 static bool do_predef
;
394 static ListGen
*list
;
397 * The current set of multi-line macros we have defined.
399 static struct hash_table mmacros
;
402 * The current set of single-line macros we have defined.
404 static struct hash_table smacros
;
407 * The multi-line macro we are currently defining, or the %rep
408 * block we are currently reading, if any.
410 static MMacro
*defining
;
412 static uint64_t nested_mac_count
;
413 static uint64_t nested_rep_count
;
416 * The number of macro parameters to allocate space for at a time.
418 #define PARAM_DELTA 16
421 * The standard macro set: defined in macros.c in the array nasm_stdmac.
422 * This gives our position in the macro set, when we're processing it.
424 static macros_t
*stdmacpos
;
427 * The extra standard macros that come from the object format, if
430 static macros_t
*extrastdmac
= NULL
;
431 static bool any_extrastdmac
;
434 * Tokens are allocated in blocks to improve speed
436 #define TOKEN_BLOCKSIZE 4096
437 static Token
*freeTokens
= NULL
;
443 static Blocks blocks
= { NULL
, NULL
};
446 * Forward declarations.
448 static Token
*expand_mmac_params(Token
* tline
);
449 static Token
*expand_smacro(Token
* tline
);
450 static Token
*expand_id(Token
* tline
);
451 static Context
*get_ctx(const char *name
, const char **namep
,
453 static void make_tok_num(Token
* tok
, int64_t val
);
454 static void error(int severity
, const char *fmt
, ...);
455 static void error_precond(int severity
, const char *fmt
, ...);
456 static void *new_Block(size_t size
);
457 static void delete_Blocks(void);
458 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
459 const char *text
, int txtlen
);
460 static Token
*delete_Token(Token
* t
);
463 * Macros for safe checking of token pointers, avoid *(NULL)
465 #define tok_type_(x,t) ((x) && (x)->type == (t))
466 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
467 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
468 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
471 * nasm_unquote with error if the string contains NUL characters.
472 * If the string contains NUL characters, issue an error and return
473 * the C len, i.e. truncate at the NUL.
475 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
477 size_t len
= nasm_unquote(qstr
, NULL
);
478 size_t clen
= strlen(qstr
);
481 error(ERR_NONFATAL
, "NUL character in `%s' directive",
482 pp_directives
[directive
]);
488 * Handle TASM specific directives, which do not contain a % in
489 * front of them. We do it here because I could not find any other
490 * place to do it for the moment, and it is a hack (ideally it would
491 * be nice to be able to use the NASM pre-processor to do it).
493 static char *check_tasm_directive(char *line
)
495 int32_t i
, j
, k
, m
, len
;
496 char *p
, *q
, *oldline
, oldchar
;
498 p
= nasm_skip_spaces(line
);
500 /* Binary search for the directive name */
502 j
= ARRAY_SIZE(tasm_directives
);
503 q
= nasm_skip_word(p
);
510 m
= nasm_stricmp(p
, tasm_directives
[k
]);
512 /* We have found a directive, so jam a % in front of it
513 * so that NASM will then recognise it as one if it's own.
518 line
= nasm_malloc(len
+ 2);
520 if (k
== TM_IFDIFI
) {
522 * NASM does not recognise IFDIFI, so we convert
523 * it to %if 0. This is not used in NASM
524 * compatible code, but does need to parse for the
525 * TASM macro package.
527 strcpy(line
+ 1, "if 0");
529 memcpy(line
+ 1, p
, len
+ 1);
544 * The pre-preprocessing stage... This function translates line
545 * number indications as they emerge from GNU cpp (`# lineno "file"
546 * flags') into NASM preprocessor line number indications (`%line
549 static char *prepreproc(char *line
)
552 char *fname
, *oldline
;
554 if (line
[0] == '#' && line
[1] == ' ') {
557 lineno
= atoi(fname
);
558 fname
+= strspn(fname
, "0123456789 ");
561 fnlen
= strcspn(fname
, "\"");
562 line
= nasm_malloc(20 + fnlen
);
563 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
566 if (tasm_compatible_mode
)
567 return check_tasm_directive(line
);
572 * Free a linked list of tokens.
574 static void free_tlist(Token
* list
)
577 list
= delete_Token(list
);
581 * Free a linked list of lines.
583 static void free_llist(Line
* list
)
586 list_for_each_safe(l
, tmp
, list
) {
587 free_tlist(l
->first
);
595 static void free_mmacro(MMacro
* m
)
598 free_tlist(m
->dlist
);
599 nasm_free(m
->defaults
);
600 free_llist(m
->expansion
);
605 * Free all currently defined macros, and free the hash tables
607 static void free_smacro_table(struct hash_table
*smt
)
611 struct hash_tbl_node
*it
= NULL
;
613 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
614 nasm_free((void *)key
);
615 list_for_each_safe(s
, tmp
, s
) {
617 free_tlist(s
->expansion
);
624 static void free_mmacro_table(struct hash_table
*mmt
)
628 struct hash_tbl_node
*it
= NULL
;
631 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
632 nasm_free((void *)key
);
633 list_for_each_safe(m
,tmp
, m
)
639 static void free_macros(void)
641 free_smacro_table(&smacros
);
642 free_mmacro_table(&mmacros
);
646 * Initialize the hash tables
648 static void init_macros(void)
650 hash_init(&smacros
, HASH_LARGE
);
651 hash_init(&mmacros
, HASH_LARGE
);
655 * Pop the context stack.
657 static void ctx_pop(void)
662 free_smacro_table(&c
->localmac
);
668 * Search for a key in the hash index; adding it if necessary
669 * (in which case we initialize the data pointer to NULL.)
672 hash_findi_add(struct hash_table
*hash
, const char *str
)
674 struct hash_insert hi
;
678 r
= hash_findi(hash
, str
, &hi
);
682 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
683 return hash_add(&hi
, strx
, NULL
);
687 * Like hash_findi, but returns the data element rather than a pointer
688 * to it. Used only when not adding a new element, hence no third
692 hash_findix(struct hash_table
*hash
, const char *str
)
696 p
= hash_findi(hash
, str
, NULL
);
697 return p
? *p
: NULL
;
701 * read line from standart macros set,
702 * if there no more left -- return NULL
704 static char *line_from_stdmac(void)
707 const unsigned char *p
= stdmacpos
;
716 len
+= pp_directives_len
[c
- 0x80] + 1;
721 line
= nasm_malloc(len
+ 1);
723 while ((c
= *stdmacpos
++)) {
725 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
726 q
+= pp_directives_len
[c
- 0x80];
736 /* This was the last of the standard macro chain... */
738 if (any_extrastdmac
) {
739 stdmacpos
= extrastdmac
;
740 any_extrastdmac
= false;
741 } else if (do_predef
) {
743 Token
*head
, **tail
, *t
;
746 * Nasty hack: here we push the contents of
747 * `predef' on to the top-level expansion stack,
748 * since this is the most convenient way to
749 * implement the pre-include and pre-define
752 list_for_each(pd
, predef
) {
755 list_for_each(t
, pd
->first
) {
756 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
757 tail
= &(*tail
)->next
;
760 l
= nasm_malloc(sizeof(Line
));
761 l
->next
= istk
->expansion
;
774 #define BUF_DELTA 512
776 * Read a line from the top file in istk, handling multiple CR/LFs
777 * at the end of the line read, and handling spurious ^Zs. Will
778 * return lines from the standard macro set if this has not already
781 static char *read_line(void)
783 char *buffer
, *p
, *q
;
784 int bufsize
, continued_count
;
787 * standart macros set (predefined) goes first
789 p
= line_from_stdmac();
794 * regular read from a file
797 buffer
= nasm_malloc(BUF_DELTA
);
801 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
805 if (p
> buffer
&& p
[-1] == '\n') {
807 * Convert backslash-CRLF line continuation sequences into
808 * nothing at all (for DOS and Windows)
810 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
816 * Also convert backslash-LF line continuation sequences into
817 * nothing at all (for Unix)
819 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
827 if (p
- buffer
> bufsize
- 10) {
828 int32_t offset
= p
- buffer
;
829 bufsize
+= BUF_DELTA
;
830 buffer
= nasm_realloc(buffer
, bufsize
);
831 p
= buffer
+ offset
; /* prevent stale-pointer problems */
835 if (!q
&& p
== buffer
) {
840 src_set_linnum(src_get_linnum() + istk
->lineinc
+
841 (continued_count
* istk
->lineinc
));
844 * Play safe: remove CRs as well as LFs, if any of either are
845 * present at the end of the line.
847 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
851 * Handle spurious ^Z, which may be inserted into source files
852 * by some file transfer utilities.
854 buffer
[strcspn(buffer
, "\032")] = '\0';
856 list
->line(LIST_READ
, buffer
);
862 * Tokenize a line of text. This is a very simple process since we
863 * don't need to parse the value out of e.g. numeric tokens: we
864 * simply split one string into many.
866 static Token
*tokenize(char *line
)
869 enum pp_token_type type
;
871 Token
*t
, **tail
= &list
;
877 if (*p
== '+' && !nasm_isdigit(p
[1])) {
880 } else if (nasm_isdigit(*p
) ||
881 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
885 while (nasm_isdigit(*p
));
886 type
= TOK_PREPROC_ID
;
887 } else if (*p
== '{') {
889 while (*p
&& *p
!= '}') {
896 type
= TOK_PREPROC_ID
;
897 } else if (*p
== '[') {
899 line
+= 2; /* Skip the leading %[ */
901 while (lvl
&& (c
= *p
++)) {
913 p
= nasm_skip_string(p
- 1) + 1;
923 error(ERR_NONFATAL
, "unterminated %[ construct");
925 } else if (*p
== '?') {
926 type
= TOK_PREPROC_Q
; /* %? */
929 type
= TOK_PREPROC_QQ
; /* %?? */
932 } else if (*p
== '!') {
933 type
= TOK_PREPROC_ID
;
939 while (isidchar(*p
));
940 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
941 p
= nasm_skip_string(p
);
945 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
947 /* %! without string or identifier */
948 type
= TOK_OTHER
; /* Legacy behavior... */
950 } else if (isidchar(*p
) ||
951 ((*p
== '!' || *p
== '%' || *p
== '$') &&
956 while (isidchar(*p
));
957 type
= TOK_PREPROC_ID
;
963 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
966 while (*p
&& isidchar(*p
))
968 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
973 p
= nasm_skip_string(p
);
978 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
979 /* Handling unterminated strings by UNV */
982 } else if (p
[0] == '$' && p
[1] == '$') {
983 type
= TOK_OTHER
; /* TOKEN_BASE */
985 } else if (isnumstart(*p
)) {
987 bool is_float
= false;
1003 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1005 if (*p
== '+' || *p
== '-') {
1007 * e can only be followed by +/- if it is either a
1008 * prefixed hex number or a floating-point number
1013 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1015 } else if (c
== 'P' || c
== 'p') {
1017 if (*p
== '+' || *p
== '-')
1019 } else if (isnumchar(c
) || c
== '_')
1020 ; /* just advance */
1021 else if (c
== '.') {
1023 * we need to deal with consequences of the legacy
1024 * parser, like "1.nolist" being two tokens
1025 * (TOK_NUMBER, TOK_ID) here; at least give it
1026 * a shot for now. In the future, we probably need
1027 * a flex-based scanner with proper pattern matching
1028 * to do it as well as it can be done. Nothing in
1029 * the world is going to help the person who wants
1030 * 0x123.p16 interpreted as two tokens, though.
1036 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1037 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1038 (*r
== 'p' || *r
== 'P')) {
1042 break; /* Terminate the token */
1046 p
--; /* Point to first character beyond number */
1048 if (p
== line
+1 && *line
== '$') {
1049 type
= TOK_OTHER
; /* TOKEN_HERE */
1051 if (has_e
&& !is_hex
) {
1052 /* 1e13 is floating-point, but 1e13h is not */
1056 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1058 } else if (nasm_isspace(*p
)) {
1059 type
= TOK_WHITESPACE
;
1060 p
= nasm_skip_spaces(p
);
1062 * Whitespace just before end-of-line is discarded by
1063 * pretending it's a comment; whitespace just before a
1064 * comment gets lumped into the comment.
1066 if (!*p
|| *p
== ';') {
1071 } else if (*p
== ';') {
1077 * Anything else is an operator of some kind. We check
1078 * for all the double-character operators (>>, <<, //,
1079 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1080 * else is a single-character operator.
1083 if ((p
[0] == '>' && p
[1] == '>') ||
1084 (p
[0] == '<' && p
[1] == '<') ||
1085 (p
[0] == '/' && p
[1] == '/') ||
1086 (p
[0] == '<' && p
[1] == '=') ||
1087 (p
[0] == '>' && p
[1] == '=') ||
1088 (p
[0] == '=' && p
[1] == '=') ||
1089 (p
[0] == '!' && p
[1] == '=') ||
1090 (p
[0] == '<' && p
[1] == '>') ||
1091 (p
[0] == '&' && p
[1] == '&') ||
1092 (p
[0] == '|' && p
[1] == '|') ||
1093 (p
[0] == '^' && p
[1] == '^')) {
1099 /* Handling unterminated string by UNV */
1102 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1103 t->text[p-line] = *line;
1107 if (type
!= TOK_COMMENT
) {
1108 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1117 * this function allocates a new managed block of memory and
1118 * returns a pointer to the block. The managed blocks are
1119 * deleted only all at once by the delete_Blocks function.
1121 static void *new_Block(size_t size
)
1123 Blocks
*b
= &blocks
;
1125 /* first, get to the end of the linked list */
1128 /* now allocate the requested chunk */
1129 b
->chunk
= nasm_malloc(size
);
1131 /* now allocate a new block for the next request */
1132 b
->next
= nasm_malloc(sizeof(Blocks
));
1133 /* and initialize the contents of the new block */
1134 b
->next
->next
= NULL
;
1135 b
->next
->chunk
= NULL
;
1140 * this function deletes all managed blocks of memory
1142 static void delete_Blocks(void)
1144 Blocks
*a
, *b
= &blocks
;
1147 * keep in mind that the first block, pointed to by blocks
1148 * is a static and not dynamically allocated, so we don't
1153 nasm_free(b
->chunk
);
1162 * this function creates a new Token and passes a pointer to it
1163 * back to the caller. It sets the type and text elements, and
1164 * also the a.mac and next elements to NULL.
1166 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1167 const char *text
, int txtlen
)
1173 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1174 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1175 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1176 freeTokens
[i
].next
= NULL
;
1179 freeTokens
= t
->next
;
1183 if (type
== TOK_WHITESPACE
|| !text
) {
1187 txtlen
= strlen(text
);
1188 t
->text
= nasm_malloc(txtlen
+1);
1189 memcpy(t
->text
, text
, txtlen
);
1190 t
->text
[txtlen
] = '\0';
1195 static Token
*delete_Token(Token
* t
)
1197 Token
*next
= t
->next
;
1199 t
->next
= freeTokens
;
1205 * Convert a line of tokens back into text.
1206 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1207 * will be transformed into ..@ctxnum.xxx
1209 static char *detoken(Token
* tlist
, bool expand_locals
)
1216 list_for_each(t
, tlist
) {
1217 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1222 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1223 size_t len
= nasm_unquote(v
, NULL
);
1224 size_t clen
= strlen(v
);
1227 error(ERR_NONFATAL
| ERR_PASS1
,
1228 "NUL character in %! string");
1234 char *p
= getenv(v
);
1236 error(ERR_NONFATAL
| ERR_PASS1
,
1237 "nonexistent environment variable `%s'", v
);
1240 t
->text
= nasm_strdup(p
);
1245 /* Expand local macros here and not during preprocessing */
1246 if (expand_locals
&&
1247 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1248 t
->text
[0] == '%' && t
->text
[1] == '$') {
1251 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1254 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1255 p
= nasm_strcat(buffer
, q
);
1260 if (t
->type
== TOK_WHITESPACE
)
1263 len
+= strlen(t
->text
);
1266 p
= line
= nasm_malloc(len
+ 1);
1268 list_for_each(t
, tlist
) {
1269 if (t
->type
== TOK_WHITESPACE
) {
1271 } else if (t
->text
) {
1283 * A scanner, suitable for use by the expression evaluator, which
1284 * operates on a line of Tokens. Expects a pointer to a pointer to
1285 * the first token in the line to be passed in as its private_data
1288 * FIX: This really needs to be unified with stdscan.
1290 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1292 Token
**tlineptr
= private_data
;
1294 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1298 *tlineptr
= tline
? tline
->next
: NULL
;
1299 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1300 tline
->type
== TOK_COMMENT
));
1303 return tokval
->t_type
= TOKEN_EOS
;
1305 tokval
->t_charptr
= tline
->text
;
1307 if (tline
->text
[0] == '$' && !tline
->text
[1])
1308 return tokval
->t_type
= TOKEN_HERE
;
1309 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1310 return tokval
->t_type
= TOKEN_BASE
;
1312 if (tline
->type
== TOK_ID
) {
1313 p
= tokval
->t_charptr
= tline
->text
;
1315 tokval
->t_charptr
++;
1316 return tokval
->t_type
= TOKEN_ID
;
1319 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1320 if (r
>= p
+MAX_KEYWORD
)
1321 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1322 *s
++ = nasm_tolower(*r
);
1325 /* right, so we have an identifier sitting in temp storage. now,
1326 * is it actually a register or instruction name, or what? */
1327 return nasm_token_hash(ourcopy
, tokval
);
1330 if (tline
->type
== TOK_NUMBER
) {
1332 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1333 tokval
->t_charptr
= tline
->text
;
1335 return tokval
->t_type
= TOKEN_ERRNUM
;
1337 return tokval
->t_type
= TOKEN_NUM
;
1340 if (tline
->type
== TOK_FLOAT
) {
1341 return tokval
->t_type
= TOKEN_FLOAT
;
1344 if (tline
->type
== TOK_STRING
) {
1347 bq
= tline
->text
[0];
1348 tokval
->t_charptr
= tline
->text
;
1349 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1351 if (ep
[0] != bq
|| ep
[1] != '\0')
1352 return tokval
->t_type
= TOKEN_ERRSTR
;
1354 return tokval
->t_type
= TOKEN_STR
;
1357 if (tline
->type
== TOK_OTHER
) {
1358 if (!strcmp(tline
->text
, "<<"))
1359 return tokval
->t_type
= TOKEN_SHL
;
1360 if (!strcmp(tline
->text
, ">>"))
1361 return tokval
->t_type
= TOKEN_SHR
;
1362 if (!strcmp(tline
->text
, "//"))
1363 return tokval
->t_type
= TOKEN_SDIV
;
1364 if (!strcmp(tline
->text
, "%%"))
1365 return tokval
->t_type
= TOKEN_SMOD
;
1366 if (!strcmp(tline
->text
, "=="))
1367 return tokval
->t_type
= TOKEN_EQ
;
1368 if (!strcmp(tline
->text
, "<>"))
1369 return tokval
->t_type
= TOKEN_NE
;
1370 if (!strcmp(tline
->text
, "!="))
1371 return tokval
->t_type
= TOKEN_NE
;
1372 if (!strcmp(tline
->text
, "<="))
1373 return tokval
->t_type
= TOKEN_LE
;
1374 if (!strcmp(tline
->text
, ">="))
1375 return tokval
->t_type
= TOKEN_GE
;
1376 if (!strcmp(tline
->text
, "&&"))
1377 return tokval
->t_type
= TOKEN_DBL_AND
;
1378 if (!strcmp(tline
->text
, "^^"))
1379 return tokval
->t_type
= TOKEN_DBL_XOR
;
1380 if (!strcmp(tline
->text
, "||"))
1381 return tokval
->t_type
= TOKEN_DBL_OR
;
1385 * We have no other options: just return the first character of
1388 return tokval
->t_type
= tline
->text
[0];
1392 * Compare a string to the name of an existing macro; this is a
1393 * simple wrapper which calls either strcmp or nasm_stricmp
1394 * depending on the value of the `casesense' parameter.
1396 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1398 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1402 * Compare a string to the name of an existing macro; this is a
1403 * simple wrapper which calls either strcmp or nasm_stricmp
1404 * depending on the value of the `casesense' parameter.
1406 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1408 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1412 * Return the Context structure associated with a %$ token. Return
1413 * NULL, having _already_ reported an error condition, if the
1414 * context stack isn't deep enough for the supplied number of $
1416 * If all_contexts == true, contexts that enclose current are
1417 * also scanned for such smacro, until it is found; if not -
1418 * only the context that directly results from the number of $'s
1419 * in variable's name.
1421 * If "namep" is non-NULL, set it to the pointer to the macro name
1422 * tail, i.e. the part beyond %$...
1424 static Context
*get_ctx(const char *name
, const char **namep
,
1434 if (!name
|| name
[0] != '%' || name
[1] != '$')
1438 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1445 while (ctx
&& *name
== '$') {
1451 error(ERR_NONFATAL
, "`%s': context stack is only"
1452 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1463 /* Search for this smacro in found context */
1464 m
= hash_findix(&ctx
->localmac
, name
);
1466 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1477 * Check to see if a file is already in a string list
1479 static bool in_list(const StrList
*list
, const char *str
)
1482 if (!strcmp(list
->str
, str
))
1490 * Open an include file. This routine must always return a valid
1491 * file pointer if it returns - it's responsible for throwing an
1492 * ERR_FATAL and bombing out completely if not. It should also try
1493 * the include path one by one until it finds the file or reaches
1494 * the end of the path.
1496 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1501 IncPath
*ip
= ipath
;
1502 int len
= strlen(file
);
1503 size_t prefix_len
= 0;
1507 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1508 memcpy(sl
->str
, prefix
, prefix_len
);
1509 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1510 fp
= fopen(sl
->str
, "r");
1511 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1529 prefix_len
= strlen(prefix
);
1531 /* -MG given and file not found */
1532 if (dhead
&& !in_list(*dhead
, file
)) {
1533 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1535 strcpy(sl
->str
, file
);
1543 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1548 * Determine if we should warn on defining a single-line macro of
1549 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1550 * return true if _any_ single-line macro of that name is defined.
1551 * Otherwise, will return true if a single-line macro with either
1552 * `nparam' or no parameters is defined.
1554 * If a macro with precisely the right number of parameters is
1555 * defined, or nparam is -1, the address of the definition structure
1556 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1557 * is NULL, no action will be taken regarding its contents, and no
1560 * Note that this is also called with nparam zero to resolve
1563 * If you already know which context macro belongs to, you can pass
1564 * the context pointer as first parameter; if you won't but name begins
1565 * with %$ the context will be automatically computed. If all_contexts
1566 * is true, macro will be searched in outer contexts as well.
1569 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1572 struct hash_table
*smtbl
;
1576 smtbl
= &ctx
->localmac
;
1577 } else if (name
[0] == '%' && name
[1] == '$') {
1579 ctx
= get_ctx(name
, &name
, false);
1581 return false; /* got to return _something_ */
1582 smtbl
= &ctx
->localmac
;
1586 m
= (SMacro
*) hash_findix(smtbl
, name
);
1589 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1590 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1592 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1606 * Count and mark off the parameters in a multi-line macro call.
1607 * This is called both from within the multi-line macro expansion
1608 * code, and also to mark off the default parameters when provided
1609 * in a %macro definition line.
1611 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1613 int paramsize
, brace
;
1615 *nparam
= paramsize
= 0;
1618 /* +1: we need space for the final NULL */
1619 if (*nparam
+1 >= paramsize
) {
1620 paramsize
+= PARAM_DELTA
;
1621 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1625 if (tok_is_(t
, "{"))
1627 (*params
)[(*nparam
)++] = t
;
1628 while (tok_isnt_(t
, brace
? "}" : ","))
1630 if (t
) { /* got a comma/brace */
1634 * Now we've found the closing brace, look further
1638 if (tok_isnt_(t
, ",")) {
1640 "braces do not enclose all of macro parameter");
1641 while (tok_isnt_(t
, ","))
1645 t
= t
->next
; /* eat the comma */
1652 * Determine whether one of the various `if' conditions is true or
1655 * We must free the tline we get passed.
1657 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1659 enum pp_conditional i
= PP_COND(ct
);
1661 Token
*t
, *tt
, **tptr
, *origline
;
1662 struct tokenval tokval
;
1664 enum pp_token_type needtype
;
1671 j
= false; /* have we matched yet? */
1676 if (tline
->type
!= TOK_ID
) {
1678 "`%s' expects context identifiers", pp_directives
[ct
]);
1679 free_tlist(origline
);
1682 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1684 tline
= tline
->next
;
1689 j
= false; /* have we matched yet? */
1692 if (!tline
|| (tline
->type
!= TOK_ID
&&
1693 (tline
->type
!= TOK_PREPROC_ID
||
1694 tline
->text
[1] != '$'))) {
1696 "`%s' expects macro identifiers", pp_directives
[ct
]);
1699 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1701 tline
= tline
->next
;
1706 tline
= expand_smacro(tline
);
1707 j
= false; /* have we matched yet? */
1710 if (!tline
|| (tline
->type
!= TOK_ID
&&
1711 tline
->type
!= TOK_STRING
&&
1712 (tline
->type
!= TOK_PREPROC_ID
||
1713 tline
->text
[1] != '!'))) {
1715 "`%s' expects environment variable names",
1720 if (tline
->type
== TOK_PREPROC_ID
)
1721 p
+= 2; /* Skip leading %! */
1722 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1723 nasm_unquote_cstr(p
, ct
);
1726 tline
= tline
->next
;
1732 tline
= expand_smacro(tline
);
1734 while (tok_isnt_(tt
, ","))
1738 "`%s' expects two comma-separated arguments",
1743 j
= true; /* assume equality unless proved not */
1744 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1745 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1746 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1750 if (t
->type
== TOK_WHITESPACE
) {
1754 if (tt
->type
== TOK_WHITESPACE
) {
1758 if (tt
->type
!= t
->type
) {
1759 j
= false; /* found mismatching tokens */
1762 /* When comparing strings, need to unquote them first */
1763 if (t
->type
== TOK_STRING
) {
1764 size_t l1
= nasm_unquote(t
->text
, NULL
);
1765 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1771 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1775 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1776 j
= false; /* found mismatching tokens */
1783 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1784 j
= false; /* trailing gunk on one end or other */
1790 MMacro searching
, *mmac
;
1793 tline
= expand_id(tline
);
1794 if (!tok_type_(tline
, TOK_ID
)) {
1796 "`%s' expects a macro name", pp_directives
[ct
]);
1799 searching
.name
= nasm_strdup(tline
->text
);
1800 searching
.casesense
= true;
1801 searching
.plus
= false;
1802 searching
.nolist
= false;
1803 searching
.in_progress
= 0;
1804 searching
.max_depth
= 0;
1805 searching
.rep_nest
= NULL
;
1806 searching
.nparam_min
= 0;
1807 searching
.nparam_max
= INT_MAX
;
1808 tline
= expand_smacro(tline
->next
);
1811 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1813 "`%s' expects a parameter count or nothing",
1816 searching
.nparam_min
= searching
.nparam_max
=
1817 readnum(tline
->text
, &j
);
1820 "unable to parse parameter count `%s'",
1823 if (tline
&& tok_is_(tline
->next
, "-")) {
1824 tline
= tline
->next
->next
;
1825 if (tok_is_(tline
, "*"))
1826 searching
.nparam_max
= INT_MAX
;
1827 else if (!tok_type_(tline
, TOK_NUMBER
))
1829 "`%s' expects a parameter count after `-'",
1832 searching
.nparam_max
= readnum(tline
->text
, &j
);
1835 "unable to parse parameter count `%s'",
1837 if (searching
.nparam_min
> searching
.nparam_max
)
1839 "minimum parameter count exceeds maximum");
1842 if (tline
&& tok_is_(tline
->next
, "+")) {
1843 tline
= tline
->next
;
1844 searching
.plus
= true;
1846 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1848 if (!strcmp(mmac
->name
, searching
.name
) &&
1849 (mmac
->nparam_min
<= searching
.nparam_max
1851 && (searching
.nparam_min
<= mmac
->nparam_max
1858 if (tline
&& tline
->next
)
1859 error(ERR_WARNING
|ERR_PASS1
,
1860 "trailing garbage after %%ifmacro ignored");
1861 nasm_free(searching
.name
);
1870 needtype
= TOK_NUMBER
;
1873 needtype
= TOK_STRING
;
1877 t
= tline
= expand_smacro(tline
);
1879 while (tok_type_(t
, TOK_WHITESPACE
) ||
1880 (needtype
== TOK_NUMBER
&&
1881 tok_type_(t
, TOK_OTHER
) &&
1882 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1886 j
= tok_type_(t
, needtype
);
1890 t
= tline
= expand_smacro(tline
);
1891 while (tok_type_(t
, TOK_WHITESPACE
))
1896 t
= t
->next
; /* Skip the actual token */
1897 while (tok_type_(t
, TOK_WHITESPACE
))
1899 j
= !t
; /* Should be nothing left */
1904 t
= tline
= expand_smacro(tline
);
1905 while (tok_type_(t
, TOK_WHITESPACE
))
1908 j
= !t
; /* Should be empty */
1912 t
= tline
= expand_smacro(tline
);
1914 tokval
.t_type
= TOKEN_INVALID
;
1915 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1916 NULL
, pass
| CRITICAL
, error
, NULL
);
1920 error(ERR_WARNING
|ERR_PASS1
,
1921 "trailing garbage after expression ignored");
1922 if (!is_simple(evalresult
)) {
1924 "non-constant value given to `%s'", pp_directives
[ct
]);
1927 j
= reloc_value(evalresult
) != 0;
1932 "preprocessor directive `%s' not yet implemented",
1937 free_tlist(origline
);
1938 return j
^ PP_NEGATIVE(ct
);
1941 free_tlist(origline
);
1946 * Common code for defining an smacro
1948 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1949 int nparam
, Token
*expansion
)
1951 SMacro
*smac
, **smhead
;
1952 struct hash_table
*smtbl
;
1954 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1956 error(ERR_WARNING
|ERR_PASS1
,
1957 "single-line macro `%s' defined both with and"
1958 " without parameters", mname
);
1960 * Some instances of the old code considered this a failure,
1961 * some others didn't. What is the right thing to do here?
1963 free_tlist(expansion
);
1964 return false; /* Failure */
1967 * We're redefining, so we have to take over an
1968 * existing SMacro structure. This means freeing
1969 * what was already in it.
1971 nasm_free(smac
->name
);
1972 free_tlist(smac
->expansion
);
1975 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1976 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1977 smac
= nasm_malloc(sizeof(SMacro
));
1978 smac
->next
= *smhead
;
1981 smac
->name
= nasm_strdup(mname
);
1982 smac
->casesense
= casesense
;
1983 smac
->nparam
= nparam
;
1984 smac
->expansion
= expansion
;
1985 smac
->in_progress
= false;
1986 return true; /* Success */
1990 * Undefine an smacro
1992 static void undef_smacro(Context
*ctx
, const char *mname
)
1994 SMacro
**smhead
, *s
, **sp
;
1995 struct hash_table
*smtbl
;
1997 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1998 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2002 * We now have a macro name... go hunt for it.
2005 while ((s
= *sp
) != NULL
) {
2006 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2009 free_tlist(s
->expansion
);
2019 * Parse a mmacro specification.
2021 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2025 tline
= tline
->next
;
2027 tline
= expand_id(tline
);
2028 if (!tok_type_(tline
, TOK_ID
)) {
2029 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2034 def
->name
= nasm_strdup(tline
->text
);
2036 def
->nolist
= false;
2037 def
->in_progress
= 0;
2038 def
->rep_nest
= NULL
;
2039 def
->nparam_min
= 0;
2040 def
->nparam_max
= 0;
2042 tline
= expand_smacro(tline
->next
);
2044 if (!tok_type_(tline
, TOK_NUMBER
)) {
2045 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2047 def
->nparam_min
= def
->nparam_max
=
2048 readnum(tline
->text
, &err
);
2051 "unable to parse parameter count `%s'", tline
->text
);
2053 if (tline
&& tok_is_(tline
->next
, "-")) {
2054 tline
= tline
->next
->next
;
2055 if (tok_is_(tline
, "*")) {
2056 def
->nparam_max
= INT_MAX
;
2057 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2059 "`%s' expects a parameter count after `-'", directive
);
2061 def
->nparam_max
= readnum(tline
->text
, &err
);
2063 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2066 if (def
->nparam_min
> def
->nparam_max
) {
2067 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2071 if (tline
&& tok_is_(tline
->next
, "+")) {
2072 tline
= tline
->next
;
2075 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2076 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2077 tline
= tline
->next
;
2082 * Handle default parameters.
2084 if (tline
&& tline
->next
) {
2085 def
->dlist
= tline
->next
;
2087 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2090 def
->defaults
= NULL
;
2092 def
->expansion
= NULL
;
2094 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2096 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2097 "too many default macro parameters");
2104 * Decode a size directive
2106 static int parse_size(const char *str
) {
2107 static const char *size_names
[] =
2108 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2109 static const int sizes
[] =
2110 { 0, 1, 4, 16, 8, 10, 2, 32 };
2112 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2116 * find and process preprocessor directive in passed line
2117 * Find out if a line contains a preprocessor directive, and deal
2120 * If a directive _is_ found, it is the responsibility of this routine
2121 * (and not the caller) to free_tlist() the line.
2123 * @param tline a pointer to the current tokeninzed line linked list
2124 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2127 static int do_directive(Token
* tline
)
2129 enum preproc_token i
;
2142 MMacro
*mmac
, **mmhead
;
2143 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2145 struct tokenval tokval
;
2147 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2155 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2156 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2157 || tline
->text
[1] == '!'))
2158 return NO_DIRECTIVE_FOUND
;
2160 i
= pp_token_hash(tline
->text
);
2163 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2164 * since they are known to be buggy at moment, we need to fix them
2165 * in future release (2.09-2.10)
2167 if (i
== PP_RMACRO
|| i
== PP_RMACRO
|| i
== PP_EXITMACRO
) {
2168 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2170 return NO_DIRECTIVE_FOUND
;
2174 * If we're in a non-emitting branch of a condition construct,
2175 * or walking to the end of an already terminated %rep block,
2176 * we should ignore all directives except for condition
2179 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2180 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2181 return NO_DIRECTIVE_FOUND
;
2185 * If we're defining a macro or reading a %rep block, we should
2186 * ignore all directives except for %macro/%imacro (which nest),
2187 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2188 * If we're in a %rep block, another %rep nests, so should be let through.
2190 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2191 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2192 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2193 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2194 return NO_DIRECTIVE_FOUND
;
2198 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2199 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2201 return NO_DIRECTIVE_FOUND
;
2202 } else if (nested_mac_count
> 0) {
2203 if (i
== PP_ENDMACRO
) {
2205 return NO_DIRECTIVE_FOUND
;
2208 if (!defining
->name
) {
2211 return NO_DIRECTIVE_FOUND
;
2212 } else if (nested_rep_count
> 0) {
2213 if (i
== PP_ENDREP
) {
2215 return NO_DIRECTIVE_FOUND
;
2223 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2225 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2228 /* Directive to tell NASM what the default stack size is. The
2229 * default is for a 16-bit stack, and this can be overriden with
2232 tline
= tline
->next
;
2233 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2234 tline
= tline
->next
;
2235 if (!tline
|| tline
->type
!= TOK_ID
) {
2236 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2237 free_tlist(origline
);
2238 return DIRECTIVE_FOUND
;
2240 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2241 /* All subsequent ARG directives are for a 32-bit stack */
2243 StackPointer
= "ebp";
2246 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2247 /* All subsequent ARG directives are for a 64-bit stack */
2249 StackPointer
= "rbp";
2252 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2253 /* All subsequent ARG directives are for a 16-bit stack,
2254 * far function call.
2257 StackPointer
= "bp";
2260 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2261 /* All subsequent ARG directives are for a 16-bit stack,
2262 * far function call. We don't support near functions.
2265 StackPointer
= "bp";
2269 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2270 free_tlist(origline
);
2271 return DIRECTIVE_FOUND
;
2273 free_tlist(origline
);
2274 return DIRECTIVE_FOUND
;
2277 /* TASM like ARG directive to define arguments to functions, in
2278 * the following form:
2280 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2284 char *arg
, directive
[256];
2285 int size
= StackSize
;
2287 /* Find the argument name */
2288 tline
= tline
->next
;
2289 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2290 tline
= tline
->next
;
2291 if (!tline
|| tline
->type
!= TOK_ID
) {
2292 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2293 free_tlist(origline
);
2294 return DIRECTIVE_FOUND
;
2298 /* Find the argument size type */
2299 tline
= tline
->next
;
2300 if (!tline
|| tline
->type
!= TOK_OTHER
2301 || tline
->text
[0] != ':') {
2303 "Syntax error processing `%%arg' directive");
2304 free_tlist(origline
);
2305 return DIRECTIVE_FOUND
;
2307 tline
= tline
->next
;
2308 if (!tline
|| tline
->type
!= TOK_ID
) {
2309 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2310 free_tlist(origline
);
2311 return DIRECTIVE_FOUND
;
2314 /* Allow macro expansion of type parameter */
2315 tt
= tokenize(tline
->text
);
2316 tt
= expand_smacro(tt
);
2317 size
= parse_size(tt
->text
);
2320 "Invalid size type for `%%arg' missing directive");
2322 free_tlist(origline
);
2323 return DIRECTIVE_FOUND
;
2327 /* Round up to even stack slots */
2328 size
= ALIGN(size
, StackSize
);
2330 /* Now define the macro for the argument */
2331 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2332 arg
, StackPointer
, offset
);
2333 do_directive(tokenize(directive
));
2336 /* Move to the next argument in the list */
2337 tline
= tline
->next
;
2338 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2339 tline
= tline
->next
;
2340 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2342 free_tlist(origline
);
2343 return DIRECTIVE_FOUND
;
2346 /* TASM like LOCAL directive to define local variables for a
2347 * function, in the following form:
2349 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2351 * The '= LocalSize' at the end is ignored by NASM, but is
2352 * required by TASM to define the local parameter size (and used
2353 * by the TASM macro package).
2355 offset
= LocalOffset
;
2357 char *local
, directive
[256];
2358 int size
= StackSize
;
2360 /* Find the argument name */
2361 tline
= tline
->next
;
2362 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2363 tline
= tline
->next
;
2364 if (!tline
|| tline
->type
!= TOK_ID
) {
2366 "`%%local' missing argument parameter");
2367 free_tlist(origline
);
2368 return DIRECTIVE_FOUND
;
2370 local
= tline
->text
;
2372 /* Find the argument size type */
2373 tline
= tline
->next
;
2374 if (!tline
|| tline
->type
!= TOK_OTHER
2375 || tline
->text
[0] != ':') {
2377 "Syntax error processing `%%local' directive");
2378 free_tlist(origline
);
2379 return DIRECTIVE_FOUND
;
2381 tline
= tline
->next
;
2382 if (!tline
|| tline
->type
!= TOK_ID
) {
2384 "`%%local' missing size type parameter");
2385 free_tlist(origline
);
2386 return DIRECTIVE_FOUND
;
2389 /* Allow macro expansion of type parameter */
2390 tt
= tokenize(tline
->text
);
2391 tt
= expand_smacro(tt
);
2392 size
= parse_size(tt
->text
);
2395 "Invalid size type for `%%local' missing directive");
2397 free_tlist(origline
);
2398 return DIRECTIVE_FOUND
;
2402 /* Round up to even stack slots */
2403 size
= ALIGN(size
, StackSize
);
2405 offset
+= size
; /* Negative offset, increment before */
2407 /* Now define the macro for the argument */
2408 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2409 local
, StackPointer
, offset
);
2410 do_directive(tokenize(directive
));
2412 /* Now define the assign to setup the enter_c macro correctly */
2413 snprintf(directive
, sizeof(directive
),
2414 "%%assign %%$localsize %%$localsize+%d", size
);
2415 do_directive(tokenize(directive
));
2417 /* Move to the next argument in the list */
2418 tline
= tline
->next
;
2419 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2420 tline
= tline
->next
;
2421 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2422 LocalOffset
= offset
;
2423 free_tlist(origline
);
2424 return DIRECTIVE_FOUND
;
2428 error(ERR_WARNING
|ERR_PASS1
,
2429 "trailing garbage after `%%clear' ignored");
2432 free_tlist(origline
);
2433 return DIRECTIVE_FOUND
;
2436 t
= tline
->next
= expand_smacro(tline
->next
);
2438 if (!t
|| (t
->type
!= TOK_STRING
&&
2439 t
->type
!= TOK_INTERNAL_STRING
)) {
2440 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2441 free_tlist(origline
);
2442 return DIRECTIVE_FOUND
; /* but we did _something_ */
2445 error(ERR_WARNING
|ERR_PASS1
,
2446 "trailing garbage after `%%depend' ignored");
2448 if (t
->type
!= TOK_INTERNAL_STRING
)
2449 nasm_unquote_cstr(p
, i
);
2450 if (dephead
&& !in_list(*dephead
, p
)) {
2451 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2455 deptail
= &sl
->next
;
2457 free_tlist(origline
);
2458 return DIRECTIVE_FOUND
;
2461 t
= tline
->next
= expand_smacro(tline
->next
);
2464 if (!t
|| (t
->type
!= TOK_STRING
&&
2465 t
->type
!= TOK_INTERNAL_STRING
)) {
2466 error(ERR_NONFATAL
, "`%%include' expects a file name");
2467 free_tlist(origline
);
2468 return DIRECTIVE_FOUND
; /* but we did _something_ */
2471 error(ERR_WARNING
|ERR_PASS1
,
2472 "trailing garbage after `%%include' ignored");
2474 if (t
->type
!= TOK_INTERNAL_STRING
)
2475 nasm_unquote_cstr(p
, i
);
2476 inc
= nasm_malloc(sizeof(Include
));
2479 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2481 /* -MG given but file not found */
2484 inc
->fname
= src_set_fname(nasm_strdup(p
));
2485 inc
->lineno
= src_set_linnum(0);
2487 inc
->expansion
= NULL
;
2490 list
->uplevel(LIST_INCLUDE
);
2492 free_tlist(origline
);
2493 return DIRECTIVE_FOUND
;
2497 static macros_t
*use_pkg
;
2498 const char *pkg_macro
= NULL
;
2500 tline
= tline
->next
;
2502 tline
= expand_id(tline
);
2504 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2505 tline
->type
!= TOK_INTERNAL_STRING
&&
2506 tline
->type
!= TOK_ID
)) {
2507 error(ERR_NONFATAL
, "`%%use' expects a package name");
2508 free_tlist(origline
);
2509 return DIRECTIVE_FOUND
; /* but we did _something_ */
2512 error(ERR_WARNING
|ERR_PASS1
,
2513 "trailing garbage after `%%use' ignored");
2514 if (tline
->type
== TOK_STRING
)
2515 nasm_unquote_cstr(tline
->text
, i
);
2516 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2518 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2520 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2521 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2522 /* Not already included, go ahead and include it */
2523 stdmacpos
= use_pkg
;
2525 free_tlist(origline
);
2526 return DIRECTIVE_FOUND
;
2531 tline
= tline
->next
;
2533 tline
= expand_id(tline
);
2535 if (!tok_type_(tline
, TOK_ID
)) {
2536 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2538 free_tlist(origline
);
2539 return DIRECTIVE_FOUND
; /* but we did _something_ */
2542 error(ERR_WARNING
|ERR_PASS1
,
2543 "trailing garbage after `%s' ignored",
2545 p
= nasm_strdup(tline
->text
);
2547 p
= NULL
; /* Anonymous */
2551 ctx
= nasm_malloc(sizeof(Context
));
2553 hash_init(&ctx
->localmac
, HASH_SMALL
);
2555 ctx
->number
= unique
++;
2560 error(ERR_NONFATAL
, "`%s': context stack is empty",
2562 } else if (i
== PP_POP
) {
2563 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2564 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2566 cstk
->name
? cstk
->name
: "anonymous", p
);
2571 nasm_free(cstk
->name
);
2577 free_tlist(origline
);
2578 return DIRECTIVE_FOUND
;
2580 severity
= ERR_FATAL
;
2583 severity
= ERR_NONFATAL
;
2586 severity
= ERR_WARNING
|ERR_WARN_USER
;
2591 /* Only error out if this is the final pass */
2592 if (pass
!= 2 && i
!= PP_FATAL
)
2593 return DIRECTIVE_FOUND
;
2595 tline
->next
= expand_smacro(tline
->next
);
2596 tline
= tline
->next
;
2598 t
= tline
? tline
->next
: NULL
;
2600 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2601 /* The line contains only a quoted string */
2603 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2604 error(severity
, "%s", p
);
2606 /* Not a quoted string, or more than a quoted string */
2607 p
= detoken(tline
, false);
2608 error(severity
, "%s", p
);
2611 free_tlist(origline
);
2612 return DIRECTIVE_FOUND
;
2616 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2619 j
= if_condition(tline
->next
, i
);
2620 tline
->next
= NULL
; /* it got freed */
2621 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2623 cond
= nasm_malloc(sizeof(Cond
));
2624 cond
->next
= istk
->conds
;
2628 istk
->mstk
->condcnt
++;
2629 free_tlist(origline
);
2630 return DIRECTIVE_FOUND
;
2634 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2635 switch(istk
->conds
->state
) {
2637 istk
->conds
->state
= COND_DONE
;
2644 case COND_ELSE_TRUE
:
2645 case COND_ELSE_FALSE
:
2646 error_precond(ERR_WARNING
|ERR_PASS1
,
2647 "`%%elif' after `%%else' ignored");
2648 istk
->conds
->state
= COND_NEVER
;
2653 * IMPORTANT: In the case of %if, we will already have
2654 * called expand_mmac_params(); however, if we're
2655 * processing an %elif we must have been in a
2656 * non-emitting mode, which would have inhibited
2657 * the normal invocation of expand_mmac_params().
2658 * Therefore, we have to do it explicitly here.
2660 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2661 tline
->next
= NULL
; /* it got freed */
2662 istk
->conds
->state
=
2663 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2666 free_tlist(origline
);
2667 return DIRECTIVE_FOUND
;
2671 error_precond(ERR_WARNING
|ERR_PASS1
,
2672 "trailing garbage after `%%else' ignored");
2674 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2675 switch(istk
->conds
->state
) {
2678 istk
->conds
->state
= COND_ELSE_FALSE
;
2685 istk
->conds
->state
= COND_ELSE_TRUE
;
2688 case COND_ELSE_TRUE
:
2689 case COND_ELSE_FALSE
:
2690 error_precond(ERR_WARNING
|ERR_PASS1
,
2691 "`%%else' after `%%else' ignored.");
2692 istk
->conds
->state
= COND_NEVER
;
2695 free_tlist(origline
);
2696 return DIRECTIVE_FOUND
;
2700 error_precond(ERR_WARNING
|ERR_PASS1
,
2701 "trailing garbage after `%%endif' ignored");
2703 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2705 istk
->conds
= cond
->next
;
2708 istk
->mstk
->condcnt
--;
2709 free_tlist(origline
);
2710 return DIRECTIVE_FOUND
;
2717 error(ERR_FATAL
, "`%s': already defining a macro",
2719 return DIRECTIVE_FOUND
;
2721 defining
= nasm_malloc(sizeof(MMacro
));
2722 defining
->max_depth
=
2723 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2724 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2725 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2726 nasm_free(defining
);
2728 return DIRECTIVE_FOUND
;
2731 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2733 if (!strcmp(mmac
->name
, defining
->name
) &&
2734 (mmac
->nparam_min
<= defining
->nparam_max
2736 && (defining
->nparam_min
<= mmac
->nparam_max
2738 error(ERR_WARNING
|ERR_PASS1
,
2739 "redefining multi-line macro `%s'", defining
->name
);
2740 return DIRECTIVE_FOUND
;
2744 free_tlist(origline
);
2745 return DIRECTIVE_FOUND
;
2749 if (! (defining
&& defining
->name
)) {
2750 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2751 return DIRECTIVE_FOUND
;
2753 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2754 defining
->next
= *mmhead
;
2757 free_tlist(origline
);
2758 return DIRECTIVE_FOUND
;
2762 * We must search along istk->expansion until we hit a
2763 * macro-end marker for a macro with a name. Then we
2764 * bypass all lines between exitmacro and endmacro.
2766 list_for_each(l
, istk
->expansion
)
2767 if (l
->finishes
&& l
->finishes
->name
)
2772 * Remove all conditional entries relative to this
2773 * macro invocation. (safe to do in this context)
2775 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2777 istk
->conds
= cond
->next
;
2780 istk
->expansion
= l
;
2782 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2784 free_tlist(origline
);
2785 return DIRECTIVE_FOUND
;
2793 spec
.casesense
= (i
== PP_UNMACRO
);
2794 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2795 return DIRECTIVE_FOUND
;
2797 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2798 while (mmac_p
&& *mmac_p
) {
2800 if (mmac
->casesense
== spec
.casesense
&&
2801 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2802 mmac
->nparam_min
== spec
.nparam_min
&&
2803 mmac
->nparam_max
== spec
.nparam_max
&&
2804 mmac
->plus
== spec
.plus
) {
2805 *mmac_p
= mmac
->next
;
2808 mmac_p
= &mmac
->next
;
2811 free_tlist(origline
);
2812 free_tlist(spec
.dlist
);
2813 return DIRECTIVE_FOUND
;
2817 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2818 tline
= tline
->next
;
2820 free_tlist(origline
);
2821 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2822 return DIRECTIVE_FOUND
;
2824 t
= expand_smacro(tline
->next
);
2826 free_tlist(origline
);
2829 tokval
.t_type
= TOKEN_INVALID
;
2831 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2834 return DIRECTIVE_FOUND
;
2836 error(ERR_WARNING
|ERR_PASS1
,
2837 "trailing garbage after expression ignored");
2838 if (!is_simple(evalresult
)) {
2839 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2840 return DIRECTIVE_FOUND
;
2843 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2844 mmac
= mmac
->next_active
;
2846 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2847 } else if (mmac
->nparam
== 0) {
2849 "`%%rotate' invoked within macro without parameters");
2851 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2853 rotate
%= (int)mmac
->nparam
;
2855 rotate
+= mmac
->nparam
;
2857 mmac
->rotate
= rotate
;
2859 return DIRECTIVE_FOUND
;
2864 tline
= tline
->next
;
2865 } while (tok_type_(tline
, TOK_WHITESPACE
));
2867 if (tok_type_(tline
, TOK_ID
) &&
2868 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2871 tline
= tline
->next
;
2872 } while (tok_type_(tline
, TOK_WHITESPACE
));
2876 t
= expand_smacro(tline
);
2878 tokval
.t_type
= TOKEN_INVALID
;
2880 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2882 free_tlist(origline
);
2883 return DIRECTIVE_FOUND
;
2886 error(ERR_WARNING
|ERR_PASS1
,
2887 "trailing garbage after expression ignored");
2888 if (!is_simple(evalresult
)) {
2889 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2890 return DIRECTIVE_FOUND
;
2892 count
= reloc_value(evalresult
) + 1;
2894 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2897 free_tlist(origline
);
2899 tmp_defining
= defining
;
2900 defining
= nasm_malloc(sizeof(MMacro
));
2901 defining
->prev
= NULL
;
2902 defining
->name
= NULL
; /* flags this macro as a %rep block */
2903 defining
->casesense
= false;
2904 defining
->plus
= false;
2905 defining
->nolist
= nolist
;
2906 defining
->in_progress
= count
;
2907 defining
->max_depth
= 0;
2908 defining
->nparam_min
= defining
->nparam_max
= 0;
2909 defining
->defaults
= NULL
;
2910 defining
->dlist
= NULL
;
2911 defining
->expansion
= NULL
;
2912 defining
->next_active
= istk
->mstk
;
2913 defining
->rep_nest
= tmp_defining
;
2914 return DIRECTIVE_FOUND
;
2917 if (!defining
|| defining
->name
) {
2918 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2919 return DIRECTIVE_FOUND
;
2923 * Now we have a "macro" defined - although it has no name
2924 * and we won't be entering it in the hash tables - we must
2925 * push a macro-end marker for it on to istk->expansion.
2926 * After that, it will take care of propagating itself (a
2927 * macro-end marker line for a macro which is really a %rep
2928 * block will cause the macro to be re-expanded, complete
2929 * with another macro-end marker to ensure the process
2930 * continues) until the whole expansion is forcibly removed
2931 * from istk->expansion by a %exitrep.
2933 l
= nasm_malloc(sizeof(Line
));
2934 l
->next
= istk
->expansion
;
2935 l
->finishes
= defining
;
2937 istk
->expansion
= l
;
2939 istk
->mstk
= defining
;
2941 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2942 tmp_defining
= defining
;
2943 defining
= defining
->rep_nest
;
2944 free_tlist(origline
);
2945 return DIRECTIVE_FOUND
;
2949 * We must search along istk->expansion until we hit a
2950 * macro-end marker for a macro with no name. Then we set
2951 * its `in_progress' flag to 0.
2953 list_for_each(l
, istk
->expansion
)
2954 if (l
->finishes
&& !l
->finishes
->name
)
2958 l
->finishes
->in_progress
= 1;
2960 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2961 free_tlist(origline
);
2962 return DIRECTIVE_FOUND
;
2968 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2970 tline
= tline
->next
;
2972 tline
= expand_id(tline
);
2973 if (!tline
|| (tline
->type
!= TOK_ID
&&
2974 (tline
->type
!= TOK_PREPROC_ID
||
2975 tline
->text
[1] != '$'))) {
2976 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2978 free_tlist(origline
);
2979 return DIRECTIVE_FOUND
;
2982 ctx
= get_ctx(tline
->text
, &mname
, false);
2984 param_start
= tline
= tline
->next
;
2987 /* Expand the macro definition now for %xdefine and %ixdefine */
2988 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
2989 tline
= expand_smacro(tline
);
2991 if (tok_is_(tline
, "(")) {
2993 * This macro has parameters.
2996 tline
= tline
->next
;
3000 error(ERR_NONFATAL
, "parameter identifier expected");
3001 free_tlist(origline
);
3002 return DIRECTIVE_FOUND
;
3004 if (tline
->type
!= TOK_ID
) {
3006 "`%s': parameter identifier expected",
3008 free_tlist(origline
);
3009 return DIRECTIVE_FOUND
;
3011 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3012 tline
= tline
->next
;
3014 if (tok_is_(tline
, ",")) {
3015 tline
= tline
->next
;
3017 if (!tok_is_(tline
, ")")) {
3019 "`)' expected to terminate macro template");
3020 free_tlist(origline
);
3021 return DIRECTIVE_FOUND
;
3027 tline
= tline
->next
;
3029 if (tok_type_(tline
, TOK_WHITESPACE
))
3030 last
= tline
, tline
= tline
->next
;
3035 if (t
->type
== TOK_ID
) {
3036 list_for_each(tt
, param_start
)
3037 if (tt
->type
>= TOK_SMAC_PARAM
&&
3038 !strcmp(tt
->text
, t
->text
))
3042 t
->next
= macro_start
;
3047 * Good. We now have a macro name, a parameter count, and a
3048 * token list (in reverse order) for an expansion. We ought
3049 * to be OK just to create an SMacro, store it, and let
3050 * free_tlist have the rest of the line (which we have
3051 * carefully re-terminated after chopping off the expansion
3054 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3055 free_tlist(origline
);
3056 return DIRECTIVE_FOUND
;
3059 tline
= tline
->next
;
3061 tline
= expand_id(tline
);
3062 if (!tline
|| (tline
->type
!= TOK_ID
&&
3063 (tline
->type
!= TOK_PREPROC_ID
||
3064 tline
->text
[1] != '$'))) {
3065 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3066 free_tlist(origline
);
3067 return DIRECTIVE_FOUND
;
3070 error(ERR_WARNING
|ERR_PASS1
,
3071 "trailing garbage after macro name ignored");
3074 /* Find the context that symbol belongs to */
3075 ctx
= get_ctx(tline
->text
, &mname
, false);
3076 undef_smacro(ctx
, mname
);
3077 free_tlist(origline
);
3078 return DIRECTIVE_FOUND
;
3082 casesense
= (i
== PP_DEFSTR
);
3084 tline
= tline
->next
;
3086 tline
= expand_id(tline
);
3087 if (!tline
|| (tline
->type
!= TOK_ID
&&
3088 (tline
->type
!= TOK_PREPROC_ID
||
3089 tline
->text
[1] != '$'))) {
3090 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3092 free_tlist(origline
);
3093 return DIRECTIVE_FOUND
;
3096 ctx
= get_ctx(tline
->text
, &mname
, false);
3098 tline
= expand_smacro(tline
->next
);
3101 while (tok_type_(tline
, TOK_WHITESPACE
))
3102 tline
= delete_Token(tline
);
3104 p
= detoken(tline
, false);
3105 macro_start
= nasm_malloc(sizeof(*macro_start
));
3106 macro_start
->next
= NULL
;
3107 macro_start
->text
= nasm_quote(p
, strlen(p
));
3108 macro_start
->type
= TOK_STRING
;
3109 macro_start
->a
.mac
= NULL
;
3113 * We now have a macro name, an implicit parameter count of
3114 * zero, and a string token to use as an expansion. Create
3115 * and store an SMacro.
3117 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3118 free_tlist(origline
);
3119 return DIRECTIVE_FOUND
;
3123 casesense
= (i
== PP_DEFTOK
);
3125 tline
= tline
->next
;
3127 tline
= expand_id(tline
);
3128 if (!tline
|| (tline
->type
!= TOK_ID
&&
3129 (tline
->type
!= TOK_PREPROC_ID
||
3130 tline
->text
[1] != '$'))) {
3132 "`%s' expects a macro identifier as first parameter",
3134 free_tlist(origline
);
3135 return DIRECTIVE_FOUND
;
3137 ctx
= get_ctx(tline
->text
, &mname
, false);
3139 tline
= expand_smacro(tline
->next
);
3143 while (tok_type_(t
, TOK_WHITESPACE
))
3145 /* t should now point to the string */
3146 if (t
->type
!= TOK_STRING
) {
3148 "`%s` requires string as second parameter",
3151 free_tlist(origline
);
3152 return DIRECTIVE_FOUND
;
3155 nasm_unquote_cstr(t
->text
, i
);
3156 macro_start
= tokenize(t
->text
);
3159 * We now have a macro name, an implicit parameter count of
3160 * zero, and a numeric token to use as an expansion. Create
3161 * and store an SMacro.
3163 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3165 free_tlist(origline
);
3166 return DIRECTIVE_FOUND
;
3171 StrList
*xsl
= NULL
;
3172 StrList
**xst
= &xsl
;
3176 tline
= tline
->next
;
3178 tline
= expand_id(tline
);
3179 if (!tline
|| (tline
->type
!= TOK_ID
&&
3180 (tline
->type
!= TOK_PREPROC_ID
||
3181 tline
->text
[1] != '$'))) {
3183 "`%%pathsearch' expects a macro identifier as first parameter");
3184 free_tlist(origline
);
3185 return DIRECTIVE_FOUND
;
3187 ctx
= get_ctx(tline
->text
, &mname
, false);
3189 tline
= expand_smacro(tline
->next
);
3193 while (tok_type_(t
, TOK_WHITESPACE
))
3196 if (!t
|| (t
->type
!= TOK_STRING
&&
3197 t
->type
!= TOK_INTERNAL_STRING
)) {
3198 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3200 free_tlist(origline
);
3201 return DIRECTIVE_FOUND
; /* but we did _something_ */
3204 error(ERR_WARNING
|ERR_PASS1
,
3205 "trailing garbage after `%%pathsearch' ignored");
3207 if (t
->type
!= TOK_INTERNAL_STRING
)
3208 nasm_unquote(p
, NULL
);
3210 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3213 fclose(fp
); /* Don't actually care about the file */
3215 macro_start
= nasm_malloc(sizeof(*macro_start
));
3216 macro_start
->next
= NULL
;
3217 macro_start
->text
= nasm_quote(p
, strlen(p
));
3218 macro_start
->type
= TOK_STRING
;
3219 macro_start
->a
.mac
= NULL
;
3224 * We now have a macro name, an implicit parameter count of
3225 * zero, and a string token to use as an expansion. Create
3226 * and store an SMacro.
3228 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3230 free_tlist(origline
);
3231 return DIRECTIVE_FOUND
;
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 "`%%strlen' 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
))
3256 /* t should now point to the string */
3257 if (!tok_type_(t
, TOK_STRING
)) {
3259 "`%%strlen` requires string as second parameter");
3261 free_tlist(origline
);
3262 return DIRECTIVE_FOUND
;
3265 macro_start
= nasm_malloc(sizeof(*macro_start
));
3266 macro_start
->next
= NULL
;
3267 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3268 macro_start
->a
.mac
= NULL
;
3271 * We now have a macro name, an implicit parameter count of
3272 * zero, and a numeric token to use as an expansion. Create
3273 * and store an SMacro.
3275 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3277 free_tlist(origline
);
3278 return DIRECTIVE_FOUND
;
3283 tline
= tline
->next
;
3285 tline
= expand_id(tline
);
3286 if (!tline
|| (tline
->type
!= TOK_ID
&&
3287 (tline
->type
!= TOK_PREPROC_ID
||
3288 tline
->text
[1] != '$'))) {
3290 "`%%strcat' expects a macro identifier as first parameter");
3291 free_tlist(origline
);
3292 return DIRECTIVE_FOUND
;
3294 ctx
= get_ctx(tline
->text
, &mname
, false);
3296 tline
= expand_smacro(tline
->next
);
3300 list_for_each(t
, tline
) {
3302 case TOK_WHITESPACE
:
3305 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3308 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3310 /* else fall through */
3313 "non-string passed to `%%strcat' (%d)", t
->type
);
3315 free_tlist(origline
);
3316 return DIRECTIVE_FOUND
;
3320 p
= pp
= nasm_malloc(len
);
3321 list_for_each(t
, tline
) {
3322 if (t
->type
== TOK_STRING
) {
3323 memcpy(p
, t
->text
, t
->a
.len
);
3329 * We now have a macro name, an implicit parameter count of
3330 * zero, and a numeric token to use as an expansion. Create
3331 * and store an SMacro.
3333 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3334 macro_start
->text
= nasm_quote(pp
, len
);
3336 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3338 free_tlist(origline
);
3339 return DIRECTIVE_FOUND
;
3348 tline
= tline
->next
;
3350 tline
= expand_id(tline
);
3351 if (!tline
|| (tline
->type
!= TOK_ID
&&
3352 (tline
->type
!= TOK_PREPROC_ID
||
3353 tline
->text
[1] != '$'))) {
3355 "`%%substr' expects a macro identifier as first parameter");
3356 free_tlist(origline
);
3357 return DIRECTIVE_FOUND
;
3359 ctx
= get_ctx(tline
->text
, &mname
, false);
3361 tline
= expand_smacro(tline
->next
);
3365 while (tok_type_(t
, TOK_WHITESPACE
))
3368 /* t should now point to the string */
3369 if (t
->type
!= TOK_STRING
) {
3371 "`%%substr` requires string as second parameter");
3373 free_tlist(origline
);
3374 return DIRECTIVE_FOUND
;
3379 tokval
.t_type
= TOKEN_INVALID
;
3380 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3384 free_tlist(origline
);
3385 return DIRECTIVE_FOUND
;
3386 } else if (!is_simple(evalresult
)) {
3387 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3389 free_tlist(origline
);
3390 return DIRECTIVE_FOUND
;
3392 a1
= evalresult
->value
-1;
3394 while (tok_type_(tt
, TOK_WHITESPACE
))
3397 a2
= 1; /* Backwards compatibility: one character */
3399 tokval
.t_type
= TOKEN_INVALID
;
3400 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3404 free_tlist(origline
);
3405 return DIRECTIVE_FOUND
;
3406 } else if (!is_simple(evalresult
)) {
3407 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3409 free_tlist(origline
);
3410 return DIRECTIVE_FOUND
;
3412 a2
= evalresult
->value
;
3415 len
= nasm_unquote(t
->text
, NULL
);
3418 if (a1
+a2
> (int64_t)len
)
3421 macro_start
= nasm_malloc(sizeof(*macro_start
));
3422 macro_start
->next
= NULL
;
3423 macro_start
->text
= nasm_quote((a1
< 0) ? "" : t
->text
+a1
, a2
);
3424 macro_start
->type
= TOK_STRING
;
3425 macro_start
->a
.mac
= NULL
;
3428 * We now have a macro name, an implicit parameter count of
3429 * zero, and a numeric token to use as an expansion. Create
3430 * and store an SMacro.
3432 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3434 free_tlist(origline
);
3435 return DIRECTIVE_FOUND
;
3440 casesense
= (i
== PP_ASSIGN
);
3442 tline
= tline
->next
;
3444 tline
= expand_id(tline
);
3445 if (!tline
|| (tline
->type
!= TOK_ID
&&
3446 (tline
->type
!= TOK_PREPROC_ID
||
3447 tline
->text
[1] != '$'))) {
3449 "`%%%sassign' expects a macro identifier",
3450 (i
== PP_IASSIGN
? "i" : ""));
3451 free_tlist(origline
);
3452 return DIRECTIVE_FOUND
;
3454 ctx
= get_ctx(tline
->text
, &mname
, false);
3456 tline
= expand_smacro(tline
->next
);
3461 tokval
.t_type
= TOKEN_INVALID
;
3463 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3466 free_tlist(origline
);
3467 return DIRECTIVE_FOUND
;
3471 error(ERR_WARNING
|ERR_PASS1
,
3472 "trailing garbage after expression ignored");
3474 if (!is_simple(evalresult
)) {
3476 "non-constant value given to `%%%sassign'",
3477 (i
== PP_IASSIGN
? "i" : ""));
3478 free_tlist(origline
);
3479 return DIRECTIVE_FOUND
;
3482 macro_start
= nasm_malloc(sizeof(*macro_start
));
3483 macro_start
->next
= NULL
;
3484 make_tok_num(macro_start
, reloc_value(evalresult
));
3485 macro_start
->a
.mac
= NULL
;
3488 * We now have a macro name, an implicit parameter count of
3489 * zero, and a numeric token to use as an expansion. Create
3490 * and store an SMacro.
3492 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3493 free_tlist(origline
);
3494 return DIRECTIVE_FOUND
;
3498 * Syntax is `%line nnn[+mmm] [filename]'
3500 tline
= tline
->next
;
3502 if (!tok_type_(tline
, TOK_NUMBER
)) {
3503 error(ERR_NONFATAL
, "`%%line' expects line number");
3504 free_tlist(origline
);
3505 return DIRECTIVE_FOUND
;
3507 k
= readnum(tline
->text
, &err
);
3509 tline
= tline
->next
;
3510 if (tok_is_(tline
, "+")) {
3511 tline
= tline
->next
;
3512 if (!tok_type_(tline
, TOK_NUMBER
)) {
3513 error(ERR_NONFATAL
, "`%%line' expects line increment");
3514 free_tlist(origline
);
3515 return DIRECTIVE_FOUND
;
3517 m
= readnum(tline
->text
, &err
);
3518 tline
= tline
->next
;
3524 nasm_free(src_set_fname(detoken(tline
, false)));
3526 free_tlist(origline
);
3527 return DIRECTIVE_FOUND
;
3531 "preprocessor directive `%s' not yet implemented",
3533 return DIRECTIVE_FOUND
;
3538 * Ensure that a macro parameter contains a condition code and
3539 * nothing else. Return the condition code index if so, or -1
3542 static int find_cc(Token
* t
)
3548 return -1; /* Probably a %+ without a space */
3551 if (t
->type
!= TOK_ID
)
3555 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3559 j
= ARRAY_SIZE(conditions
);
3562 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3577 static bool paste_tokens(Token
**head
, bool handle_paste_tokens
)
3579 Token
**tail
, *t
, *tt
;
3581 bool did_paste
= false;
3584 /* Now handle token pasting... */
3587 while ((t
= *tail
) && (tt
= t
->next
)) {
3589 case TOK_WHITESPACE
:
3590 if (tt
->type
== TOK_WHITESPACE
) {
3591 /* Zap adjacent whitespace tokens */
3592 t
->next
= delete_Token(tt
);
3594 /* Do not advance paste_head here */
3605 while (tt
&& (tt
->type
== TOK_ID
|| tt
->type
== TOK_PREPROC_ID
||
3606 tt
->type
== TOK_NUMBER
|| tt
->type
== TOK_FLOAT
||
3607 tt
->type
== TOK_OTHER
)) {
3608 len
+= strlen(tt
->text
);
3613 * Now tt points to the first token after
3614 * the potential paste area...
3616 if (tt
!= t
->next
) {
3617 /* We have at least two tokens... */
3618 len
+= strlen(t
->text
);
3619 p
= tmp
= nasm_malloc(len
+1);
3623 p
= strchr(p
, '\0');
3624 t
= delete_Token(t
);
3627 t
= *tail
= tokenize(tmp
);
3634 t
->next
= tt
; /* Attach the remaining token chain */
3642 case TOK_PASTE
: /* %+ */
3643 if (handle_paste_tokens
) {
3644 /* Zap %+ and whitespace tokens to the right */
3645 while (t
&& (t
->type
== TOK_WHITESPACE
||
3646 t
->type
== TOK_PASTE
))
3647 t
= *tail
= delete_Token(t
);
3648 if (!paste_head
|| !t
)
3649 break; /* Nothing to paste with */
3653 while (tok_type_(tt
, TOK_WHITESPACE
))
3654 tt
= t
->next
= delete_Token(tt
);
3657 tmp
= nasm_strcat(t
->text
, tt
->text
);
3659 tt
= delete_Token(tt
);
3660 t
= *tail
= tokenize(tmp
);
3666 t
->next
= tt
; /* Attach the remaining token chain */
3673 /* else fall through */
3676 if (!tok_type_(t
->next
, TOK_WHITESPACE
))
3685 * expands to a list of tokens from %{x:y}
3687 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3689 Token
*t
= tline
, **tt
, *tm
, *head
;
3693 pos
= strchr(tline
->text
, ':');
3696 lst
= atoi(pos
+ 1);
3697 fst
= atoi(tline
->text
+ 1);
3700 * only macros params are accounted so
3701 * if someone passes %0 -- we reject such
3704 if (lst
== 0 || fst
== 0)
3707 /* the values should be sane */
3708 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3709 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3712 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3713 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3715 /* counted from zero */
3719 * it will be at least one token
3721 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3722 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3723 head
= t
, tt
= &t
->next
;
3725 for (i
= fst
+ 1; i
<= lst
; i
++) {
3726 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3727 *tt
= t
, tt
= &t
->next
;
3728 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3729 tm
= mac
->params
[j
];
3730 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3731 *tt
= t
, tt
= &t
->next
;
3734 for (i
= fst
- 1; i
>= lst
; i
--) {
3735 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3736 *tt
= t
, tt
= &t
->next
;
3737 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3738 tm
= mac
->params
[j
];
3739 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3740 *tt
= t
, tt
= &t
->next
;
3748 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3754 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3755 * %-n) and MMacro-local identifiers (%%foo) as well as
3756 * macro indirection (%[...]) and range (%{..:..}).
3758 static Token
*expand_mmac_params(Token
* tline
)
3760 Token
*t
, *tt
, **tail
, *thead
;
3761 bool changed
= false;
3768 if (tline
->type
== TOK_PREPROC_ID
&&
3769 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3770 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3771 tline
->text
[1] == '%')) {
3773 int type
= 0, cc
; /* type = 0 to placate optimisers */
3780 tline
= tline
->next
;
3783 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3784 mac
= mac
->next_active
;
3786 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3788 pos
= strchr(t
->text
, ':');
3790 switch (t
->text
[1]) {
3792 * We have to make a substitution of one of the
3793 * forms %1, %-1, %+1, %%foo, %0.
3797 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3798 text
= nasm_strdup(tmpbuf
);
3802 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3804 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3807 n
= atoi(t
->text
+ 2) - 1;
3808 if (n
>= mac
->nparam
)
3811 if (mac
->nparam
> 1)
3812 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3813 tt
= mac
->params
[n
];
3818 "macro parameter %d is not a condition code",
3823 if (inverse_ccs
[cc
] == -1) {
3825 "condition code `%s' is not invertible",
3829 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3833 n
= atoi(t
->text
+ 2) - 1;
3834 if (n
>= mac
->nparam
)
3837 if (mac
->nparam
> 1)
3838 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3839 tt
= mac
->params
[n
];
3844 "macro parameter %d is not a condition code",
3849 text
= nasm_strdup(conditions
[cc
]);
3853 n
= atoi(t
->text
+ 1) - 1;
3854 if (n
>= mac
->nparam
)
3857 if (mac
->nparam
> 1)
3858 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3859 tt
= mac
->params
[n
];
3862 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3863 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3864 tail
= &(*tail
)->next
;
3868 text
= NULL
; /* we've done it here */
3873 * seems we have a parameters range here
3875 Token
*head
, **last
;
3876 head
= expand_mmac_params_range(mac
, t
, &last
);
3897 } else if (tline
->type
== TOK_INDIRECT
) {
3899 tline
= tline
->next
;
3900 tt
= tokenize(t
->text
);
3901 tt
= expand_mmac_params(tt
);
3902 tt
= expand_smacro(tt
);
3905 tt
->a
.mac
= NULL
; /* Necessary? */
3913 tline
= tline
->next
;
3921 paste_tokens(&thead
, false);
3927 * Expand all single-line macro calls made in the given line.
3928 * Return the expanded version of the line. The original is deemed
3929 * to be destroyed in the process. (In reality we'll just move
3930 * Tokens from input to output a lot of the time, rather than
3931 * actually bothering to destroy and replicate.)
3934 static Token
*expand_smacro(Token
* tline
)
3936 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
3937 SMacro
*head
= NULL
, *m
;
3940 unsigned int nparam
, sparam
;
3942 Token
*org_tline
= tline
;
3945 int deadman
= DEADMAN_LIMIT
;
3949 * Trick: we should avoid changing the start token pointer since it can
3950 * be contained in "next" field of other token. Because of this
3951 * we allocate a copy of first token and work with it; at the end of
3952 * routine we copy it back
3955 tline
= new_Token(org_tline
->next
, org_tline
->type
,
3956 org_tline
->text
, 0);
3957 tline
->a
.mac
= org_tline
->a
.mac
;
3958 nasm_free(org_tline
->text
);
3959 org_tline
->text
= NULL
;
3962 expanded
= true; /* Always expand %+ at least once */
3968 while (tline
) { /* main token loop */
3970 error(ERR_NONFATAL
, "interminable macro recursion");
3974 if ((mname
= tline
->text
)) {
3975 /* if this token is a local macro, look in local context */
3976 if (tline
->type
== TOK_ID
) {
3977 head
= (SMacro
*)hash_findix(&smacros
, mname
);
3978 } else if (tline
->type
== TOK_PREPROC_ID
) {
3979 ctx
= get_ctx(mname
, &mname
, true);
3980 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
3985 * We've hit an identifier. As in is_mmacro below, we first
3986 * check whether the identifier is a single-line macro at
3987 * all, then think about checking for parameters if
3990 list_for_each(m
, head
)
3991 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
3997 if (m
->nparam
== 0) {
3999 * Simple case: the macro is parameterless. Discard the
4000 * one token that the macro call took, and push the
4001 * expansion back on the to-do stack.
4003 if (!m
->expansion
) {
4004 if (!strcmp("__FILE__", m
->name
)) {
4007 src_get(&num
, &file
);
4008 tline
->text
= nasm_quote(file
, strlen(file
));
4009 tline
->type
= TOK_STRING
;
4013 if (!strcmp("__LINE__", m
->name
)) {
4014 nasm_free(tline
->text
);
4015 make_tok_num(tline
, src_get_linnum());
4018 if (!strcmp("__BITS__", m
->name
)) {
4019 nasm_free(tline
->text
);
4020 make_tok_num(tline
, globalbits
);
4023 tline
= delete_Token(tline
);
4028 * Complicated case: at least one macro with this name
4029 * exists and takes parameters. We must find the
4030 * parameters in the call, count them, find the SMacro
4031 * that corresponds to that form of the macro call, and
4032 * substitute for the parameters when we expand. What a
4035 /*tline = tline->next;
4036 skip_white_(tline); */
4039 while (tok_type_(t
, TOK_SMAC_END
)) {
4040 t
->a
.mac
->in_progress
= false;
4042 t
= tline
->next
= delete_Token(t
);
4045 } while (tok_type_(tline
, TOK_WHITESPACE
));
4046 if (!tok_is_(tline
, "(")) {
4048 * This macro wasn't called with parameters: ignore
4049 * the call. (Behaviour borrowed from gnu cpp.)
4058 sparam
= PARAM_DELTA
;
4059 params
= nasm_malloc(sparam
* sizeof(Token
*));
4060 params
[0] = tline
->next
;
4061 paramsize
= nasm_malloc(sparam
* sizeof(int));
4063 while (true) { /* parameter loop */
4065 * For some unusual expansions
4066 * which concatenates function call
4069 while (tok_type_(t
, TOK_SMAC_END
)) {
4070 t
->a
.mac
->in_progress
= false;
4072 t
= tline
->next
= delete_Token(t
);
4078 "macro call expects terminating `)'");
4081 if (tline
->type
== TOK_WHITESPACE
4083 if (paramsize
[nparam
])
4086 params
[nparam
] = tline
->next
;
4087 continue; /* parameter loop */
4089 if (tline
->type
== TOK_OTHER
4090 && tline
->text
[1] == 0) {
4091 char ch
= tline
->text
[0];
4092 if (ch
== ',' && !paren
&& brackets
<= 0) {
4093 if (++nparam
>= sparam
) {
4094 sparam
+= PARAM_DELTA
;
4095 params
= nasm_realloc(params
,
4096 sparam
* sizeof(Token
*));
4097 paramsize
= nasm_realloc(paramsize
,
4098 sparam
* sizeof(int));
4100 params
[nparam
] = tline
->next
;
4101 paramsize
[nparam
] = 0;
4103 continue; /* parameter loop */
4106 (brackets
> 0 || (brackets
== 0 &&
4107 !paramsize
[nparam
])))
4109 if (!(brackets
++)) {
4110 params
[nparam
] = tline
->next
;
4111 continue; /* parameter loop */
4114 if (ch
== '}' && brackets
> 0)
4115 if (--brackets
== 0) {
4117 continue; /* parameter loop */
4119 if (ch
== '(' && !brackets
)
4121 if (ch
== ')' && brackets
<= 0)
4127 error(ERR_NONFATAL
, "braces do not "
4128 "enclose all of macro parameter");
4130 paramsize
[nparam
] += white
+ 1;
4132 } /* parameter loop */
4134 while (m
&& (m
->nparam
!= nparam
||
4135 mstrcmp(m
->name
, mname
,
4139 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4140 "macro `%s' exists, "
4141 "but not taking %d parameters",
4142 mstart
->text
, nparam
);
4145 if (m
&& m
->in_progress
)
4147 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4149 * Design question: should we handle !tline, which
4150 * indicates missing ')' here, or expand those
4151 * macros anyway, which requires the (t) test a few
4155 nasm_free(paramsize
);
4159 * Expand the macro: we are placed on the last token of the
4160 * call, so that we can easily split the call from the
4161 * following tokens. We also start by pushing an SMAC_END
4162 * token for the cycle removal.
4169 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4171 m
->in_progress
= true;
4173 list_for_each(t
, m
->expansion
) {
4174 if (t
->type
>= TOK_SMAC_PARAM
) {
4175 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4179 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4180 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4182 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4188 } else if (t
->type
== TOK_PREPROC_Q
) {
4189 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4191 } else if (t
->type
== TOK_PREPROC_QQ
) {
4192 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4195 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4201 * Having done that, get rid of the macro call, and clean
4202 * up the parameters.
4205 nasm_free(paramsize
);
4208 continue; /* main token loop */
4213 if (tline
->type
== TOK_SMAC_END
) {
4214 tline
->a
.mac
->in_progress
= false;
4215 tline
= delete_Token(tline
);
4218 tline
= tline
->next
;
4226 * Now scan the entire line and look for successive TOK_IDs that resulted
4227 * after expansion (they can't be produced by tokenize()). The successive
4228 * TOK_IDs should be concatenated.
4229 * Also we look for %+ tokens and concatenate the tokens before and after
4230 * them (without white spaces in between).
4232 if (expanded
&& paste_tokens(&thead
, true)) {
4234 * If we concatenated something, *and* we had previously expanded
4235 * an actual macro, scan the lines again for macros...
4245 *org_tline
= *thead
;
4246 /* since we just gave text to org_line, don't free it */
4248 delete_Token(thead
);
4250 /* the expression expanded to empty line;
4251 we can't return NULL for some reasons
4252 we just set the line to a single WHITESPACE token. */
4253 memset(org_tline
, 0, sizeof(*org_tline
));
4254 org_tline
->text
= NULL
;
4255 org_tline
->type
= TOK_WHITESPACE
;
4264 * Similar to expand_smacro but used exclusively with macro identifiers
4265 * right before they are fetched in. The reason is that there can be
4266 * identifiers consisting of several subparts. We consider that if there
4267 * are more than one element forming the name, user wants a expansion,
4268 * otherwise it will be left as-is. Example:
4272 * the identifier %$abc will be left as-is so that the handler for %define
4273 * will suck it and define the corresponding value. Other case:
4275 * %define _%$abc cde
4277 * In this case user wants name to be expanded *before* %define starts
4278 * working, so we'll expand %$abc into something (if it has a value;
4279 * otherwise it will be left as-is) then concatenate all successive
4282 static Token
*expand_id(Token
* tline
)
4284 Token
*cur
, *oldnext
= NULL
;
4286 if (!tline
|| !tline
->next
)
4291 (cur
->next
->type
== TOK_ID
||
4292 cur
->next
->type
== TOK_PREPROC_ID
4293 || cur
->next
->type
== TOK_NUMBER
))
4296 /* If identifier consists of just one token, don't expand */
4301 oldnext
= cur
->next
; /* Detach the tail past identifier */
4302 cur
->next
= NULL
; /* so that expand_smacro stops here */
4305 tline
= expand_smacro(tline
);
4308 /* expand_smacro possibly changhed tline; re-scan for EOL */
4310 while (cur
&& cur
->next
)
4313 cur
->next
= oldnext
;
4320 * Determine whether the given line constitutes a multi-line macro
4321 * call, and return the MMacro structure called if so. Doesn't have
4322 * to check for an initial label - that's taken care of in
4323 * expand_mmacro - but must check numbers of parameters. Guaranteed
4324 * to be called with tline->type == TOK_ID, so the putative macro
4325 * name is easy to find.
4327 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4333 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4336 * Efficiency: first we see if any macro exists with the given
4337 * name. If not, we can return NULL immediately. _Then_ we
4338 * count the parameters, and then we look further along the
4339 * list if necessary to find the proper MMacro.
4341 list_for_each(m
, head
)
4342 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4348 * OK, we have a potential macro. Count and demarcate the
4351 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4354 * So we know how many parameters we've got. Find the MMacro
4355 * structure that handles this number.
4358 if (m
->nparam_min
<= nparam
4359 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4361 * This one is right. Just check if cycle removal
4362 * prohibits us using it before we actually celebrate...
4364 if (m
->in_progress
> m
->max_depth
) {
4365 if (m
->max_depth
> 0) {
4367 "reached maximum recursion depth of %i",
4374 * It's right, and we can use it. Add its default
4375 * parameters to the end of our list if necessary.
4377 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4379 nasm_realloc(params
,
4380 ((m
->nparam_min
+ m
->ndefs
+
4381 1) * sizeof(*params
)));
4382 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4383 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4388 * If we've gone over the maximum parameter count (and
4389 * we're in Plus mode), ignore parameters beyond
4392 if (m
->plus
&& nparam
> m
->nparam_max
)
4393 nparam
= m
->nparam_max
;
4395 * Then terminate the parameter list, and leave.
4397 if (!params
) { /* need this special case */
4398 params
= nasm_malloc(sizeof(*params
));
4401 params
[nparam
] = NULL
;
4402 *params_array
= params
;
4406 * This one wasn't right: look for the next one with the
4409 list_for_each(m
, m
->next
)
4410 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4415 * After all that, we didn't find one with the right number of
4416 * parameters. Issue a warning, and fail to expand the macro.
4418 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4419 "macro `%s' exists, but not taking %d parameters",
4420 tline
->text
, nparam
);
4427 * Save MMacro invocation specific fields in
4428 * preparation for a recursive macro expansion
4430 static void push_mmacro(MMacro
*m
)
4432 MMacroInvocation
*i
;
4434 i
= nasm_malloc(sizeof(MMacroInvocation
));
4436 i
->params
= m
->params
;
4437 i
->iline
= m
->iline
;
4438 i
->nparam
= m
->nparam
;
4439 i
->rotate
= m
->rotate
;
4440 i
->paramlen
= m
->paramlen
;
4441 i
->unique
= m
->unique
;
4442 i
->condcnt
= m
->condcnt
;
4448 * Restore MMacro invocation specific fields that were
4449 * saved during a previous recursive macro expansion
4451 static void pop_mmacro(MMacro
*m
)
4453 MMacroInvocation
*i
;
4458 m
->params
= i
->params
;
4459 m
->iline
= i
->iline
;
4460 m
->nparam
= i
->nparam
;
4461 m
->rotate
= i
->rotate
;
4462 m
->paramlen
= i
->paramlen
;
4463 m
->unique
= i
->unique
;
4464 m
->condcnt
= i
->condcnt
;
4471 * Expand the multi-line macro call made by the given line, if
4472 * there is one to be expanded. If there is, push the expansion on
4473 * istk->expansion and return 1. Otherwise return 0.
4475 static int expand_mmacro(Token
* tline
)
4477 Token
*startline
= tline
;
4478 Token
*label
= NULL
;
4479 int dont_prepend
= 0;
4480 Token
**params
, *t
, *mtok
, *tt
;
4483 int i
, nparam
, *paramlen
;
4488 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4489 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4492 m
= is_mmacro(t
, ¶ms
);
4498 * We have an id which isn't a macro call. We'll assume
4499 * it might be a label; we'll also check to see if a
4500 * colon follows it. Then, if there's another id after
4501 * that lot, we'll check it again for macro-hood.
4505 if (tok_type_(t
, TOK_WHITESPACE
))
4506 last
= t
, t
= t
->next
;
4507 if (tok_is_(t
, ":")) {
4509 last
= t
, t
= t
->next
;
4510 if (tok_type_(t
, TOK_WHITESPACE
))
4511 last
= t
, t
= t
->next
;
4513 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4521 * Fix up the parameters: this involves stripping leading and
4522 * trailing whitespace, then stripping braces if they are
4525 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4526 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4528 for (i
= 0; params
[i
]; i
++) {
4530 int comma
= (!m
->plus
|| i
< nparam
- 1);
4534 if (tok_is_(t
, "{"))
4535 t
= t
->next
, brace
= true, comma
= false;
4539 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4540 break; /* ... because we have hit a comma */
4541 if (comma
&& t
->type
== TOK_WHITESPACE
4542 && tok_is_(t
->next
, ","))
4543 break; /* ... or a space then a comma */
4544 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4545 break; /* ... or a brace */
4552 * OK, we have a MMacro structure together with a set of
4553 * parameters. We must now go through the expansion and push
4554 * copies of each Line on to istk->expansion. Substitution of
4555 * parameter tokens and macro-local tokens doesn't get done
4556 * until the single-line macro substitution process; this is
4557 * because delaying them allows us to change the semantics
4558 * later through %rotate.
4560 * First, push an end marker on to istk->expansion, mark this
4561 * macro as in progress, and set up its invocation-specific
4564 ll
= nasm_malloc(sizeof(Line
));
4565 ll
->next
= istk
->expansion
;
4568 istk
->expansion
= ll
;
4571 * Save the previous MMacro expansion in the case of
4574 if (m
->max_depth
&& m
->in_progress
)
4582 m
->paramlen
= paramlen
;
4583 m
->unique
= unique
++;
4587 m
->next_active
= istk
->mstk
;
4590 list_for_each(l
, m
->expansion
) {
4593 ll
= nasm_malloc(sizeof(Line
));
4594 ll
->finishes
= NULL
;
4595 ll
->next
= istk
->expansion
;
4596 istk
->expansion
= ll
;
4599 list_for_each(t
, l
->first
) {
4603 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4605 case TOK_PREPROC_QQ
:
4606 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4608 case TOK_PREPROC_ID
:
4609 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4617 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4626 * If we had a label, push it on as the first line of
4627 * the macro expansion.
4630 if (dont_prepend
< 0)
4631 free_tlist(startline
);
4633 ll
= nasm_malloc(sizeof(Line
));
4634 ll
->finishes
= NULL
;
4635 ll
->next
= istk
->expansion
;
4636 istk
->expansion
= ll
;
4637 ll
->first
= startline
;
4638 if (!dont_prepend
) {
4640 label
= label
->next
;
4641 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4646 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4651 /* The function that actually does the error reporting */
4652 static void verror(int severity
, const char *fmt
, va_list arg
)
4656 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4658 if (istk
&& istk
->mstk
&& istk
->mstk
->name
)
4659 nasm_error(severity
, "(%s:%d) %s", istk
->mstk
->name
,
4660 istk
->mstk
->lineno
, buff
);
4662 nasm_error(severity
, "%s", buff
);
4666 * Since preprocessor always operate only on the line that didn't
4667 * arrived yet, we should always use ERR_OFFBY1.
4669 static void error(int severity
, const char *fmt
, ...)
4673 /* If we're in a dead branch of IF or something like it, ignore the error */
4674 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4678 verror(severity
, fmt
, arg
);
4683 * Because %else etc are evaluated in the state context
4684 * of the previous branch, errors might get lost with error():
4685 * %if 0 ... %else trailing garbage ... %endif
4686 * So %else etc should report errors with this function.
4688 static void error_precond(int severity
, const char *fmt
, ...)
4692 /* Only ignore the error if it's really in a dead branch */
4693 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4697 verror(severity
, fmt
, arg
);
4702 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4707 istk
= nasm_malloc(sizeof(Include
));
4710 istk
->expansion
= NULL
;
4712 istk
->fp
= fopen(file
, "r");
4714 src_set_fname(nasm_strdup(file
));
4718 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4721 nested_mac_count
= 0;
4722 nested_rep_count
= 0;
4725 if (tasm_compatible_mode
) {
4726 stdmacpos
= nasm_stdmac
;
4728 stdmacpos
= nasm_stdmac_after_tasm
;
4730 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4735 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4736 * The caller, however, will also pass in 3 for preprocess-only so
4737 * we can set __PASS__ accordingly.
4739 pass
= apass
> 2 ? 2 : apass
;
4741 dephead
= deptail
= deplist
;
4743 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4745 strcpy(sl
->str
, file
);
4747 deptail
= &sl
->next
;
4751 * Define the __PASS__ macro. This is defined here unlike
4752 * all the other builtins, because it is special -- it varies between
4755 t
= nasm_malloc(sizeof(*t
));
4757 make_tok_num(t
, apass
);
4759 define_smacro(NULL
, "__PASS__", true, 0, t
);
4762 static char *pp_getline(void)
4769 * Fetch a tokenized line, either from the macro-expansion
4770 * buffer or from the input file.
4773 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4774 Line
*l
= istk
->expansion
;
4775 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4779 * This is a macro-end marker for a macro with no
4780 * name, which means it's not really a macro at all
4781 * but a %rep block, and the `in_progress' field is
4782 * more than 1, meaning that we still need to
4783 * repeat. (1 means the natural last repetition; 0
4784 * means termination by %exitrep.) We have
4785 * therefore expanded up to the %endrep, and must
4786 * push the whole block on to the expansion buffer
4787 * again. We don't bother to remove the macro-end
4788 * marker: we'd only have to generate another one
4791 l
->finishes
->in_progress
--;
4792 list_for_each(l
, l
->finishes
->expansion
) {
4793 Token
*t
, *tt
, **tail
;
4795 ll
= nasm_malloc(sizeof(Line
));
4796 ll
->next
= istk
->expansion
;
4797 ll
->finishes
= NULL
;
4801 list_for_each(t
, l
->first
) {
4802 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4803 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4808 istk
->expansion
= ll
;
4812 * Check whether a `%rep' was started and not ended
4813 * within this macro expansion. This can happen and
4814 * should be detected. It's a fatal error because
4815 * I'm too confused to work out how to recover
4821 "defining with name in expansion");
4822 else if (istk
->mstk
->name
)
4824 "`%%rep' without `%%endrep' within"
4825 " expansion of macro `%s'",
4830 * FIXME: investigate the relationship at this point between
4831 * istk->mstk and l->finishes
4834 MMacro
*m
= istk
->mstk
;
4835 istk
->mstk
= m
->next_active
;
4838 * This was a real macro call, not a %rep, and
4839 * therefore the parameter information needs to
4844 l
->finishes
->in_progress
--;
4846 nasm_free(m
->params
);
4847 free_tlist(m
->iline
);
4848 nasm_free(m
->paramlen
);
4849 l
->finishes
->in_progress
= 0;
4854 istk
->expansion
= l
->next
;
4856 list
->downlevel(LIST_MACRO
);
4859 while (1) { /* until we get a line we can use */
4861 if (istk
->expansion
) { /* from a macro expansion */
4863 Line
*l
= istk
->expansion
;
4865 istk
->mstk
->lineno
++;
4867 istk
->expansion
= l
->next
;
4869 p
= detoken(tline
, false);
4870 list
->line(LIST_MACRO
, p
);
4875 if (line
) { /* from the current input file */
4876 line
= prepreproc(line
);
4877 tline
= tokenize(line
);
4882 * The current file has ended; work down the istk
4889 "expected `%%endif' before end of file");
4890 /* only set line and file name if there's a next node */
4892 src_set_linnum(i
->lineno
);
4893 nasm_free(src_set_fname(i
->fname
));
4896 list
->downlevel(LIST_INCLUDE
);
4900 if (istk
->expansion
&& istk
->expansion
->finishes
)
4906 * We must expand MMacro parameters and MMacro-local labels
4907 * _before_ we plunge into directive processing, to cope
4908 * with things like `%define something %1' such as STRUC
4909 * uses. Unless we're _defining_ a MMacro, in which case
4910 * those tokens should be left alone to go into the
4911 * definition; and unless we're in a non-emitting
4912 * condition, in which case we don't want to meddle with
4915 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
4916 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
4917 tline
= expand_mmac_params(tline
);
4921 * Check the line to see if it's a preprocessor directive.
4923 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
4925 } else if (defining
) {
4927 * We're defining a multi-line macro. We emit nothing
4929 * shove the tokenized line on to the macro definition.
4931 Line
*l
= nasm_malloc(sizeof(Line
));
4932 l
->next
= defining
->expansion
;
4935 defining
->expansion
= l
;
4937 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
4939 * We're in a non-emitting branch of a condition block.
4940 * Emit nothing at all, not even a blank line: when we
4941 * emerge from the condition we'll give a line-number
4942 * directive so we keep our place correctly.
4946 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
4948 * We're in a %rep block which has been terminated, so
4949 * we're walking through to the %endrep without
4950 * emitting anything. Emit nothing at all, not even a
4951 * blank line: when we emerge from the %rep block we'll
4952 * give a line-number directive so we keep our place
4958 tline
= expand_smacro(tline
);
4959 if (!expand_mmacro(tline
)) {
4961 * De-tokenize the line again, and emit it.
4963 line
= detoken(tline
, true);
4967 continue; /* expand_mmacro calls free_tlist */
4975 static void pp_cleanup(int pass
)
4978 if (defining
->name
) {
4980 "end of file while still defining macro `%s'",
4983 error(ERR_NONFATAL
, "end of file while still in %%rep");
4986 free_mmacro(defining
);
4996 nasm_free(i
->fname
);
5001 nasm_free(src_set_fname(NULL
));
5006 while ((i
= ipath
)) {
5015 void pp_include_path(char *path
)
5019 i
= nasm_malloc(sizeof(IncPath
));
5020 i
->path
= path
? nasm_strdup(path
) : NULL
;
5033 void pp_pre_include(char *fname
)
5035 Token
*inc
, *space
, *name
;
5038 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5039 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5040 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5042 l
= nasm_malloc(sizeof(Line
));
5049 void pp_pre_define(char *definition
)
5055 equals
= strchr(definition
, '=');
5056 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5057 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5060 space
->next
= tokenize(definition
);
5064 l
= nasm_malloc(sizeof(Line
));
5071 void pp_pre_undefine(char *definition
)
5076 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5077 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5078 space
->next
= tokenize(definition
);
5080 l
= nasm_malloc(sizeof(Line
));
5088 * Added by Keith Kanios:
5090 * This function is used to assist with "runtime" preprocessor
5091 * directives. (e.g. pp_runtime("%define __BITS__ 64");)
5093 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5094 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5097 void pp_runtime(char *definition
)
5101 def
= tokenize(definition
);
5102 if (do_directive(def
) == NO_DIRECTIVE_FOUND
)
5107 void pp_extra_stdmac(macros_t
*macros
)
5109 extrastdmac
= macros
;
5112 static void make_tok_num(Token
* tok
, int64_t val
)
5115 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5116 tok
->text
= nasm_strdup(numbuf
);
5117 tok
->type
= TOK_NUMBER
;