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 ExpDef ExpDef
;
86 typedef struct ExpInv ExpInv
;
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 * The context stack is composed of a linked list of these.
122 struct hash_table localmac
;
127 * This is the internal form which we break input lines up into.
128 * Typically stored in linked lists.
130 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
131 * necessarily used as-is, but is intended to denote the number of
132 * the substituted parameter. So in the definition
134 * %define a(x,y) ( (x) & ~(y) )
136 * the token representing `x' will have its type changed to
137 * TOK_SMAC_PARAM, but the one representing `y' will be
140 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
141 * which doesn't need quotes around it. Used in the pre-include
142 * mechanism as an alternative to trying to find a sensible type of
143 * quote to use on the filename we were passed.
146 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
147 TOK_PREPROC_ID
, TOK_STRING
,
148 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
150 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
152 TOK_INDIRECT
, /* %[...] */
153 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
154 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
157 #define PP_CONCAT_MASK(x) (1 << (x))
159 struct tokseq_match
{
168 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
169 size_t len
; /* scratch length field */
170 } a
; /* Auxiliary data */
171 enum pp_token_type type
;
175 * Expansion definitions are stored as a linked list of
176 * these, which is essentially a container to allow several linked
179 * Note that in this module, linked lists are treated as stacks
180 * wherever possible. For this reason, Lines are _pushed_ on to the
181 * `last' field in ExpDef structures, so that the linked list,
182 * if walked, would emit the expansion lines in the proper order.
193 EXP_NONE
= 0, EXP_PREDEF
,
196 EXP_COMMENT
, EXP_FINAL
,
197 EXP_MAX
= INT_MAX
/* Keep compiler from reducing the range */
201 * Store the definition of an expansion, in which is any
202 * preprocessor directive that has an ending pair.
204 * This design allows for arbitrary expansion/recursion depth,
205 * upto the DEADMAN_LIMIT.
207 * The `next' field is used for storing ExpDef in hash tables; the
208 * `prev' field is for the global `expansions` linked-list.
211 ExpDef
*prev
; /* previous definition */
212 ExpDef
*next
; /* next in hash table */
213 enum pp_exp_type type
; /* expansion type */
214 char *name
; /* definition name */
215 int nparam_min
, nparam_max
;
217 bool plus
; /* is the last parameter greedy? */
218 bool nolist
; /* is this expansion listing-inhibited? */
219 Token
*dlist
; /* all defaults as one list */
220 Token
**defaults
; /* parameter default pointers */
221 int ndefs
; /* number of default parameters */
223 int prepend
; /* label prepend state */
227 int linecount
; /* number of lines within expansion */
229 int64_t def_depth
; /* current number of definition pairs deep */
230 int64_t cur_depth
; /* current number of expansions */
231 int64_t max_depth
; /* maximum number of expansions allowed */
233 int state
; /* condition state */
234 bool ignoring
; /* ignoring definition lines */
238 * Store the invocation of an expansion.
240 * The `prev' field is for the `istk->expansion` linked-list.
242 * When an expansion is being expanded, `params', `iline', `nparam',
243 * `paramlen', `rotate' and `unique' are local to the invocation.
246 ExpInv
*prev
; /* previous invocation */
247 enum pp_exp_type type
; /* expansion type */
248 ExpDef
*def
; /* pointer to expansion definition */
249 char *name
; /* invocation name */
250 Line
*label
; /* pointer to label */
251 char *label_text
; /* pointer to label text */
252 Line
*current
; /* pointer to current line in invocation */
254 Token
**params
; /* actual parameters */
255 Token
*iline
; /* invocation line */
256 unsigned int nparam
, rotate
;
261 int lineno
; /* current line number in expansion */
262 int linnum
; /* line number at invocation */
263 int relno
; /* relative line number at invocation */
267 * To handle an arbitrary level of file inclusion, we maintain a
268 * stack (ie linked list) of these things.
281 * Include search path. This is simply a list of strings which get
282 * prepended, in turn, to the name of an include file, in an
283 * attempt to find the file if it's not in the current directory.
291 * Conditional assembly: we maintain a separate stack of these for
292 * each level of file inclusion. (The only reason we keep the
293 * stacks separate is to ensure that a stray `%endif' in a file
294 * included from within the true branch of a `%if' won't terminate
295 * it and cause confusion: instead, rightly, it'll cause an error.)
299 * These states are for use just after %if or %elif: IF_TRUE
300 * means the condition has evaluated to truth so we are
301 * currently emitting, whereas IF_FALSE means we are not
302 * currently emitting but will start doing so if a %else comes
303 * up. In these states, all directives are admissible: %elif,
304 * %else and %endif. (And of course %if.)
306 COND_IF_TRUE
, COND_IF_FALSE
,
308 * These states come up after a %else: ELSE_TRUE means we're
309 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
310 * any %elif or %else will cause an error.
312 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
314 * These states mean that we're not emitting now, and also that
315 * nothing until %endif will be emitted at all. COND_DONE is
316 * used when we've had our moment of emission
317 * and have now started seeing %elifs. COND_NEVER is used when
318 * the condition construct in question is contained within a
319 * non-emitting branch of a larger condition construct,
320 * or if there is an error.
322 COND_DONE
, COND_NEVER
324 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
327 * These defines are used as the possible return values for do_directive
329 #define NO_DIRECTIVE_FOUND 0
330 #define DIRECTIVE_FOUND 1
333 * This define sets the upper limit for smacro and expansions
335 #define DEADMAN_LIMIT (1 << 20)
338 #define REP_LIMIT ((INT64_C(1) << 62))
341 * Condition codes. Note that we use c_ prefix not C_ because C_ is
342 * used in nasm.h for the "real" condition codes. At _this_ level,
343 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
344 * ones, so we need a different enum...
346 static const char * const conditions
[] = {
347 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
348 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
349 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
352 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
353 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
354 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
357 static const enum pp_conds inverse_ccs
[] = {
358 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
359 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
,
360 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
363 /* For TASM compatibility we need to be able to recognise TASM compatible
364 * conditional compilation directives. Using the NASM pre-processor does
365 * not work, so we look for them specifically from the following list and
366 * then jam in the equivalent NASM directive into the input stream.
370 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
371 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
374 static const char * const tasm_directives
[] = {
375 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
376 "ifndef", "include", "local"
379 static int StackSize
= 4;
380 static char *StackPointer
= "ebp";
381 static int ArgOffset
= 8;
382 static int LocalOffset
= 0;
384 static Context
*cstk
;
385 static Include
*istk
;
386 static IncPath
*ipath
= NULL
;
388 static int pass
; /* HACK: pass 0 = generate dependencies only */
389 static StrList
**dephead
, **deptail
; /* Dependency list */
391 static uint64_t unique
; /* unique identifier numbers */
393 static Line
*predef
= NULL
;
394 static bool do_predef
;
396 static ListGen
*list
;
399 * The current set of expansion definitions we have defined.
401 static struct hash_table expdefs
;
404 * The current set of single-line macros we have defined.
406 static struct hash_table smacros
;
409 * Linked List of all active expansion definitions
411 struct ExpDef
*expansions
= NULL
;
414 * The expansion we are currently defining
416 static ExpDef
*defining
= NULL
;
418 static uint64_t nested_mac_count
;
419 static uint64_t nested_rep_count
;
422 * Linked-list of lines to preprocess, prior to cleanup
424 static Line
*finals
= NULL
;
425 static bool in_final
= false;
428 * The number of macro parameters to allocate space for at a time.
430 #define PARAM_DELTA 16
433 * The standard macro set: defined in macros.c in the array nasm_stdmac.
434 * This gives our position in the macro set, when we're processing it.
436 static macros_t
*stdmacpos
;
439 * The extra standard macros that come from the object format, if
442 static macros_t
*extrastdmac
= NULL
;
443 static bool any_extrastdmac
;
446 * Tokens are allocated in blocks to improve speed
448 #define TOKEN_BLOCKSIZE 4096
449 static Token
*freeTokens
= NULL
;
455 static Blocks blocks
= { NULL
, NULL
};
458 * Forward declarations.
460 static Token
*expand_mmac_params(Token
* tline
);
461 static Token
*expand_smacro(Token
* tline
);
462 static Token
*expand_id(Token
* tline
);
463 static Context
*get_ctx(const char *name
, const char **namep
,
465 static void make_tok_num(Token
* tok
, int64_t val
);
466 static void error(int severity
, const char *fmt
, ...);
467 static void error_precond(int severity
, const char *fmt
, ...);
468 static void *new_Block(size_t size
);
469 static void delete_Blocks(void);
470 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
471 const char *text
, int txtlen
);
472 static Token
*copy_Token(Token
* tline
);
473 static Token
*delete_Token(Token
* t
);
474 static Line
*new_Line(void);
475 static ExpDef
*new_ExpDef(int exp_type
);
476 static ExpInv
*new_ExpInv(int exp_type
, ExpDef
*ed
);
479 * Macros for safe checking of token pointers, avoid *(NULL)
481 #define tok_type_(x,t) ((x) && (x)->type == (t))
482 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
483 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
484 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
488 #define dump_token(t) raw_dump_token(t, __FILE__, __LINE__, __func__);
489 static void raw_dump_token(Token
*token
, const char *file
, int line
, const char *func
)
491 printf("---[%s (%s:%d): %p]---\n", func
, file
, line
, (void *)token
);
494 list_for_each(t
, token
) {
496 printf("'%s' ", t
->text
);
505 * nasm_unquote with error if the string contains NUL characters.
506 * If the string contains NUL characters, issue an error and return
507 * the C len, i.e. truncate at the NUL.
509 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
511 size_t len
= nasm_unquote(qstr
, NULL
);
512 size_t clen
= strlen(qstr
);
515 error(ERR_NONFATAL
, "NUL character in `%s' directive",
516 pp_directives
[directive
]);
522 * In-place reverse a list of tokens.
524 static Token
*reverse_tokens(Token
*t
)
540 * Handle TASM specific directives, which do not contain a % in
541 * front of them. We do it here because I could not find any other
542 * place to do it for the moment, and it is a hack (ideally it would
543 * be nice to be able to use the NASM pre-processor to do it).
545 static char *check_tasm_directive(char *line
)
547 int32_t i
, j
, k
, m
, len
;
548 char *p
, *q
, *oldline
, oldchar
;
550 p
= nasm_skip_spaces(line
);
552 /* Binary search for the directive name */
554 j
= ARRAY_SIZE(tasm_directives
);
555 q
= nasm_skip_word(p
);
562 m
= nasm_stricmp(p
, tasm_directives
[k
]);
564 /* We have found a directive, so jam a % in front of it
565 * so that NASM will then recognise it as one if it's own.
570 line
= nasm_malloc(len
+ 2);
572 if (k
== TM_IFDIFI
) {
574 * NASM does not recognise IFDIFI, so we convert
575 * it to %if 0. This is not used in NASM
576 * compatible code, but does need to parse for the
577 * TASM macro package.
579 strcpy(line
+ 1, "if 0");
581 memcpy(line
+ 1, p
, len
+ 1);
596 * The pre-preprocessing stage... This function translates line
597 * number indications as they emerge from GNU cpp (`# lineno "file"
598 * flags') into NASM preprocessor line number indications (`%line
601 static char *prepreproc(char *line
)
604 char *fname
, *oldline
;
606 if (line
[0] == '#' && line
[1] == ' ') {
609 lineno
= atoi(fname
);
610 fname
+= strspn(fname
, "0123456789 ");
613 fnlen
= strcspn(fname
, "\"");
614 line
= nasm_malloc(20 + fnlen
);
615 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
618 if (tasm_compatible_mode
)
619 return check_tasm_directive(line
);
624 * Free a linked list of tokens.
626 static void free_tlist(Token
* list
)
629 list
= delete_Token(list
);
633 * Free a linked list of lines.
635 static void free_llist(Line
* list
)
638 list_for_each_safe(l
, tmp
, list
) {
639 free_tlist(l
->first
);
647 static void free_expdef(ExpDef
* ed
)
650 free_tlist(ed
->dlist
);
651 nasm_free(ed
->defaults
);
652 free_llist(ed
->line
);
659 static void free_expinv(ExpInv
* ei
)
661 if (ei
->name
!= NULL
)
663 if (ei
->label_text
!= NULL
)
664 nasm_free(ei
->label_text
);
669 * Free all currently defined macros, and free the hash tables
671 static void free_smacro_table(struct hash_table
*smt
)
675 struct hash_tbl_node
*it
= NULL
;
677 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
678 nasm_free((void *)key
);
679 list_for_each_safe(s
, tmp
, s
) {
681 free_tlist(s
->expansion
);
688 static void free_expdef_table(struct hash_table
*edt
)
692 struct hash_tbl_node
*it
= NULL
;
695 while ((ed
= hash_iterate(edt
, &it
, &key
)) != NULL
) {
696 nasm_free((void *)key
);
697 list_for_each_safe(ed
,tmp
, ed
)
703 static void free_macros(void)
705 free_smacro_table(&smacros
);
706 free_expdef_table(&expdefs
);
710 * Initialize the hash tables
712 static void init_macros(void)
714 hash_init(&smacros
, HASH_LARGE
);
715 hash_init(&expdefs
, HASH_LARGE
);
719 * Pop the context stack.
721 static void ctx_pop(void)
726 free_smacro_table(&c
->localmac
);
732 * Search for a key in the hash index; adding it if necessary
733 * (in which case we initialize the data pointer to NULL.)
736 hash_findi_add(struct hash_table
*hash
, const char *str
)
738 struct hash_insert hi
;
742 r
= hash_findi(hash
, str
, &hi
);
746 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
747 return hash_add(&hi
, strx
, NULL
);
751 * Like hash_findi, but returns the data element rather than a pointer
752 * to it. Used only when not adding a new element, hence no third
756 hash_findix(struct hash_table
*hash
, const char *str
)
760 p
= hash_findi(hash
, str
, NULL
);
761 return p
? *p
: NULL
;
765 * read line from standard macros set,
766 * if there no more left -- return NULL
768 static char *line_from_stdmac(void)
771 const unsigned char *p
= stdmacpos
;
780 len
+= pp_directives_len
[c
- 0x80] + 1;
785 line
= nasm_malloc(len
+ 1);
787 while ((c
= *stdmacpos
++)) {
789 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
790 q
+= pp_directives_len
[c
- 0x80];
800 /* This was the last of the standard macro chain... */
802 if (any_extrastdmac
) {
803 stdmacpos
= extrastdmac
;
804 any_extrastdmac
= false;
805 } else if (do_predef
) {
808 Token
*head
, **tail
, *t
;
811 * Nasty hack: here we push the contents of
812 * `predef' on to the top-level expansion stack,
813 * since this is the most convenient way to
814 * implement the pre-include and pre-define
817 list_for_each(pd
, predef
) {
820 list_for_each(t
, pd
->first
) {
821 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
822 tail
= &(*tail
)->next
;
827 ei
= new_ExpInv(EXP_PREDEF
, NULL
);
830 ei
->prev
= istk
->expansion
;
831 istk
->expansion
= ei
;
840 #define BUF_DELTA 512
842 * Read a line from the top file in istk, handling multiple CR/LFs
843 * at the end of the line read, and handling spurious ^Zs. Will
844 * return lines from the standard macro set if this has not already
847 static char *read_line(void)
849 char *buffer
, *p
, *q
;
850 int bufsize
, continued_count
;
853 * standart macros set (predefined) goes first
855 p
= line_from_stdmac();
860 * regular read from a file
863 buffer
= nasm_malloc(BUF_DELTA
);
867 q
= fgets(p
, bufsize
- (p
- buffer
), istk
->fp
);
871 if (p
> buffer
&& p
[-1] == '\n') {
873 * Convert backslash-CRLF line continuation sequences into
874 * nothing at all (for DOS and Windows)
876 if (((p
- 2) > buffer
) && (p
[-3] == '\\') && (p
[-2] == '\r')) {
882 * Also convert backslash-LF line continuation sequences into
883 * nothing at all (for Unix)
885 else if (((p
- 1) > buffer
) && (p
[-2] == '\\')) {
893 if (p
- buffer
> bufsize
- 10) {
894 int32_t offset
= p
- buffer
;
895 bufsize
+= BUF_DELTA
;
896 buffer
= nasm_realloc(buffer
, bufsize
);
897 p
= buffer
+ offset
; /* prevent stale-pointer problems */
901 if (!q
&& p
== buffer
) {
906 src_set_linnum(src_get_linnum() + istk
->lineinc
+
907 (continued_count
* istk
->lineinc
));
910 * Play safe: remove CRs as well as LFs, if any of either are
911 * present at the end of the line.
913 while (--p
>= buffer
&& (*p
== '\n' || *p
== '\r'))
917 * Handle spurious ^Z, which may be inserted into source files
918 * by some file transfer utilities.
920 buffer
[strcspn(buffer
, "\032")] = '\0';
922 list
->line(LIST_READ
, buffer
);
928 * Tokenize a line of text. This is a very simple process since we
929 * don't need to parse the value out of e.g. numeric tokens: we
930 * simply split one string into many.
932 static Token
*tokenize(char *line
)
935 enum pp_token_type type
;
937 Token
*t
, **tail
= &list
;
943 if (*p
== '+' && !nasm_isdigit(p
[1])) {
946 } else if (nasm_isdigit(*p
) ||
947 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
951 while (nasm_isdigit(*p
));
952 type
= TOK_PREPROC_ID
;
953 } else if (*p
== '{') {
955 while (*p
&& *p
!= '}') {
962 type
= TOK_PREPROC_ID
;
963 } else if (*p
== '[') {
965 line
+= 2; /* Skip the leading %[ */
967 while (lvl
&& (c
= *p
++)) {
979 p
= nasm_skip_string(p
- 1) + 1;
989 error(ERR_NONFATAL
, "unterminated %[ construct");
991 } else if (*p
== '?') {
992 type
= TOK_PREPROC_Q
; /* %? */
995 type
= TOK_PREPROC_QQ
; /* %?? */
998 } else if (*p
== '!') {
999 type
= TOK_PREPROC_ID
;
1004 } while (isidchar(*p
));
1005 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
1006 p
= nasm_skip_string(p
);
1010 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
1012 /* %! without string or identifier */
1013 type
= TOK_OTHER
; /* Legacy behavior... */
1015 } else if (isidchar(*p
) ||
1016 ((*p
== '!' || *p
== '%' || *p
== '$') &&
1021 while (isidchar(*p
));
1022 type
= TOK_PREPROC_ID
;
1028 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
1031 while (*p
&& isidchar(*p
))
1033 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
1038 p
= nasm_skip_string(p
);
1043 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1044 /* Handling unterminated strings by UNV */
1047 } else if (p
[0] == '$' && p
[1] == '$') {
1048 type
= TOK_OTHER
; /* TOKEN_BASE */
1050 } else if (isnumstart(*p
)) {
1051 bool is_hex
= false;
1052 bool is_float
= false;
1068 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1070 if (*p
== '+' || *p
== '-') {
1072 * e can only be followed by +/- if it is either a
1073 * prefixed hex number or a floating-point number
1078 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1080 } else if (c
== 'P' || c
== 'p') {
1082 if (*p
== '+' || *p
== '-')
1084 } else if (isnumchar(c
) || c
== '_')
1085 ; /* just advance */
1086 else if (c
== '.') {
1088 * we need to deal with consequences of the legacy
1089 * parser, like "1.nolist" being two tokens
1090 * (TOK_NUMBER, TOK_ID) here; at least give it
1091 * a shot for now. In the future, we probably need
1092 * a flex-based scanner with proper pattern matching
1093 * to do it as well as it can be done. Nothing in
1094 * the world is going to help the person who wants
1095 * 0x123.p16 interpreted as two tokens, though.
1101 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1102 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1103 (*r
== 'p' || *r
== 'P')) {
1107 break; /* Terminate the token */
1111 p
--; /* Point to first character beyond number */
1113 if (p
== line
+1 && *line
== '$') {
1114 type
= TOK_OTHER
; /* TOKEN_HERE */
1116 if (has_e
&& !is_hex
) {
1117 /* 1e13 is floating-point, but 1e13h is not */
1121 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1123 } else if (nasm_isspace(*p
)) {
1124 type
= TOK_WHITESPACE
;
1125 p
= nasm_skip_spaces(p
);
1127 * Whitespace just before end-of-line is discarded by
1128 * pretending it's a comment; whitespace just before a
1129 * comment gets lumped into the comment.
1131 if (!*p
|| *p
== ';') {
1136 } else if (*p
== ';') {
1142 * Anything else is an operator of some kind. We check
1143 * for all the double-character operators (>>, <<, //,
1144 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1145 * else is a single-character operator.
1148 if ((p
[0] == '>' && p
[1] == '>') ||
1149 (p
[0] == '<' && p
[1] == '<') ||
1150 (p
[0] == '/' && p
[1] == '/') ||
1151 (p
[0] == '<' && p
[1] == '=') ||
1152 (p
[0] == '>' && p
[1] == '=') ||
1153 (p
[0] == '=' && p
[1] == '=') ||
1154 (p
[0] == '!' && p
[1] == '=') ||
1155 (p
[0] == '<' && p
[1] == '>') ||
1156 (p
[0] == '&' && p
[1] == '&') ||
1157 (p
[0] == '|' && p
[1] == '|') ||
1158 (p
[0] == '^' && p
[1] == '^')) {
1164 /* Handling unterminated string by UNV */
1167 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1168 t->text[p-line] = *line;
1172 if (type
!= TOK_COMMENT
) {
1173 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1182 * this function allocates a new managed block of memory and
1183 * returns a pointer to the block. The managed blocks are
1184 * deleted only all at once by the delete_Blocks function.
1186 static void *new_Block(size_t size
)
1188 Blocks
*b
= &blocks
;
1190 /* first, get to the end of the linked list */
1193 /* now allocate the requested chunk */
1194 b
->chunk
= nasm_malloc(size
);
1196 /* now allocate a new block for the next request */
1197 b
->next
= nasm_malloc(sizeof(Blocks
));
1198 /* and initialize the contents of the new block */
1199 b
->next
->next
= NULL
;
1200 b
->next
->chunk
= NULL
;
1205 * this function deletes all managed blocks of memory
1207 static void delete_Blocks(void)
1209 Blocks
*a
, *b
= &blocks
;
1212 * keep in mind that the first block, pointed to by blocks
1213 * is a static and not dynamically allocated, so we don't
1218 nasm_free(b
->chunk
);
1227 * this function creates a new Token and passes a pointer to it
1228 * back to the caller. It sets the type and text elements, and
1229 * also the a.mac and next elements to NULL.
1231 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1232 const char *text
, int txtlen
)
1238 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1239 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1240 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1241 freeTokens
[i
].next
= NULL
;
1244 freeTokens
= t
->next
;
1248 if (type
== TOK_WHITESPACE
|| !text
) {
1252 txtlen
= strlen(text
);
1253 t
->text
= nasm_malloc(txtlen
+1);
1254 memcpy(t
->text
, text
, txtlen
);
1255 t
->text
[txtlen
] = '\0';
1260 static Token
*copy_Token(Token
* tline
)
1262 Token
*t
, *tt
, *first
= NULL
, *prev
= NULL
;
1264 for (tt
= tline
; tt
!= NULL
; tt
= tt
->next
) {
1266 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1267 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1268 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1269 freeTokens
[i
].next
= NULL
;
1272 freeTokens
= t
->next
;
1274 t
->text
= tt
->text
? nasm_strdup(tt
->text
) : NULL
;
1275 t
->a
.mac
= tt
->a
.mac
;
1276 t
->a
.len
= tt
->a
.len
;
1288 static Token
*delete_Token(Token
* t
)
1290 Token
*next
= t
->next
;
1292 t
->next
= freeTokens
;
1298 * Convert a line of tokens back into text.
1299 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1300 * will be transformed into ..@ctxnum.xxx
1302 static char *detoken(Token
* tlist
, bool expand_locals
)
1309 list_for_each(t
, tlist
) {
1310 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1315 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1316 size_t len
= nasm_unquote(v
, NULL
);
1317 size_t clen
= strlen(v
);
1320 error(ERR_NONFATAL
| ERR_PASS1
,
1321 "NUL character in %! string");
1327 char *p
= getenv(v
);
1329 error(ERR_NONFATAL
| ERR_PASS1
,
1330 "nonexistent environment variable `%s'", v
);
1333 t
->text
= nasm_strdup(p
);
1338 /* Expand local macros here and not during preprocessing */
1339 if (expand_locals
&&
1340 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1341 t
->text
[0] == '%' && t
->text
[1] == '$') {
1344 Context
*ctx
= get_ctx(t
->text
, &q
, false);
1347 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1348 p
= nasm_strcat(buffer
, q
);
1354 /* Expand %? and %?? directives */
1355 if ((istk
->expansion
!= NULL
) &&
1356 ((t
->type
== TOK_PREPROC_Q
) ||
1357 (t
->type
== TOK_PREPROC_QQ
))) {
1359 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
){
1360 if (ei
->type
== EXP_MMACRO
) {
1362 if (t
->type
== TOK_PREPROC_Q
) {
1363 t
->text
= nasm_strdup(ei
->name
);
1365 t
->text
= nasm_strdup(ei
->def
->name
);
1372 if (t
->type
== TOK_WHITESPACE
)
1375 len
+= strlen(t
->text
);
1378 p
= line
= nasm_malloc(len
+ 1);
1380 list_for_each(t
, tlist
) {
1381 if (t
->type
== TOK_WHITESPACE
) {
1383 } else if (t
->text
) {
1395 * Initialize a new Line
1397 static inline Line
*new_Line(void)
1399 Line
*l
= nasm_malloc(sizeof(Line
));
1407 * Initialize a new Expansion Definition
1409 static ExpDef
*new_ExpDef(int exp_type
)
1411 ExpDef
*ed
= (ExpDef
*)nasm_zalloc(sizeof(ExpDef
));
1412 ed
->type
= exp_type
;
1413 ed
->casesense
= true;
1414 ed
->state
= COND_NEVER
;
1421 * Initialize a new Expansion Instance
1423 static ExpInv
*new_ExpInv(int exp_type
, ExpDef
*ed
)
1425 ExpInv
*ei
= (ExpInv
*)nasm_zalloc(sizeof(ExpInv
));
1426 ei
->type
= exp_type
;
1428 ei
->unique
= ++unique
;
1430 if ((istk
->mmac_depth
< 1) &&
1431 (istk
->expansion
== NULL
) &&
1433 (ed
->type
!= EXP_MMACRO
) &&
1434 (ed
->type
!= EXP_REP
) &&
1435 (ed
->type
!= EXP_WHILE
)) {
1436 ei
->linnum
= src_get_linnum();
1437 src_set_linnum(ei
->linnum
- ed
->linecount
- 1);
1441 if ((istk
->expansion
== NULL
) ||
1442 (ei
->type
== EXP_MMACRO
)) {
1445 ei
->relno
= istk
->expansion
->lineno
;
1447 ei
->relno
-= (ed
->linecount
+ 1);
1454 * A scanner, suitable for use by the expression evaluator, which
1455 * operates on a line of Tokens. Expects a pointer to a pointer to
1456 * the first token in the line to be passed in as its private_data
1459 * FIX: This really needs to be unified with stdscan.
1461 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1463 Token
**tlineptr
= private_data
;
1465 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1469 *tlineptr
= tline
? tline
->next
: NULL
;
1470 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1471 tline
->type
== TOK_COMMENT
));
1474 return tokval
->t_type
= TOKEN_EOS
;
1476 tokval
->t_charptr
= tline
->text
;
1478 if (tline
->text
[0] == '$' && !tline
->text
[1])
1479 return tokval
->t_type
= TOKEN_HERE
;
1480 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1481 return tokval
->t_type
= TOKEN_BASE
;
1483 if (tline
->type
== TOK_ID
) {
1484 p
= tokval
->t_charptr
= tline
->text
;
1486 tokval
->t_charptr
++;
1487 return tokval
->t_type
= TOKEN_ID
;
1490 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1491 if (r
>= p
+MAX_KEYWORD
)
1492 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1493 *s
++ = nasm_tolower(*r
);
1496 /* right, so we have an identifier sitting in temp storage. now,
1497 * is it actually a register or instruction name, or what? */
1498 return nasm_token_hash(ourcopy
, tokval
);
1501 if (tline
->type
== TOK_NUMBER
) {
1503 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1504 tokval
->t_charptr
= tline
->text
;
1506 return tokval
->t_type
= TOKEN_ERRNUM
;
1508 return tokval
->t_type
= TOKEN_NUM
;
1511 if (tline
->type
== TOK_FLOAT
) {
1512 return tokval
->t_type
= TOKEN_FLOAT
;
1515 if (tline
->type
== TOK_STRING
) {
1518 bq
= tline
->text
[0];
1519 tokval
->t_charptr
= tline
->text
;
1520 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1522 if (ep
[0] != bq
|| ep
[1] != '\0')
1523 return tokval
->t_type
= TOKEN_ERRSTR
;
1525 return tokval
->t_type
= TOKEN_STR
;
1528 if (tline
->type
== TOK_OTHER
) {
1529 if (!strcmp(tline
->text
, "<<"))
1530 return tokval
->t_type
= TOKEN_SHL
;
1531 if (!strcmp(tline
->text
, ">>"))
1532 return tokval
->t_type
= TOKEN_SHR
;
1533 if (!strcmp(tline
->text
, "//"))
1534 return tokval
->t_type
= TOKEN_SDIV
;
1535 if (!strcmp(tline
->text
, "%%"))
1536 return tokval
->t_type
= TOKEN_SMOD
;
1537 if (!strcmp(tline
->text
, "=="))
1538 return tokval
->t_type
= TOKEN_EQ
;
1539 if (!strcmp(tline
->text
, "<>"))
1540 return tokval
->t_type
= TOKEN_NE
;
1541 if (!strcmp(tline
->text
, "!="))
1542 return tokval
->t_type
= TOKEN_NE
;
1543 if (!strcmp(tline
->text
, "<="))
1544 return tokval
->t_type
= TOKEN_LE
;
1545 if (!strcmp(tline
->text
, ">="))
1546 return tokval
->t_type
= TOKEN_GE
;
1547 if (!strcmp(tline
->text
, "&&"))
1548 return tokval
->t_type
= TOKEN_DBL_AND
;
1549 if (!strcmp(tline
->text
, "^^"))
1550 return tokval
->t_type
= TOKEN_DBL_XOR
;
1551 if (!strcmp(tline
->text
, "||"))
1552 return tokval
->t_type
= TOKEN_DBL_OR
;
1556 * We have no other options: just return the first character of
1559 return tokval
->t_type
= tline
->text
[0];
1563 * Compare a string to the name of an existing macro; this is a
1564 * simple wrapper which calls either strcmp or nasm_stricmp
1565 * depending on the value of the `casesense' parameter.
1567 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1569 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1573 * Compare a string to the name of an existing macro; this is a
1574 * simple wrapper which calls either strcmp or nasm_stricmp
1575 * depending on the value of the `casesense' parameter.
1577 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1579 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1583 * Return the Context structure associated with a %$ token. Return
1584 * NULL, having _already_ reported an error condition, if the
1585 * context stack isn't deep enough for the supplied number of $
1587 * If all_contexts == true, contexts that enclose current are
1588 * also scanned for such smacro, until it is found; if not -
1589 * only the context that directly results from the number of $'s
1590 * in variable's name.
1592 * If "namep" is non-NULL, set it to the pointer to the macro name
1593 * tail, i.e. the part beyond %$...
1595 static Context
*get_ctx(const char *name
, const char **namep
,
1605 if (!name
|| name
[0] != '%' || name
[1] != '$')
1609 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1616 while (ctx
&& *name
== '$') {
1622 error(ERR_NONFATAL
, "`%s': context stack is only"
1623 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1634 /* Search for this smacro in found context */
1635 m
= hash_findix(&ctx
->localmac
, name
);
1637 if (!mstrcmp(m
->name
, name
, m
->casesense
))
1648 * Check to see if a file is already in a string list
1650 static bool in_list(const StrList
*list
, const char *str
)
1653 if (!strcmp(list
->str
, str
))
1661 * Open an include file. This routine must always return a valid
1662 * file pointer if it returns - it's responsible for throwing an
1663 * ERR_FATAL and bombing out completely if not. It should also try
1664 * the include path one by one until it finds the file or reaches
1665 * the end of the path.
1667 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1672 IncPath
*ip
= ipath
;
1673 int len
= strlen(file
);
1674 size_t prefix_len
= 0;
1678 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1680 memcpy(sl
->str
, prefix
, prefix_len
);
1681 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1682 fp
= fopen(sl
->str
, "r");
1683 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1700 prefix_len
= strlen(prefix
);
1702 /* -MG given and file not found */
1703 if (dhead
&& !in_list(*dhead
, file
)) {
1704 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1706 strcpy(sl
->str
, file
);
1714 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1719 * Determine if we should warn on defining a single-line macro of
1720 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1721 * return true if _any_ single-line macro of that name is defined.
1722 * Otherwise, will return true if a single-line macro with either
1723 * `nparam' or no parameters is defined.
1725 * If a macro with precisely the right number of parameters is
1726 * defined, or nparam is -1, the address of the definition structure
1727 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1728 * is NULL, no action will be taken regarding its contents, and no
1731 * Note that this is also called with nparam zero to resolve
1734 * If you already know which context macro belongs to, you can pass
1735 * the context pointer as first parameter; if you won't but name begins
1736 * with %$ the context will be automatically computed. If all_contexts
1737 * is true, macro will be searched in outer contexts as well.
1740 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1743 struct hash_table
*smtbl
;
1747 smtbl
= &ctx
->localmac
;
1748 } else if (name
[0] == '%' && name
[1] == '$') {
1750 ctx
= get_ctx(name
, &name
, false);
1752 return false; /* got to return _something_ */
1753 smtbl
= &ctx
->localmac
;
1757 m
= (SMacro
*) hash_findix(smtbl
, name
);
1760 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1761 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1763 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1777 * Count and mark off the parameters in a multi-line macro call.
1778 * This is called both from within the multi-line macro expansion
1779 * code, and also to mark off the default parameters when provided
1780 * in a %macro definition line.
1782 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1784 int paramsize
, brace
;
1786 *nparam
= paramsize
= 0;
1789 /* +1: we need space for the final NULL */
1790 if (*nparam
+1 >= paramsize
) {
1791 paramsize
+= PARAM_DELTA
;
1792 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1796 if (tok_is_(t
, "{"))
1798 (*params
)[(*nparam
)++] = t
;
1799 while (tok_isnt_(t
, brace
? "}" : ","))
1801 if (t
) { /* got a comma/brace */
1805 * Now we've found the closing brace, look further
1809 if (tok_isnt_(t
, ",")) {
1811 "braces do not enclose all of macro parameter");
1812 while (tok_isnt_(t
, ","))
1816 t
= t
->next
; /* eat the comma */
1823 * Determine whether one of the various `if' conditions is true or
1826 * We must free the tline we get passed.
1828 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1830 enum pp_conditional i
= PP_COND(ct
);
1832 Token
*t
, *tt
, **tptr
, *origline
;
1833 struct tokenval tokval
;
1835 enum pp_token_type needtype
;
1842 j
= false; /* have we matched yet? */
1847 if (tline
->type
!= TOK_ID
) {
1849 "`%s' expects context identifiers", pp_directives
[ct
]);
1850 free_tlist(origline
);
1853 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1855 tline
= tline
->next
;
1860 j
= false; /* have we matched yet? */
1863 if (!tline
|| (tline
->type
!= TOK_ID
&&
1864 (tline
->type
!= TOK_PREPROC_ID
||
1865 tline
->text
[1] != '$'))) {
1867 "`%s' expects macro identifiers", pp_directives
[ct
]);
1870 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1872 tline
= tline
->next
;
1877 tline
= expand_smacro(tline
);
1878 j
= false; /* have we matched yet? */
1881 if (!tline
|| (tline
->type
!= TOK_ID
&&
1882 tline
->type
!= TOK_STRING
&&
1883 (tline
->type
!= TOK_PREPROC_ID
||
1884 tline
->text
[1] != '!'))) {
1886 "`%s' expects environment variable names",
1891 if (tline
->type
== TOK_PREPROC_ID
)
1892 p
+= 2; /* Skip leading %! */
1893 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1894 nasm_unquote_cstr(p
, ct
);
1897 tline
= tline
->next
;
1903 tline
= expand_smacro(tline
);
1905 while (tok_isnt_(tt
, ","))
1909 "`%s' expects two comma-separated arguments",
1914 j
= true; /* assume equality unless proved not */
1915 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1916 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1917 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1921 if (t
->type
== TOK_WHITESPACE
) {
1925 if (tt
->type
== TOK_WHITESPACE
) {
1929 if (tt
->type
!= t
->type
) {
1930 j
= false; /* found mismatching tokens */
1933 /* When comparing strings, need to unquote them first */
1934 if (t
->type
== TOK_STRING
) {
1935 size_t l1
= nasm_unquote(t
->text
, NULL
);
1936 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1942 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1946 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1947 j
= false; /* found mismatching tokens */
1954 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1955 j
= false; /* trailing gunk on one end or other */
1961 ExpDef searching
, *ed
;
1964 tline
= expand_id(tline
);
1965 if (!tok_type_(tline
, TOK_ID
)) {
1967 "`%s' expects a macro name", pp_directives
[ct
]);
1970 memset(&searching
, 0, sizeof(searching
));
1971 searching
.name
= nasm_strdup(tline
->text
);
1972 searching
.casesense
= true;
1973 searching
.nparam_max
= INT_MAX
;
1974 tline
= expand_smacro(tline
->next
);
1977 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1979 "`%s' expects a parameter count or nothing",
1982 searching
.nparam_min
= searching
.nparam_max
=
1983 readnum(tline
->text
, &j
);
1986 "unable to parse parameter count `%s'",
1989 if (tline
&& tok_is_(tline
->next
, "-")) {
1990 tline
= tline
->next
->next
;
1991 if (tok_is_(tline
, "*"))
1992 searching
.nparam_max
= INT_MAX
;
1993 else if (!tok_type_(tline
, TOK_NUMBER
))
1995 "`%s' expects a parameter count after `-'",
1998 searching
.nparam_max
= readnum(tline
->text
, &j
);
2001 "unable to parse parameter count `%s'",
2003 if (searching
.nparam_min
> searching
.nparam_max
)
2005 "minimum parameter count exceeds maximum");
2008 if (tline
&& tok_is_(tline
->next
, "+")) {
2009 tline
= tline
->next
;
2010 searching
.plus
= true;
2012 ed
= (ExpDef
*) hash_findix(&expdefs
, searching
.name
);
2013 while (ed
!= NULL
) {
2014 if (!strcmp(ed
->name
, searching
.name
) &&
2015 (ed
->nparam_min
<= searching
.nparam_max
|| searching
.plus
) &&
2016 (searching
.nparam_min
<= ed
->nparam_max
|| ed
->plus
)) {
2022 if (tline
&& tline
->next
)
2023 error(ERR_WARNING
|ERR_PASS1
,
2024 "trailing garbage after %%ifmacro ignored");
2025 nasm_free(searching
.name
);
2034 needtype
= TOK_NUMBER
;
2037 needtype
= TOK_STRING
;
2041 t
= tline
= expand_smacro(tline
);
2043 while (tok_type_(t
, TOK_WHITESPACE
) ||
2044 (needtype
== TOK_NUMBER
&&
2045 tok_type_(t
, TOK_OTHER
) &&
2046 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
2050 j
= tok_type_(t
, needtype
);
2054 t
= tline
= expand_smacro(tline
);
2055 while (tok_type_(t
, TOK_WHITESPACE
))
2060 t
= t
->next
; /* Skip the actual token */
2061 while (tok_type_(t
, TOK_WHITESPACE
))
2063 j
= !t
; /* Should be nothing left */
2068 t
= tline
= expand_smacro(tline
);
2069 while (tok_type_(t
, TOK_WHITESPACE
))
2072 j
= !t
; /* Should be empty */
2076 t
= tline
= expand_smacro(tline
);
2078 tokval
.t_type
= TOKEN_INVALID
;
2079 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
2080 NULL
, pass
| CRITICAL
, error
, NULL
);
2084 error(ERR_WARNING
|ERR_PASS1
,
2085 "trailing garbage after expression ignored");
2086 if (!is_simple(evalresult
)) {
2088 "non-constant value given to `%s'", pp_directives
[ct
]);
2091 j
= reloc_value(evalresult
) != 0;
2096 "preprocessor directive `%s' not yet implemented",
2101 free_tlist(origline
);
2102 return j
^ PP_NEGATIVE(ct
);
2105 free_tlist(origline
);
2110 * Common code for defining an smacro
2112 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
2113 int nparam
, Token
*expansion
)
2115 SMacro
*smac
, **smhead
;
2116 struct hash_table
*smtbl
;
2118 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
2120 error(ERR_WARNING
|ERR_PASS1
,
2121 "single-line macro `%s' defined both with and"
2122 " without parameters", mname
);
2124 * Some instances of the old code considered this a failure,
2125 * some others didn't. What is the right thing to do here?
2127 free_tlist(expansion
);
2128 return false; /* Failure */
2131 * We're redefining, so we have to take over an
2132 * existing SMacro structure. This means freeing
2133 * what was already in it.
2135 nasm_free(smac
->name
);
2136 free_tlist(smac
->expansion
);
2139 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2140 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
2141 smac
= nasm_zalloc(sizeof(SMacro
));
2142 smac
->next
= *smhead
;
2145 smac
->name
= nasm_strdup(mname
);
2146 smac
->casesense
= casesense
;
2147 smac
->nparam
= nparam
;
2148 smac
->expansion
= expansion
;
2149 smac
->in_progress
= false;
2150 return true; /* Success */
2154 * Undefine an smacro
2156 static void undef_smacro(Context
*ctx
, const char *mname
)
2158 SMacro
**smhead
, *s
, **sp
;
2159 struct hash_table
*smtbl
;
2161 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2162 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2166 * We now have a macro name... go hunt for it.
2169 while ((s
= *sp
) != NULL
) {
2170 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2173 free_tlist(s
->expansion
);
2183 * Parse a mmacro specification.
2185 static bool parse_mmacro_spec(Token
*tline
, ExpDef
*def
, const char *directive
)
2189 tline
= tline
->next
;
2191 tline
= expand_id(tline
);
2192 if (!tok_type_(tline
, TOK_ID
)) {
2193 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2197 def
->name
= nasm_strdup(tline
->text
);
2199 def
->nolist
= false;
2200 // def->in_progress = 0;
2201 // def->rep_nest = NULL;
2202 def
->nparam_min
= 0;
2203 def
->nparam_max
= 0;
2205 tline
= expand_smacro(tline
->next
);
2207 if (!tok_type_(tline
, TOK_NUMBER
)) {
2208 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2210 def
->nparam_min
= def
->nparam_max
=
2211 readnum(tline
->text
, &err
);
2214 "unable to parse parameter count `%s'", tline
->text
);
2216 if (tline
&& tok_is_(tline
->next
, "-")) {
2217 tline
= tline
->next
->next
;
2218 if (tok_is_(tline
, "*")) {
2219 def
->nparam_max
= INT_MAX
;
2220 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2222 "`%s' expects a parameter count after `-'", directive
);
2224 def
->nparam_max
= readnum(tline
->text
, &err
);
2226 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2229 if (def
->nparam_min
> def
->nparam_max
) {
2230 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2234 if (tline
&& tok_is_(tline
->next
, "+")) {
2235 tline
= tline
->next
;
2238 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2239 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2240 tline
= tline
->next
;
2245 * Handle default parameters.
2247 if (tline
&& tline
->next
) {
2248 def
->dlist
= tline
->next
;
2250 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2253 def
->defaults
= NULL
;
2257 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2259 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2260 "too many default macro parameters");
2267 * Decode a size directive
2269 static int parse_size(const char *str
) {
2270 static const char *size_names
[] =
2271 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2272 static const int sizes
[] =
2273 { 0, 1, 4, 16, 8, 10, 2, 32 };
2275 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2279 * find and process preprocessor directive in passed line
2280 * Find out if a line contains a preprocessor directive, and deal
2283 * If a directive _is_ found, it is the responsibility of this routine
2284 * (and not the caller) to free_tlist() the line.
2286 * @param tline a pointer to the current tokeninzed line linked list
2287 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2290 static int do_directive(Token
* tline
)
2292 enum preproc_token i
;
2305 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2306 struct tokenval tokval
;
2308 ExpDef
*ed
, *eed
, **edhead
;
2317 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2318 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2319 || tline
->text
[1] == '!'))
2320 return NO_DIRECTIVE_FOUND
;
2322 i
= pp_token_hash(tline
->text
);
2326 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2327 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2329 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2332 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2333 /* Directive to tell NASM what the default stack size is. The
2334 * default is for a 16-bit stack, and this can be overriden with
2337 tline
= tline
->next
;
2338 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2339 tline
= tline
->next
;
2340 if (!tline
|| tline
->type
!= TOK_ID
) {
2341 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2342 free_tlist(origline
);
2343 return DIRECTIVE_FOUND
;
2345 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2346 /* All subsequent ARG directives are for a 32-bit stack */
2348 StackPointer
= "ebp";
2351 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2352 /* All subsequent ARG directives are for a 64-bit stack */
2354 StackPointer
= "rbp";
2357 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2358 /* All subsequent ARG directives are for a 16-bit stack,
2359 * far function call.
2362 StackPointer
= "bp";
2365 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2366 /* All subsequent ARG directives are for a 16-bit stack,
2367 * far function call. We don't support near functions.
2370 StackPointer
= "bp";
2374 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2375 free_tlist(origline
);
2376 return DIRECTIVE_FOUND
;
2378 free_tlist(origline
);
2379 return DIRECTIVE_FOUND
;
2382 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2383 /* TASM like ARG directive to define arguments to functions, in
2384 * the following form:
2386 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2390 char *arg
, directive
[256];
2391 int size
= StackSize
;
2393 /* Find the argument name */
2394 tline
= tline
->next
;
2395 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2396 tline
= tline
->next
;
2397 if (!tline
|| tline
->type
!= TOK_ID
) {
2398 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2399 free_tlist(origline
);
2400 return DIRECTIVE_FOUND
;
2404 /* Find the argument size type */
2405 tline
= tline
->next
;
2406 if (!tline
|| tline
->type
!= TOK_OTHER
2407 || tline
->text
[0] != ':') {
2409 "Syntax error processing `%%arg' directive");
2410 free_tlist(origline
);
2411 return DIRECTIVE_FOUND
;
2413 tline
= tline
->next
;
2414 if (!tline
|| tline
->type
!= TOK_ID
) {
2415 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2416 free_tlist(origline
);
2417 return DIRECTIVE_FOUND
;
2420 /* Allow macro expansion of type parameter */
2421 tt
= tokenize(tline
->text
);
2422 tt
= expand_smacro(tt
);
2423 size
= parse_size(tt
->text
);
2426 "Invalid size type for `%%arg' missing directive");
2428 free_tlist(origline
);
2429 return DIRECTIVE_FOUND
;
2433 /* Round up to even stack slots */
2434 size
= ALIGN(size
, StackSize
);
2436 /* Now define the macro for the argument */
2437 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2438 arg
, StackPointer
, offset
);
2439 do_directive(tokenize(directive
));
2442 /* Move to the next argument in the list */
2443 tline
= tline
->next
;
2444 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2445 tline
= tline
->next
;
2446 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2448 free_tlist(origline
);
2449 return DIRECTIVE_FOUND
;
2452 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2453 /* TASM like LOCAL directive to define local variables for a
2454 * function, in the following form:
2456 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2458 * The '= LocalSize' at the end is ignored by NASM, but is
2459 * required by TASM to define the local parameter size (and used
2460 * by the TASM macro package).
2462 offset
= LocalOffset
;
2464 char *local
, directive
[256];
2465 int size
= StackSize
;
2467 /* Find the argument name */
2468 tline
= tline
->next
;
2469 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2470 tline
= tline
->next
;
2471 if (!tline
|| tline
->type
!= TOK_ID
) {
2473 "`%%local' missing argument parameter");
2474 free_tlist(origline
);
2475 return DIRECTIVE_FOUND
;
2477 local
= tline
->text
;
2479 /* Find the argument size type */
2480 tline
= tline
->next
;
2481 if (!tline
|| tline
->type
!= TOK_OTHER
2482 || tline
->text
[0] != ':') {
2484 "Syntax error processing `%%local' directive");
2485 free_tlist(origline
);
2486 return DIRECTIVE_FOUND
;
2488 tline
= tline
->next
;
2489 if (!tline
|| tline
->type
!= TOK_ID
) {
2491 "`%%local' missing size type parameter");
2492 free_tlist(origline
);
2493 return DIRECTIVE_FOUND
;
2496 /* Allow macro expansion of type parameter */
2497 tt
= tokenize(tline
->text
);
2498 tt
= expand_smacro(tt
);
2499 size
= parse_size(tt
->text
);
2502 "Invalid size type for `%%local' missing directive");
2504 free_tlist(origline
);
2505 return DIRECTIVE_FOUND
;
2509 /* Round up to even stack slots */
2510 size
= ALIGN(size
, StackSize
);
2512 offset
+= size
; /* Negative offset, increment before */
2514 /* Now define the macro for the argument */
2515 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2516 local
, StackPointer
, offset
);
2517 do_directive(tokenize(directive
));
2519 /* Now define the assign to setup the enter_c macro correctly */
2520 snprintf(directive
, sizeof(directive
),
2521 "%%assign %%$localsize %%$localsize+%d", size
);
2522 do_directive(tokenize(directive
));
2524 /* Move to the next argument in the list */
2525 tline
= tline
->next
;
2526 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2527 tline
= tline
->next
;
2528 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2529 LocalOffset
= offset
;
2530 free_tlist(origline
);
2531 return DIRECTIVE_FOUND
;
2534 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2536 error(ERR_WARNING
|ERR_PASS1
,
2537 "trailing garbage after `%%clear' ignored");
2540 free_tlist(origline
);
2541 return DIRECTIVE_FOUND
;
2544 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2545 t
= tline
->next
= expand_smacro(tline
->next
);
2547 if (!t
|| (t
->type
!= TOK_STRING
&&
2548 t
->type
!= TOK_INTERNAL_STRING
)) {
2549 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2550 free_tlist(origline
);
2551 return DIRECTIVE_FOUND
; /* but we did _something_ */
2554 error(ERR_WARNING
|ERR_PASS1
,
2555 "trailing garbage after `%%depend' ignored");
2557 if (t
->type
!= TOK_INTERNAL_STRING
)
2558 nasm_unquote_cstr(p
, i
);
2559 if (dephead
&& !in_list(*dephead
, p
)) {
2560 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2564 deptail
= &sl
->next
;
2566 free_tlist(origline
);
2567 return DIRECTIVE_FOUND
;
2570 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2571 t
= tline
->next
= expand_smacro(tline
->next
);
2574 if (!t
|| (t
->type
!= TOK_STRING
&&
2575 t
->type
!= TOK_INTERNAL_STRING
)) {
2576 error(ERR_NONFATAL
, "`%%include' expects a file name");
2577 free_tlist(origline
);
2578 return DIRECTIVE_FOUND
; /* but we did _something_ */
2581 error(ERR_WARNING
|ERR_PASS1
,
2582 "trailing garbage after `%%include' ignored");
2584 if (t
->type
!= TOK_INTERNAL_STRING
)
2585 nasm_unquote_cstr(p
, i
);
2586 inc
= nasm_zalloc(sizeof(Include
));
2588 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2590 /* -MG given but file not found */
2593 inc
->fname
= src_set_fname(nasm_strdup(p
));
2594 inc
->lineno
= src_set_linnum(0);
2596 inc
->expansion
= NULL
;
2598 list
->uplevel(LIST_INCLUDE
);
2600 free_tlist(origline
);
2601 return DIRECTIVE_FOUND
;
2604 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2606 static macros_t
*use_pkg
;
2607 const char *pkg_macro
= NULL
;
2609 tline
= tline
->next
;
2611 tline
= expand_id(tline
);
2613 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2614 tline
->type
!= TOK_INTERNAL_STRING
&&
2615 tline
->type
!= TOK_ID
)) {
2616 error(ERR_NONFATAL
, "`%%use' expects a package name");
2617 free_tlist(origline
);
2618 return DIRECTIVE_FOUND
; /* but we did _something_ */
2621 error(ERR_WARNING
|ERR_PASS1
,
2622 "trailing garbage after `%%use' ignored");
2623 if (tline
->type
== TOK_STRING
)
2624 nasm_unquote_cstr(tline
->text
, i
);
2625 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2627 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2629 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2630 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2631 /* Not already included, go ahead and include it */
2632 stdmacpos
= use_pkg
;
2634 free_tlist(origline
);
2635 return DIRECTIVE_FOUND
;
2640 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2641 tline
= tline
->next
;
2643 tline
= expand_id(tline
);
2645 if (!tok_type_(tline
, TOK_ID
)) {
2646 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2648 free_tlist(origline
);
2649 return DIRECTIVE_FOUND
; /* but we did _something_ */
2652 error(ERR_WARNING
|ERR_PASS1
,
2653 "trailing garbage after `%s' ignored",
2655 p
= nasm_strdup(tline
->text
);
2657 p
= NULL
; /* Anonymous */
2661 ctx
= nasm_zalloc(sizeof(Context
));
2663 hash_init(&ctx
->localmac
, HASH_SMALL
);
2665 ctx
->number
= unique
++;
2670 error(ERR_NONFATAL
, "`%s': context stack is empty",
2672 } else if (i
== PP_POP
) {
2673 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2674 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2676 cstk
->name
? cstk
->name
: "anonymous", p
);
2681 nasm_free(cstk
->name
);
2687 free_tlist(origline
);
2688 return DIRECTIVE_FOUND
;
2690 severity
= ERR_FATAL
;
2693 severity
= ERR_NONFATAL
;
2696 severity
= ERR_WARNING
|ERR_WARN_USER
;
2700 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2702 /* Only error out if this is the final pass */
2703 if (pass
!= 2 && i
!= PP_FATAL
)
2704 return DIRECTIVE_FOUND
;
2706 tline
->next
= expand_smacro(tline
->next
);
2707 tline
= tline
->next
;
2709 t
= tline
? tline
->next
: NULL
;
2711 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2712 /* The line contains only a quoted string */
2714 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2715 error(severity
, "%s", p
);
2717 /* Not a quoted string, or more than a quoted string */
2718 p
= detoken(tline
, false);
2719 error(severity
, "%s", p
);
2722 free_tlist(origline
);
2723 return DIRECTIVE_FOUND
;
2727 if (defining
!= NULL
) {
2728 if (defining
->type
== EXP_IF
) {
2729 defining
->def_depth
++;
2731 return NO_DIRECTIVE_FOUND
;
2733 if ((istk
->expansion
!= NULL
) &&
2734 (istk
->expansion
->emitting
== false)) {
2737 j
= if_condition(tline
->next
, i
);
2738 tline
->next
= NULL
; /* it got freed */
2739 j
= (((j
< 0) ? COND_NEVER
: j
) ? COND_IF_TRUE
: COND_IF_FALSE
);
2741 ed
= new_ExpDef(EXP_IF
);
2747 ed
->ignoring
= ((ed
->state
== COND_IF_TRUE
) ? false : true);
2748 ed
->prev
= defining
;
2750 free_tlist(origline
);
2751 return DIRECTIVE_FOUND
;
2754 if (defining
!= NULL
) {
2755 if ((defining
->type
!= EXP_IF
) || (defining
->def_depth
> 0)) {
2756 return NO_DIRECTIVE_FOUND
;
2759 if ((defining
== NULL
) || (defining
->type
!= EXP_IF
)) {
2760 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2762 switch (defining
->state
) {
2764 defining
->state
= COND_DONE
;
2765 defining
->ignoring
= true;
2770 defining
->ignoring
= true;
2773 case COND_ELSE_TRUE
:
2774 case COND_ELSE_FALSE
:
2775 error_precond(ERR_WARNING
|ERR_PASS1
,
2776 "`%%elif' after `%%else' ignored");
2777 defining
->state
= COND_NEVER
;
2778 defining
->ignoring
= true;
2783 * IMPORTANT: In the case of %if, we will already have
2784 * called expand_mmac_params(); however, if we're
2785 * processing an %elif we must have been in a
2786 * non-emitting mode, which would have inhibited
2787 * the normal invocation of expand_mmac_params().
2788 * Therefore, we have to do it explicitly here.
2790 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2791 tline
->next
= NULL
; /* it got freed */
2793 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2794 defining
->ignoring
= ((defining
->state
== COND_IF_TRUE
) ? false : true);
2797 free_tlist(origline
);
2798 return DIRECTIVE_FOUND
;
2801 if (defining
!= NULL
) {
2802 if ((defining
->type
!= EXP_IF
) || (defining
->def_depth
> 0)) {
2803 return NO_DIRECTIVE_FOUND
;
2807 error_precond(ERR_WARNING
|ERR_PASS1
,
2808 "trailing garbage after `%%else' ignored");
2809 if ((defining
== NULL
) || (defining
->type
!= EXP_IF
)) {
2810 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2812 switch (defining
->state
) {
2815 defining
->state
= COND_ELSE_FALSE
;
2816 defining
->ignoring
= true;
2820 defining
->ignoring
= true;
2824 defining
->state
= COND_ELSE_TRUE
;
2825 defining
->ignoring
= false;
2828 case COND_ELSE_TRUE
:
2829 case COND_ELSE_FALSE
:
2830 error_precond(ERR_WARNING
|ERR_PASS1
,
2831 "`%%else' after `%%else' ignored.");
2832 defining
->state
= COND_NEVER
;
2833 defining
->ignoring
= true;
2836 free_tlist(origline
);
2837 return DIRECTIVE_FOUND
;
2840 if (defining
!= NULL
) {
2841 if (defining
->type
== EXP_IF
) {
2842 if (defining
->def_depth
> 0) {
2843 defining
->def_depth
--;
2844 return NO_DIRECTIVE_FOUND
;
2847 return NO_DIRECTIVE_FOUND
;
2851 error_precond(ERR_WARNING
|ERR_PASS1
,
2852 "trailing garbage after `%%endif' ignored");
2853 if ((defining
== NULL
) || (defining
->type
!= EXP_IF
)) {
2854 error(ERR_NONFATAL
, "`%%endif': no matching `%%if'");
2855 return DIRECTIVE_FOUND
;
2858 defining
= ed
->prev
;
2859 ed
->prev
= expansions
;
2861 ei
= new_ExpInv(EXP_IF
, ed
);
2862 ei
->current
= ed
->line
;
2863 ei
->emitting
= true;
2864 ei
->prev
= istk
->expansion
;
2865 istk
->expansion
= ei
;
2866 free_tlist(origline
);
2867 return DIRECTIVE_FOUND
;
2873 if (defining
!= NULL
) {
2874 if (defining
->type
== EXP_MMACRO
) {
2875 defining
->def_depth
++;
2877 return NO_DIRECTIVE_FOUND
;
2879 ed
= new_ExpDef(EXP_MMACRO
);
2881 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2882 ed
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2883 if (!parse_mmacro_spec(tline
, ed
, pp_directives
[i
])) {
2886 return DIRECTIVE_FOUND
;
2890 ed
->max_depth
= (ed
->max_depth
+ 1);
2891 ed
->ignoring
= false;
2892 ed
->prev
= defining
;
2895 eed
= (ExpDef
*) hash_findix(&expdefs
, ed
->name
);
2897 if (!strcmp(eed
->name
, ed
->name
) &&
2898 (eed
->nparam_min
<= ed
->nparam_max
|| ed
->plus
) &&
2899 (ed
->nparam_min
<= eed
->nparam_max
|| eed
->plus
)) {
2900 error(ERR_WARNING
|ERR_PASS1
,
2901 "redefining multi-line macro `%s'", ed
->name
);
2902 return DIRECTIVE_FOUND
;
2906 free_tlist(origline
);
2907 return DIRECTIVE_FOUND
;
2911 if (defining
!= NULL
) {
2912 if (defining
->type
== EXP_MMACRO
) {
2913 if (defining
->def_depth
> 0) {
2914 defining
->def_depth
--;
2915 return NO_DIRECTIVE_FOUND
;
2918 return NO_DIRECTIVE_FOUND
;
2921 if (!(defining
) || (defining
->type
!= EXP_MMACRO
)) {
2922 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2923 return DIRECTIVE_FOUND
;
2925 edhead
= (ExpDef
**) hash_findi_add(&expdefs
, defining
->name
);
2926 defining
->next
= *edhead
;
2929 defining
= ed
->prev
;
2930 ed
->prev
= expansions
;
2933 free_tlist(origline
);
2934 return DIRECTIVE_FOUND
;
2937 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2939 * We must search along istk->expansion until we hit a
2940 * macro invocation. Then we disable the emitting state(s)
2941 * between exitmacro and endmacro.
2943 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
) {
2944 if(ei
->type
== EXP_MMACRO
) {
2951 * Set all invocations leading back to the macro
2952 * invocation to a non-emitting state.
2954 for (eei
= istk
->expansion
; eei
!= ei
; eei
= eei
->prev
) {
2955 eei
->emitting
= false;
2957 eei
->emitting
= false;
2959 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2961 free_tlist(origline
);
2962 return DIRECTIVE_FOUND
;
2966 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2971 spec
.casesense
= (i
== PP_UNMACRO
);
2972 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2973 return DIRECTIVE_FOUND
;
2975 ed_p
= (ExpDef
**) hash_findi(&expdefs
, spec
.name
, NULL
);
2976 while (ed_p
&& *ed_p
) {
2978 if (ed
->casesense
== spec
.casesense
&&
2979 !mstrcmp(ed
->name
, spec
.name
, spec
.casesense
) &&
2980 ed
->nparam_min
== spec
.nparam_min
&&
2981 ed
->nparam_max
== spec
.nparam_max
&&
2982 ed
->plus
== spec
.plus
) {
2989 free_tlist(origline
);
2990 free_tlist(spec
.dlist
);
2991 return DIRECTIVE_FOUND
;
2995 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
2996 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2997 tline
= tline
->next
;
2999 free_tlist(origline
);
3000 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
3001 return DIRECTIVE_FOUND
;
3003 t
= expand_smacro(tline
->next
);
3005 free_tlist(origline
);
3008 tokval
.t_type
= TOKEN_INVALID
;
3010 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3013 return DIRECTIVE_FOUND
;
3015 error(ERR_WARNING
|ERR_PASS1
,
3016 "trailing garbage after expression ignored");
3017 if (!is_simple(evalresult
)) {
3018 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
3019 return DIRECTIVE_FOUND
;
3021 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
) {
3022 if (ei
->type
== EXP_MMACRO
) {
3027 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
3028 } else if (ei
->nparam
== 0) {
3030 "`%%rotate' invoked within macro without parameters");
3032 int rotate
= ei
->rotate
+ reloc_value(evalresult
);
3034 rotate
%= (int)ei
->nparam
;
3036 rotate
+= ei
->nparam
;
3037 ei
->rotate
= rotate
;
3039 return DIRECTIVE_FOUND
;
3042 if (defining
!= NULL
) {
3043 if (defining
->type
== EXP_REP
) {
3044 defining
->def_depth
++;
3046 return NO_DIRECTIVE_FOUND
;
3050 tline
= tline
->next
;
3051 } while (tok_type_(tline
, TOK_WHITESPACE
));
3053 if (tok_type_(tline
, TOK_ID
) &&
3054 nasm_stricmp(tline
->text
, ".nolist") == 0) {
3057 tline
= tline
->next
;
3058 } while (tok_type_(tline
, TOK_WHITESPACE
));
3062 t
= expand_smacro(tline
);
3064 tokval
.t_type
= TOKEN_INVALID
;
3066 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3068 free_tlist(origline
);
3069 return DIRECTIVE_FOUND
;
3072 error(ERR_WARNING
|ERR_PASS1
,
3073 "trailing garbage after expression ignored");
3074 if (!is_simple(evalresult
)) {
3075 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
3076 return DIRECTIVE_FOUND
;
3078 count
= reloc_value(evalresult
);
3079 if (count
>= REP_LIMIT
) {
3080 error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
3085 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
3088 free_tlist(origline
);
3089 ed
= new_ExpDef(EXP_REP
);
3090 ed
->nolist
= nolist
;
3093 ed
->max_depth
= (count
- 1);
3094 ed
->ignoring
= false;
3095 ed
->prev
= defining
;
3097 return DIRECTIVE_FOUND
;
3100 if (defining
!= NULL
) {
3101 if (defining
->type
== EXP_REP
) {
3102 if (defining
->def_depth
> 0) {
3103 defining
->def_depth
--;
3104 return NO_DIRECTIVE_FOUND
;
3107 return NO_DIRECTIVE_FOUND
;
3110 if ((defining
== NULL
) || (defining
->type
!= EXP_REP
)) {
3111 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
3112 return DIRECTIVE_FOUND
;
3116 * Now we have a "macro" defined - although it has no name
3117 * and we won't be entering it in the hash tables - we must
3118 * push a macro-end marker for it on to istk->expansion.
3119 * After that, it will take care of propagating itself (a
3120 * macro-end marker line for a macro which is really a %rep
3121 * block will cause the macro to be re-expanded, complete
3122 * with another macro-end marker to ensure the process
3123 * continues) until the whole expansion is forcibly removed
3124 * from istk->expansion by a %exitrep.
3127 defining
= ed
->prev
;
3128 ed
->prev
= expansions
;
3130 ei
= new_ExpInv(EXP_REP
, ed
);
3131 ei
->current
= ed
->line
;
3132 ei
->emitting
= ((ed
->max_depth
> 0) ? true : false);
3133 list
->uplevel(ed
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
3134 ei
->prev
= istk
->expansion
;
3135 istk
->expansion
= ei
;
3136 free_tlist(origline
);
3137 return DIRECTIVE_FOUND
;
3140 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3142 * We must search along istk->expansion until we hit a
3143 * rep invocation. Then we disable the emitting state(s)
3144 * between exitrep and endrep.
3146 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
) {
3147 if (ei
->type
== EXP_REP
) {
3154 * Set all invocations leading back to the rep
3155 * invocation to a non-emitting state.
3157 for (eei
= istk
->expansion
; eei
!= ei
; eei
= eei
->prev
) {
3158 eei
->emitting
= false;
3160 eei
->emitting
= false;
3161 eei
->current
= NULL
;
3162 eei
->def
->cur_depth
= eei
->def
->max_depth
;
3164 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
3166 free_tlist(origline
);
3167 return DIRECTIVE_FOUND
;
3173 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3174 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
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] != '$'))) {
3182 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3184 free_tlist(origline
);
3185 return DIRECTIVE_FOUND
;
3188 ctx
= get_ctx(tline
->text
, &mname
, false);
3190 param_start
= tline
= tline
->next
;
3193 /* Expand the macro definition now for %xdefine and %ixdefine */
3194 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3195 tline
= expand_smacro(tline
);
3197 if (tok_is_(tline
, "(")) {
3199 * This macro has parameters.
3202 tline
= tline
->next
;
3206 error(ERR_NONFATAL
, "parameter identifier expected");
3207 free_tlist(origline
);
3208 return DIRECTIVE_FOUND
;
3210 if (tline
->type
!= TOK_ID
) {
3212 "`%s': parameter identifier expected",
3214 free_tlist(origline
);
3215 return DIRECTIVE_FOUND
;
3217 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3218 tline
= tline
->next
;
3220 if (tok_is_(tline
, ",")) {
3221 tline
= tline
->next
;
3223 if (!tok_is_(tline
, ")")) {
3225 "`)' expected to terminate macro template");
3226 free_tlist(origline
);
3227 return DIRECTIVE_FOUND
;
3233 tline
= tline
->next
;
3235 if (tok_type_(tline
, TOK_WHITESPACE
))
3236 last
= tline
, tline
= tline
->next
;
3241 if (t
->type
== TOK_ID
) {
3242 list_for_each(tt
, param_start
)
3243 if (tt
->type
>= TOK_SMAC_PARAM
&&
3244 !strcmp(tt
->text
, t
->text
))
3248 t
->next
= macro_start
;
3253 * Good. We now have a macro name, a parameter count, and a
3254 * token list (in reverse order) for an expansion. We ought
3255 * to be OK just to create an SMacro, store it, and let
3256 * free_tlist have the rest of the line (which we have
3257 * carefully re-terminated after chopping off the expansion
3260 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3261 free_tlist(origline
);
3262 return DIRECTIVE_FOUND
;
3265 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3266 tline
= tline
->next
;
3268 tline
= expand_id(tline
);
3269 if (!tline
|| (tline
->type
!= TOK_ID
&&
3270 (tline
->type
!= TOK_PREPROC_ID
||
3271 tline
->text
[1] != '$'))) {
3272 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3273 free_tlist(origline
);
3274 return DIRECTIVE_FOUND
;
3277 error(ERR_WARNING
|ERR_PASS1
,
3278 "trailing garbage after macro name ignored");
3281 /* Find the context that symbol belongs to */
3282 ctx
= get_ctx(tline
->text
, &mname
, false);
3283 undef_smacro(ctx
, mname
);
3284 free_tlist(origline
);
3285 return DIRECTIVE_FOUND
;
3289 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3290 casesense
= (i
== PP_DEFSTR
);
3292 tline
= tline
->next
;
3294 tline
= expand_id(tline
);
3295 if (!tline
|| (tline
->type
!= TOK_ID
&&
3296 (tline
->type
!= TOK_PREPROC_ID
||
3297 tline
->text
[1] != '$'))) {
3298 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3300 free_tlist(origline
);
3301 return DIRECTIVE_FOUND
;
3304 ctx
= get_ctx(tline
->text
, &mname
, false);
3306 tline
= expand_smacro(tline
->next
);
3309 while (tok_type_(tline
, TOK_WHITESPACE
))
3310 tline
= delete_Token(tline
);
3312 p
= detoken(tline
, false);
3313 macro_start
= nasm_malloc(sizeof(*macro_start
));
3314 macro_start
->next
= NULL
;
3315 macro_start
->text
= nasm_quote(p
, strlen(p
));
3316 macro_start
->type
= TOK_STRING
;
3317 macro_start
->a
.mac
= NULL
;
3321 * We now have a macro name, an implicit parameter count of
3322 * zero, and a string token to use as an expansion. Create
3323 * and store an SMacro.
3325 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3326 free_tlist(origline
);
3327 return DIRECTIVE_FOUND
;
3331 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3332 casesense
= (i
== PP_DEFTOK
);
3334 tline
= tline
->next
;
3336 tline
= expand_id(tline
);
3337 if (!tline
|| (tline
->type
!= TOK_ID
&&
3338 (tline
->type
!= TOK_PREPROC_ID
||
3339 tline
->text
[1] != '$'))) {
3341 "`%s' expects a macro identifier as first parameter",
3343 free_tlist(origline
);
3344 return DIRECTIVE_FOUND
;
3346 ctx
= get_ctx(tline
->text
, &mname
, false);
3348 tline
= expand_smacro(tline
->next
);
3352 while (tok_type_(t
, TOK_WHITESPACE
))
3354 /* t should now point to the string */
3355 if (!tok_type_(t
, TOK_STRING
)) {
3357 "`%s` requires string as second parameter",
3360 free_tlist(origline
);
3361 return DIRECTIVE_FOUND
;
3365 * Convert the string to a token stream. Note that smacros
3366 * are stored with the token stream reversed, so we have to
3367 * reverse the output of tokenize().
3369 nasm_unquote_cstr(t
->text
, i
);
3370 macro_start
= reverse_tokens(tokenize(t
->text
));
3373 * We now have a macro name, an implicit parameter count of
3374 * zero, and a numeric token to use as an expansion. Create
3375 * and store an SMacro.
3377 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3379 free_tlist(origline
);
3380 return DIRECTIVE_FOUND
;
3383 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3386 StrList
*xsl
= NULL
;
3387 StrList
**xst
= &xsl
;
3391 tline
= tline
->next
;
3393 tline
= expand_id(tline
);
3394 if (!tline
|| (tline
->type
!= TOK_ID
&&
3395 (tline
->type
!= TOK_PREPROC_ID
||
3396 tline
->text
[1] != '$'))) {
3398 "`%%pathsearch' expects a macro identifier as first parameter");
3399 free_tlist(origline
);
3400 return DIRECTIVE_FOUND
;
3402 ctx
= get_ctx(tline
->text
, &mname
, false);
3404 tline
= expand_smacro(tline
->next
);
3408 while (tok_type_(t
, TOK_WHITESPACE
))
3411 if (!t
|| (t
->type
!= TOK_STRING
&&
3412 t
->type
!= TOK_INTERNAL_STRING
)) {
3413 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3415 free_tlist(origline
);
3416 return DIRECTIVE_FOUND
; /* but we did _something_ */
3419 error(ERR_WARNING
|ERR_PASS1
,
3420 "trailing garbage after `%%pathsearch' ignored");
3422 if (t
->type
!= TOK_INTERNAL_STRING
)
3423 nasm_unquote(p
, NULL
);
3425 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3428 fclose(fp
); /* Don't actually care about the file */
3430 macro_start
= nasm_malloc(sizeof(*macro_start
));
3431 macro_start
->next
= NULL
;
3432 macro_start
->text
= nasm_quote(p
, strlen(p
));
3433 macro_start
->type
= TOK_STRING
;
3434 macro_start
->a
.mac
= NULL
;
3439 * We now have a macro name, an implicit parameter count of
3440 * zero, and a string token to use as an expansion. Create
3441 * and store an SMacro.
3443 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3445 free_tlist(origline
);
3446 return DIRECTIVE_FOUND
;
3450 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3453 tline
= tline
->next
;
3455 tline
= expand_id(tline
);
3456 if (!tline
|| (tline
->type
!= TOK_ID
&&
3457 (tline
->type
!= TOK_PREPROC_ID
||
3458 tline
->text
[1] != '$'))) {
3460 "`%%strlen' expects a macro identifier as first parameter");
3461 free_tlist(origline
);
3462 return DIRECTIVE_FOUND
;
3464 ctx
= get_ctx(tline
->text
, &mname
, false);
3466 tline
= expand_smacro(tline
->next
);
3470 while (tok_type_(t
, TOK_WHITESPACE
))
3472 /* t should now point to the string */
3473 if (!tok_type_(t
, TOK_STRING
)) {
3475 "`%%strlen` requires string as second parameter");
3477 free_tlist(origline
);
3478 return DIRECTIVE_FOUND
;
3481 macro_start
= nasm_malloc(sizeof(*macro_start
));
3482 macro_start
->next
= NULL
;
3483 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3484 macro_start
->a
.mac
= NULL
;
3487 * We now have a macro name, an implicit parameter count of
3488 * zero, and a numeric token to use as an expansion. Create
3489 * and store an SMacro.
3491 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3493 free_tlist(origline
);
3494 return DIRECTIVE_FOUND
;
3497 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3500 tline
= tline
->next
;
3502 tline
= expand_id(tline
);
3503 if (!tline
|| (tline
->type
!= TOK_ID
&&
3504 (tline
->type
!= TOK_PREPROC_ID
||
3505 tline
->text
[1] != '$'))) {
3507 "`%%strcat' expects a macro identifier as first parameter");
3508 free_tlist(origline
);
3509 return DIRECTIVE_FOUND
;
3511 ctx
= get_ctx(tline
->text
, &mname
, false);
3513 tline
= expand_smacro(tline
->next
);
3517 list_for_each(t
, tline
) {
3519 case TOK_WHITESPACE
:
3522 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3525 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3527 /* else fall through */
3530 "non-string passed to `%%strcat' (%d)", t
->type
);
3532 free_tlist(origline
);
3533 return DIRECTIVE_FOUND
;
3537 p
= pp
= nasm_malloc(len
);
3538 list_for_each(t
, tline
) {
3539 if (t
->type
== TOK_STRING
) {
3540 memcpy(p
, t
->text
, t
->a
.len
);
3546 * We now have a macro name, an implicit parameter count of
3547 * zero, and a numeric token to use as an expansion. Create
3548 * and store an SMacro.
3550 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3551 macro_start
->text
= nasm_quote(pp
, len
);
3553 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3555 free_tlist(origline
);
3556 return DIRECTIVE_FOUND
;
3559 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3561 int64_t start
, count
;
3566 tline
= tline
->next
;
3568 tline
= expand_id(tline
);
3569 if (!tline
|| (tline
->type
!= TOK_ID
&&
3570 (tline
->type
!= TOK_PREPROC_ID
||
3571 tline
->text
[1] != '$'))) {
3573 "`%%substr' expects a macro identifier as first parameter");
3574 free_tlist(origline
);
3575 return DIRECTIVE_FOUND
;
3577 ctx
= get_ctx(tline
->text
, &mname
, false);
3579 tline
= expand_smacro(tline
->next
);
3582 if (tline
) /* skip expanded id */
3584 while (tok_type_(t
, TOK_WHITESPACE
))
3587 /* t should now point to the string */
3588 if (!tok_type_(t
, TOK_STRING
)) {
3590 "`%%substr` requires string as second parameter");
3592 free_tlist(origline
);
3593 return DIRECTIVE_FOUND
;
3598 tokval
.t_type
= TOKEN_INVALID
;
3599 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3603 free_tlist(origline
);
3604 return DIRECTIVE_FOUND
;
3605 } else if (!is_simple(evalresult
)) {
3606 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3608 free_tlist(origline
);
3609 return DIRECTIVE_FOUND
;
3611 start
= evalresult
->value
- 1;
3613 while (tok_type_(tt
, TOK_WHITESPACE
))
3616 count
= 1; /* Backwards compatibility: one character */
3618 tokval
.t_type
= TOKEN_INVALID
;
3619 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3623 free_tlist(origline
);
3624 return DIRECTIVE_FOUND
;
3625 } else if (!is_simple(evalresult
)) {
3626 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3628 free_tlist(origline
);
3629 return DIRECTIVE_FOUND
;
3631 count
= evalresult
->value
;
3634 len
= nasm_unquote(t
->text
, NULL
);
3635 /* make start and count being in range */
3639 count
= len
+ count
+ 1 - start
;
3640 if (start
+ count
> (int64_t)len
)
3641 count
= len
- start
;
3642 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3643 start
= -1, count
= 0; /* empty string */
3645 macro_start
= nasm_malloc(sizeof(*macro_start
));
3646 macro_start
->next
= NULL
;
3647 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3648 macro_start
->type
= TOK_STRING
;
3649 macro_start
->a
.mac
= NULL
;
3652 * We now have a macro name, an implicit parameter count of
3653 * zero, and a numeric token to use as an expansion. Create
3654 * and store an SMacro.
3656 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3658 free_tlist(origline
);
3659 return DIRECTIVE_FOUND
;
3664 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3665 casesense
= (i
== PP_ASSIGN
);
3667 tline
= tline
->next
;
3669 tline
= expand_id(tline
);
3670 if (!tline
|| (tline
->type
!= TOK_ID
&&
3671 (tline
->type
!= TOK_PREPROC_ID
||
3672 tline
->text
[1] != '$'))) {
3674 "`%%%sassign' expects a macro identifier",
3675 (i
== PP_IASSIGN
? "i" : ""));
3676 free_tlist(origline
);
3677 return DIRECTIVE_FOUND
;
3679 ctx
= get_ctx(tline
->text
, &mname
, false);
3681 tline
= expand_smacro(tline
->next
);
3686 tokval
.t_type
= TOKEN_INVALID
;
3688 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3691 free_tlist(origline
);
3692 return DIRECTIVE_FOUND
;
3696 error(ERR_WARNING
|ERR_PASS1
,
3697 "trailing garbage after expression ignored");
3699 if (!is_simple(evalresult
)) {
3701 "non-constant value given to `%%%sassign'",
3702 (i
== PP_IASSIGN
? "i" : ""));
3703 free_tlist(origline
);
3704 return DIRECTIVE_FOUND
;
3707 macro_start
= nasm_malloc(sizeof(*macro_start
));
3708 macro_start
->next
= NULL
;
3709 make_tok_num(macro_start
, reloc_value(evalresult
));
3710 macro_start
->a
.mac
= NULL
;
3713 * We now have a macro name, an implicit parameter count of
3714 * zero, and a numeric token to use as an expansion. Create
3715 * and store an SMacro.
3717 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3718 free_tlist(origline
);
3719 return DIRECTIVE_FOUND
;
3722 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3724 * Syntax is `%line nnn[+mmm] [filename]'
3726 tline
= tline
->next
;
3728 if (!tok_type_(tline
, TOK_NUMBER
)) {
3729 error(ERR_NONFATAL
, "`%%line' expects line number");
3730 free_tlist(origline
);
3731 return DIRECTIVE_FOUND
;
3733 k
= readnum(tline
->text
, &err
);
3735 tline
= tline
->next
;
3736 if (tok_is_(tline
, "+")) {
3737 tline
= tline
->next
;
3738 if (!tok_type_(tline
, TOK_NUMBER
)) {
3739 error(ERR_NONFATAL
, "`%%line' expects line increment");
3740 free_tlist(origline
);
3741 return DIRECTIVE_FOUND
;
3743 m
= readnum(tline
->text
, &err
);
3744 tline
= tline
->next
;
3750 nasm_free(src_set_fname(detoken(tline
, false)));
3752 free_tlist(origline
);
3753 return DIRECTIVE_FOUND
;
3756 if (defining
!= NULL
) {
3757 if (defining
->type
== EXP_WHILE
) {
3758 defining
->def_depth
++;
3760 return NO_DIRECTIVE_FOUND
;
3763 if ((istk
->expansion
!= NULL
) &&
3764 (istk
->expansion
->emitting
== false)) {
3768 l
->first
= copy_Token(tline
->next
);
3769 j
= if_condition(tline
->next
, i
);
3770 tline
->next
= NULL
; /* it got freed */
3771 j
= (((j
< 0) ? COND_NEVER
: j
) ? COND_IF_TRUE
: COND_IF_FALSE
);
3773 ed
= new_ExpDef(EXP_WHILE
);
3776 ed
->max_depth
= DEADMAN_LIMIT
;
3777 ed
->ignoring
= ((ed
->state
== COND_IF_TRUE
) ? false : true);
3778 if (ed
->ignoring
== false) {
3781 } else if (l
!= NULL
) {
3782 delete_Token(l
->first
);
3786 ed
->prev
= defining
;
3788 free_tlist(origline
);
3789 return DIRECTIVE_FOUND
;
3792 if (defining
!= NULL
) {
3793 if (defining
->type
== EXP_WHILE
) {
3794 if (defining
->def_depth
> 0) {
3795 defining
->def_depth
--;
3796 return NO_DIRECTIVE_FOUND
;
3799 return NO_DIRECTIVE_FOUND
;
3802 if (tline
->next
!= NULL
) {
3803 error_precond(ERR_WARNING
|ERR_PASS1
,
3804 "trailing garbage after `%%endwhile' ignored");
3806 if ((defining
== NULL
) || (defining
->type
!= EXP_WHILE
)) {
3807 error(ERR_NONFATAL
, "`%%endwhile': no matching `%%while'");
3808 return DIRECTIVE_FOUND
;
3811 defining
= ed
->prev
;
3812 if (ed
->ignoring
== false) {
3813 ed
->prev
= expansions
;
3815 ei
= new_ExpInv(EXP_WHILE
, ed
);
3816 ei
->current
= ed
->line
->next
;
3817 ei
->emitting
= true;
3818 ei
->prev
= istk
->expansion
;
3819 istk
->expansion
= ei
;
3823 free_tlist(origline
);
3824 return DIRECTIVE_FOUND
;
3827 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3829 * We must search along istk->expansion until we hit a
3830 * while invocation. Then we disable the emitting state(s)
3831 * between exitwhile and endwhile.
3833 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
) {
3834 if (ei
->type
== EXP_WHILE
) {
3841 * Set all invocations leading back to the while
3842 * invocation to a non-emitting state.
3844 for (eei
= istk
->expansion
; eei
!= ei
; eei
= eei
->prev
) {
3845 eei
->emitting
= false;
3847 eei
->emitting
= false;
3848 eei
->current
= NULL
;
3849 eei
->def
->cur_depth
= eei
->def
->max_depth
;
3851 error(ERR_NONFATAL
, "`%%exitwhile' not within `%%while' block");
3853 free_tlist(origline
);
3854 return DIRECTIVE_FOUND
;
3857 if (defining
!= NULL
) {
3858 if (defining
->type
== EXP_COMMENT
) {
3859 defining
->def_depth
++;
3861 return NO_DIRECTIVE_FOUND
;
3863 ed
= new_ExpDef(EXP_COMMENT
);
3864 ed
->ignoring
= true;
3865 ed
->prev
= defining
;
3867 free_tlist(origline
);
3868 return DIRECTIVE_FOUND
;
3871 if (defining
!= NULL
) {
3872 if (defining
->type
== EXP_COMMENT
) {
3873 if (defining
->def_depth
> 0) {
3874 defining
->def_depth
--;
3875 return NO_DIRECTIVE_FOUND
;
3878 return NO_DIRECTIVE_FOUND
;
3881 if ((defining
== NULL
) || (defining
->type
!= EXP_COMMENT
)) {
3882 error(ERR_NONFATAL
, "`%%endcomment': no matching `%%comment'");
3883 return DIRECTIVE_FOUND
;
3886 defining
= ed
->prev
;
3888 free_tlist(origline
);
3889 return DIRECTIVE_FOUND
;
3892 if (defining
!= NULL
) return NO_DIRECTIVE_FOUND
;
3893 if (in_final
!= false) {
3894 error(ERR_FATAL
, "`%%final' cannot be used recursively");
3896 tline
= tline
->next
;
3898 if (tline
== NULL
) {
3899 error(ERR_NONFATAL
, "`%%final' expects at least one parameter");
3902 l
->first
= copy_Token(tline
);
3906 free_tlist(origline
);
3907 return DIRECTIVE_FOUND
;
3911 "preprocessor directive `%s' not yet implemented",
3913 return DIRECTIVE_FOUND
;
3918 * Ensure that a macro parameter contains a condition code and
3919 * nothing else. Return the condition code index if so, or -1
3922 static int find_cc(Token
* t
)
3928 return -1; /* Probably a %+ without a space */
3931 if (t
->type
!= TOK_ID
)
3935 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3939 j
= ARRAY_SIZE(conditions
);
3942 m
= nasm_stricmp(t
->text
, conditions
[k
]);
3957 static bool paste_tokens(Token
**head
, const struct tokseq_match
*m
,
3958 int mnum
, bool handle_paste_tokens
)
3960 Token
**tail
, *t
, *tt
;
3962 bool did_paste
= false;
3966 /* Now handle token pasting... */
3969 while ((t
= *tail
) && (tt
= t
->next
)) {
3971 case TOK_WHITESPACE
:
3972 if (tt
->type
== TOK_WHITESPACE
) {
3973 /* Zap adjacent whitespace tokens */
3974 t
->next
= delete_Token(tt
);
3976 /* Do not advance paste_head here */
3980 case TOK_PASTE
: /* %+ */
3981 if (handle_paste_tokens
) {
3982 /* Zap %+ and whitespace tokens to the right */
3983 while (t
&& (t
->type
== TOK_WHITESPACE
||
3984 t
->type
== TOK_PASTE
))
3985 t
= *tail
= delete_Token(t
);
3986 if (!paste_head
|| !t
)
3987 break; /* Nothing to paste with */
3991 while (tok_type_(tt
, TOK_WHITESPACE
))
3992 tt
= t
->next
= delete_Token(tt
);
3994 tmp
= nasm_strcat(t
->text
, tt
->text
);
3996 tt
= delete_Token(tt
);
3997 t
= *tail
= tokenize(tmp
);
4003 t
->next
= tt
; /* Attach the remaining token chain */
4010 /* else fall through */
4013 * Concatenation of tokens might look nontrivial
4014 * but in real it's pretty simple -- the caller
4015 * prepares the masks of token types to be concatenated
4016 * and we simply find matched sequences and slip
4019 for (i
= 0; i
< mnum
; i
++) {
4020 if (PP_CONCAT_MASK(t
->type
) & m
[i
].mask_head
) {
4024 while (tt
&& (PP_CONCAT_MASK(tt
->type
) & m
[i
].mask_tail
)) {
4025 len
+= strlen(tt
->text
);
4030 * Now tt points to the first token after
4031 * the potential paste area...
4033 if (tt
!= t
->next
) {
4034 /* We have at least two tokens... */
4035 len
+= strlen(t
->text
);
4036 p
= tmp
= nasm_malloc(len
+1);
4039 p
= strchr(p
, '\0');
4040 t
= delete_Token(t
);
4042 t
= *tail
= tokenize(tmp
);
4048 t
->next
= tt
; /* Attach the remaining token chain */
4056 if (i
>= mnum
) { /* no match */
4058 if (!tok_type_(t
->next
, TOK_WHITESPACE
))
4068 * expands to a list of tokens from %{x:y}
4070 static Token
*expand_mmac_params_range(ExpInv
*ei
, Token
*tline
, Token
***last
)
4072 Token
*t
= tline
, **tt
, *tm
, *head
;
4076 pos
= strchr(tline
->text
, ':');
4079 lst
= atoi(pos
+ 1);
4080 fst
= atoi(tline
->text
+ 1);
4083 * only macros params are accounted so
4084 * if someone passes %0 -- we reject such
4087 if (lst
== 0 || fst
== 0)
4090 /* the values should be sane */
4091 if ((fst
> (int)ei
->nparam
|| fst
< (-(int)ei
->nparam
)) ||
4092 (lst
> (int)ei
->nparam
|| lst
< (-(int)ei
->nparam
)))
4095 fst
= fst
< 0 ? fst
+ (int)ei
->nparam
+ 1: fst
;
4096 lst
= lst
< 0 ? lst
+ (int)ei
->nparam
+ 1: lst
;
4098 /* counted from zero */
4102 * it will be at least one token
4104 tm
= ei
->params
[(fst
+ ei
->rotate
) % ei
->nparam
];
4105 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
4106 head
= t
, tt
= &t
->next
;
4108 for (i
= fst
+ 1; i
<= lst
; i
++) {
4109 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
4110 *tt
= t
, tt
= &t
->next
;
4111 j
= (i
+ ei
->rotate
) % ei
->nparam
;
4113 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
4114 *tt
= t
, tt
= &t
->next
;
4117 for (i
= fst
- 1; i
>= lst
; i
--) {
4118 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
4119 *tt
= t
, tt
= &t
->next
;
4120 j
= (i
+ ei
->rotate
) % ei
->nparam
;
4122 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
4123 *tt
= t
, tt
= &t
->next
;
4131 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
4137 * Expand MMacro-local things: parameter references (%0, %n, %+n,
4138 * %-n) and MMacro-local identifiers (%%foo) as well as
4139 * macro indirection (%[...]) and range (%{..:..}).
4141 static Token
*expand_mmac_params(Token
* tline
)
4143 Token
*t
, *tt
, **tail
, *thead
;
4144 bool changed
= false;
4151 if (tline
->type
== TOK_PREPROC_ID
&&
4152 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
4153 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
4154 tline
->text
[1] == '%')) {
4156 int type
= 0, cc
; /* type = 0 to placate optimisers */
4163 tline
= tline
->next
;
4165 for (ei
= istk
->expansion
; ei
!= NULL
; ei
= ei
->prev
) {
4166 if (ei
->type
== EXP_MMACRO
) {
4171 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
4173 pos
= strchr(t
->text
, ':');
4175 switch (t
->text
[1]) {
4177 * We have to make a substitution of one of the
4178 * forms %1, %-1, %+1, %%foo, %0.
4181 if ((strlen(t
->text
) > 2) && (t
->text
[2] == '0')) {
4183 text
= nasm_strdup(ei
->label_text
);
4186 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", ei
->nparam
);
4187 text
= nasm_strdup(tmpbuf
);
4192 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
4194 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
4197 n
= atoi(t
->text
+ 2) - 1;
4198 if (n
>= ei
->nparam
)
4202 n
= (n
+ ei
->rotate
) % ei
->nparam
;
4208 "macro parameter %d is not a condition code",
4213 if (inverse_ccs
[cc
] == -1) {
4215 "condition code `%s' is not invertible",
4219 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
4223 n
= atoi(t
->text
+ 2) - 1;
4224 if (n
>= ei
->nparam
)
4228 n
= (n
+ ei
->rotate
) % ei
->nparam
;
4234 "macro parameter %d is not a condition code",
4239 text
= nasm_strdup(conditions
[cc
]);
4243 n
= atoi(t
->text
+ 1) - 1;
4244 if (n
>= ei
->nparam
)
4248 n
= (n
+ ei
->rotate
) % ei
->nparam
;
4252 for (i
= 0; i
< ei
->paramlen
[n
]; i
++) {
4253 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
4254 tail
= &(*tail
)->next
;
4258 text
= NULL
; /* we've done it here */
4263 * seems we have a parameters range here
4265 Token
*head
, **last
;
4266 head
= expand_mmac_params_range(ei
, t
, &last
);
4287 } else if (tline
->type
== TOK_INDIRECT
) {
4289 tline
= tline
->next
;
4290 tt
= tokenize(t
->text
);
4291 tt
= expand_mmac_params(tt
);
4292 tt
= expand_smacro(tt
);
4295 tt
->a
.mac
= NULL
; /* Necessary? */
4303 tline
= tline
->next
;
4311 const struct tokseq_match t
[] = {
4313 PP_CONCAT_MASK(TOK_ID
) |
4314 PP_CONCAT_MASK(TOK_FLOAT
), /* head */
4315 PP_CONCAT_MASK(TOK_ID
) |
4316 PP_CONCAT_MASK(TOK_NUMBER
) |
4317 PP_CONCAT_MASK(TOK_FLOAT
) |
4318 PP_CONCAT_MASK(TOK_OTHER
) /* tail */
4321 PP_CONCAT_MASK(TOK_NUMBER
), /* head */
4322 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4325 paste_tokens(&thead
, t
, ARRAY_SIZE(t
), false);
4332 * Expand all single-line macro calls made in the given line.
4333 * Return the expanded version of the line. The original is deemed
4334 * to be destroyed in the process. (In reality we'll just move
4335 * Tokens from input to output a lot of the time, rather than
4336 * actually bothering to destroy and replicate.)
4339 static Token
*expand_smacro(Token
* tline
)
4341 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4342 SMacro
*head
= NULL
, *m
;
4345 unsigned int nparam
, sparam
;
4347 Token
*org_tline
= tline
;
4350 int deadman
= DEADMAN_LIMIT
;
4354 * Trick: we should avoid changing the start token pointer since it can
4355 * be contained in "next" field of other token. Because of this
4356 * we allocate a copy of first token and work with it; at the end of
4357 * routine we copy it back
4360 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4361 org_tline
->text
, 0);
4362 tline
->a
.mac
= org_tline
->a
.mac
;
4363 nasm_free(org_tline
->text
);
4364 org_tline
->text
= NULL
;
4367 expanded
= true; /* Always expand %+ at least once */
4373 while (tline
) { /* main token loop */
4375 error(ERR_NONFATAL
, "interminable macro recursion");
4379 if ((mname
= tline
->text
)) {
4380 /* if this token is a local macro, look in local context */
4381 if (tline
->type
== TOK_ID
) {
4382 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4383 } else if (tline
->type
== TOK_PREPROC_ID
) {
4384 ctx
= get_ctx(mname
, &mname
, false);
4385 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4390 * We've hit an identifier. As in is_mmacro below, we first
4391 * check whether the identifier is a single-line macro at
4392 * all, then think about checking for parameters if
4395 list_for_each(m
, head
)
4396 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4402 if (m
->nparam
== 0) {
4404 * Simple case: the macro is parameterless. Discard the
4405 * one token that the macro call took, and push the
4406 * expansion back on the to-do stack.
4408 if (!m
->expansion
) {
4409 if (!strcmp("__FILE__", m
->name
)) {
4412 src_get(&num
, &file
);
4413 tline
->text
= nasm_quote(file
, strlen(file
));
4414 tline
->type
= TOK_STRING
;
4418 if (!strcmp("__LINE__", m
->name
)) {
4419 nasm_free(tline
->text
);
4420 make_tok_num(tline
, src_get_linnum());
4423 if (!strcmp("__BITS__", m
->name
)) {
4424 nasm_free(tline
->text
);
4425 make_tok_num(tline
, globalbits
);
4428 tline
= delete_Token(tline
);
4433 * Complicated case: at least one macro with this name
4434 * exists and takes parameters. We must find the
4435 * parameters in the call, count them, find the SMacro
4436 * that corresponds to that form of the macro call, and
4437 * substitute for the parameters when we expand. What a
4440 /*tline = tline->next;
4441 skip_white_(tline); */
4444 while (tok_type_(t
, TOK_SMAC_END
)) {
4445 t
->a
.mac
->in_progress
= false;
4447 t
= tline
->next
= delete_Token(t
);
4450 } while (tok_type_(tline
, TOK_WHITESPACE
));
4451 if (!tok_is_(tline
, "(")) {
4453 * This macro wasn't called with parameters: ignore
4454 * the call. (Behaviour borrowed from gnu cpp.)
4463 sparam
= PARAM_DELTA
;
4464 params
= nasm_malloc(sparam
* sizeof(Token
*));
4465 params
[0] = tline
->next
;
4466 paramsize
= nasm_malloc(sparam
* sizeof(int));
4468 while (true) { /* parameter loop */
4470 * For some unusual expansions
4471 * which concatenates function call
4474 while (tok_type_(t
, TOK_SMAC_END
)) {
4475 t
->a
.mac
->in_progress
= false;
4477 t
= tline
->next
= delete_Token(t
);
4483 "macro call expects terminating `)'");
4486 if (tline
->type
== TOK_WHITESPACE
4488 if (paramsize
[nparam
])
4491 params
[nparam
] = tline
->next
;
4492 continue; /* parameter loop */
4494 if (tline
->type
== TOK_OTHER
4495 && tline
->text
[1] == 0) {
4496 char ch
= tline
->text
[0];
4497 if (ch
== ',' && !paren
&& brackets
<= 0) {
4498 if (++nparam
>= sparam
) {
4499 sparam
+= PARAM_DELTA
;
4500 params
= nasm_realloc(params
,
4501 sparam
* sizeof(Token
*));
4502 paramsize
= nasm_realloc(paramsize
,
4503 sparam
* sizeof(int));
4505 params
[nparam
] = tline
->next
;
4506 paramsize
[nparam
] = 0;
4508 continue; /* parameter loop */
4511 (brackets
> 0 || (brackets
== 0 &&
4512 !paramsize
[nparam
])))
4514 if (!(brackets
++)) {
4515 params
[nparam
] = tline
->next
;
4516 continue; /* parameter loop */
4519 if (ch
== '}' && brackets
> 0)
4520 if (--brackets
== 0) {
4522 continue; /* parameter loop */
4524 if (ch
== '(' && !brackets
)
4526 if (ch
== ')' && brackets
<= 0)
4532 error(ERR_NONFATAL
, "braces do not "
4533 "enclose all of macro parameter");
4535 paramsize
[nparam
] += white
+ 1;
4537 } /* parameter loop */
4539 while (m
&& (m
->nparam
!= nparam
||
4540 mstrcmp(m
->name
, mname
,
4544 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4545 "macro `%s' exists, "
4546 "but not taking %d parameters",
4547 mstart
->text
, nparam
);
4550 if (m
&& m
->in_progress
)
4552 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4554 * Design question: should we handle !tline, which
4555 * indicates missing ')' here, or expand those
4556 * macros anyway, which requires the (t) test a few
4560 nasm_free(paramsize
);
4564 * Expand the macro: we are placed on the last token of the
4565 * call, so that we can easily split the call from the
4566 * following tokens. We also start by pushing an SMAC_END
4567 * token for the cycle removal.
4574 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4576 m
->in_progress
= true;
4578 list_for_each(t
, m
->expansion
) {
4579 if (t
->type
>= TOK_SMAC_PARAM
) {
4580 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4584 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4585 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4587 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4593 } else if (t
->type
== TOK_PREPROC_Q
) {
4594 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4596 } else if (t
->type
== TOK_PREPROC_QQ
) {
4597 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4600 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4606 * Having done that, get rid of the macro call, and clean
4607 * up the parameters.
4610 nasm_free(paramsize
);
4613 continue; /* main token loop */
4618 if (tline
->type
== TOK_SMAC_END
) {
4619 tline
->a
.mac
->in_progress
= false;
4620 tline
= delete_Token(tline
);
4623 tline
= tline
->next
;
4631 * Now scan the entire line and look for successive TOK_IDs that resulted
4632 * after expansion (they can't be produced by tokenize()). The successive
4633 * TOK_IDs should be concatenated.
4634 * Also we look for %+ tokens and concatenate the tokens before and after
4635 * them (without white spaces in between).
4638 const struct tokseq_match t
[] = {
4640 PP_CONCAT_MASK(TOK_ID
) |
4641 PP_CONCAT_MASK(TOK_PREPROC_ID
), /* head */
4642 PP_CONCAT_MASK(TOK_ID
) |
4643 PP_CONCAT_MASK(TOK_PREPROC_ID
) |
4644 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4647 if (paste_tokens(&thead
, t
, ARRAY_SIZE(t
), true)) {
4649 * If we concatenated something, *and* we had previously expanded
4650 * an actual macro, scan the lines again for macros...
4661 *org_tline
= *thead
;
4662 /* since we just gave text to org_line, don't free it */
4664 delete_Token(thead
);
4666 /* the expression expanded to empty line;
4667 we can't return NULL for some reasons
4668 we just set the line to a single WHITESPACE token. */
4669 memset(org_tline
, 0, sizeof(*org_tline
));
4670 org_tline
->text
= NULL
;
4671 org_tline
->type
= TOK_WHITESPACE
;
4680 * Similar to expand_smacro but used exclusively with macro identifiers
4681 * right before they are fetched in. The reason is that there can be
4682 * identifiers consisting of several subparts. We consider that if there
4683 * are more than one element forming the name, user wants a expansion,
4684 * otherwise it will be left as-is. Example:
4688 * the identifier %$abc will be left as-is so that the handler for %define
4689 * will suck it and define the corresponding value. Other case:
4691 * %define _%$abc cde
4693 * In this case user wants name to be expanded *before* %define starts
4694 * working, so we'll expand %$abc into something (if it has a value;
4695 * otherwise it will be left as-is) then concatenate all successive
4698 static Token
*expand_id(Token
* tline
)
4700 Token
*cur
, *oldnext
= NULL
;
4702 if (!tline
|| !tline
->next
)
4707 (cur
->next
->type
== TOK_ID
||
4708 cur
->next
->type
== TOK_PREPROC_ID
4709 || cur
->next
->type
== TOK_NUMBER
))
4712 /* If identifier consists of just one token, don't expand */
4717 oldnext
= cur
->next
; /* Detach the tail past identifier */
4718 cur
->next
= NULL
; /* so that expand_smacro stops here */
4721 tline
= expand_smacro(tline
);
4724 /* expand_smacro possibly changhed tline; re-scan for EOL */
4726 while (cur
&& cur
->next
)
4729 cur
->next
= oldnext
;
4736 * Determine whether the given line constitutes a multi-line macro
4737 * call, and return the ExpDef structure called if so. Doesn't have
4738 * to check for an initial label - that's taken care of in
4739 * expand_mmacro - but must check numbers of parameters. Guaranteed
4740 * to be called with tline->type == TOK_ID, so the putative macro
4741 * name is easy to find.
4743 static ExpDef
*is_mmacro(Token
* tline
, Token
*** params_array
)
4749 head
= (ExpDef
*) hash_findix(&expdefs
, tline
->text
);
4752 * Efficiency: first we see if any macro exists with the given
4753 * name. If not, we can return NULL immediately. _Then_ we
4754 * count the parameters, and then we look further along the
4755 * list if necessary to find the proper ExpDef.
4757 list_for_each(ed
, head
)
4758 if (!mstrcmp(ed
->name
, tline
->text
, ed
->casesense
))
4764 * OK, we have a potential macro. Count and demarcate the
4767 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4770 * So we know how many parameters we've got. Find the ExpDef
4771 * structure that handles this number.
4774 if (ed
->nparam_min
<= nparam
4775 && (ed
->plus
|| nparam
<= ed
->nparam_max
)) {
4777 * It's right, and we can use it. Add its default
4778 * parameters to the end of our list if necessary.
4780 if (ed
->defaults
&& nparam
< ed
->nparam_min
+ ed
->ndefs
) {
4782 nasm_realloc(params
,
4783 ((ed
->nparam_min
+ ed
->ndefs
+
4784 1) * sizeof(*params
)));
4785 while (nparam
< ed
->nparam_min
+ ed
->ndefs
) {
4786 params
[nparam
] = ed
->defaults
[nparam
- ed
->nparam_min
];
4791 * If we've gone over the maximum parameter count (and
4792 * we're in Plus mode), ignore parameters beyond
4795 if (ed
->plus
&& nparam
> ed
->nparam_max
)
4796 nparam
= ed
->nparam_max
;
4798 * Then terminate the parameter list, and leave.
4800 if (!params
) { /* need this special case */
4801 params
= nasm_malloc(sizeof(*params
));
4804 params
[nparam
] = NULL
;
4805 *params_array
= params
;
4809 * This one wasn't right: look for the next one with the
4812 list_for_each(ed
, ed
->next
)
4813 if (!mstrcmp(ed
->name
, tline
->text
, ed
->casesense
))
4818 * After all that, we didn't find one with the right number of
4819 * parameters. Issue a warning, and fail to expand the macro.
4821 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4822 "macro `%s' exists, but not taking %d parameters",
4823 tline
->text
, nparam
);
4829 * Expand the multi-line macro call made by the given line, if
4830 * there is one to be expanded. If there is, push the expansion on
4831 * istk->expansion and return true. Otherwise return false.
4833 static bool expand_mmacro(Token
* tline
)
4835 Token
*label
= NULL
;
4836 int dont_prepend
= 0;
4837 Token
**params
, *t
, *mtok
;
4841 int i
, nparam
, *paramlen
;
4846 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4847 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4850 ed
= is_mmacro(t
, ¶ms
);
4856 * We have an id which isn't a macro call. We'll assume
4857 * it might be a label; we'll also check to see if a
4858 * colon follows it. Then, if there's another id after
4859 * that lot, we'll check it again for macro-hood.
4863 if (tok_type_(t
, TOK_WHITESPACE
))
4864 last
= t
, t
= t
->next
;
4865 if (tok_is_(t
, ":")) {
4867 last
= t
, t
= t
->next
;
4868 if (tok_type_(t
, TOK_WHITESPACE
))
4869 last
= t
, t
= t
->next
;
4871 if (!tok_type_(t
, TOK_ID
) || !(ed
= is_mmacro(t
, ¶ms
)))
4879 * Fix up the parameters: this involves stripping leading and
4880 * trailing whitespace, then stripping braces if they are
4883 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4884 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4886 for (i
= 0; params
[i
]; i
++) {
4888 int comma
= (!ed
->plus
|| i
< nparam
- 1);
4892 if (tok_is_(t
, "{"))
4893 t
= t
->next
, brace
= true, comma
= false;
4897 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4898 break; /* ... because we have hit a comma */
4899 if (comma
&& t
->type
== TOK_WHITESPACE
4900 && tok_is_(t
->next
, ","))
4901 break; /* ... or a space then a comma */
4902 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4903 break; /* ... or a brace */
4909 if (ed
->cur_depth
>= ed
->max_depth
) {
4910 if (ed
->max_depth
> 1) {
4912 "reached maximum macro recursion depth of %i for %s",
4913 ed
->max_depth
,ed
->name
);
4921 * OK, we have found a ExpDef structure representing a
4922 * previously defined mmacro. Create an expansion invocation
4923 * and point it back to the expansion definition. Substitution of
4924 * parameter tokens and macro-local tokens doesn't get done
4925 * until the single-line macro substitution process; this is
4926 * because delaying them allows us to change the semantics
4927 * later through %rotate.
4929 ei
= new_ExpInv(EXP_MMACRO
, ed
);
4930 ei
->name
= nasm_strdup(mname
);
4931 //ei->label = label;
4932 //ei->label_text = detoken(label, false);
4933 ei
->current
= ed
->line
;
4934 ei
->emitting
= true;
4935 //ei->iline = tline;
4936 ei
->params
= params
;
4937 ei
->nparam
= nparam
;
4939 ei
->paramlen
= paramlen
;
4942 ei
->prev
= istk
->expansion
;
4943 istk
->expansion
= ei
;
4946 * Special case: detect %00 on first invocation; if found,
4947 * avoid emitting any labels that precede the mmacro call.
4948 * ed->prepend is set to -1 when %00 is detected, else 1.
4950 if (ed
->prepend
== 0) {
4951 for (l
= ed
->line
; l
!= NULL
; l
= l
->next
) {
4952 for (t
= l
->first
; t
!= NULL
; t
= t
->next
) {
4953 if ((t
->type
== TOK_PREPROC_ID
) &&
4954 (strlen(t
->text
) == 3) &&
4955 (t
->text
[1] == '0') && (t
->text
[2] == '0')) {
4960 if (dont_prepend
< 0) {
4964 ed
->prepend
= ((dont_prepend
< 0) ? -1 : 1);
4968 * If we had a label, push it on as the first line of
4969 * the macro expansion.
4971 if (label
!= NULL
) {
4972 if (ed
->prepend
< 0) {
4973 ei
->label_text
= detoken(label
, false);
4975 if (dont_prepend
== 0) {
4977 while (t
->next
!= NULL
) {
4980 t
->next
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4983 l
->first
= copy_Token(label
);
4984 l
->next
= ei
->current
;
4989 list
->uplevel(ed
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4995 /* The function that actually does the error reporting */
4996 static void verror(int severity
, const char *fmt
, va_list arg
)
5000 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
5002 if (istk
&& istk
->mmac_depth
> 0) {
5003 ExpInv
*ei
= istk
->expansion
;
5004 int lineno
= ei
->lineno
;
5006 if (ei
->type
== EXP_MMACRO
)
5008 lineno
+= ei
->relno
;
5011 nasm_error(severity
, "(%s:%d) %s", ei
->def
->name
,
5014 nasm_error(severity
, "%s", buff
);
5018 * Since preprocessor always operate only on the line that didn't
5019 * arrived yet, we should always use ERR_OFFBY1.
5021 static void error(int severity
, const char *fmt
, ...)
5025 verror(severity
, fmt
, arg
);
5030 * Because %else etc are evaluated in the state context
5031 * of the previous branch, errors might get lost with error():
5032 * %if 0 ... %else trailing garbage ... %endif
5033 * So %else etc should report errors with this function.
5035 static void error_precond(int severity
, const char *fmt
, ...)
5039 /* Only ignore the error if it's really in a dead branch */
5040 if ((istk
!= NULL
) &&
5041 (istk
->expansion
!= NULL
) &&
5042 (istk
->expansion
->type
== EXP_IF
) &&
5043 (istk
->expansion
->def
->state
== COND_NEVER
))
5047 verror(severity
, fmt
, arg
);
5052 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
5057 istk
= nasm_malloc(sizeof(Include
));
5059 istk
->expansion
= NULL
;
5060 istk
->fp
= fopen(file
, "r");
5062 src_set_fname(nasm_strdup(file
));
5065 istk
->mmac_depth
= 0;
5067 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
5072 nested_mac_count
= 0;
5073 nested_rep_count
= 0;
5076 if (tasm_compatible_mode
) {
5077 stdmacpos
= nasm_stdmac
;
5079 stdmacpos
= nasm_stdmac_after_tasm
;
5081 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
5086 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
5087 * The caller, however, will also pass in 3 for preprocess-only so
5088 * we can set __PASS__ accordingly.
5090 pass
= apass
> 2 ? 2 : apass
;
5092 dephead
= deptail
= deplist
;
5094 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
5096 strcpy(sl
->str
, file
);
5098 deptail
= &sl
->next
;
5102 * Define the __PASS__ macro. This is defined here unlike
5103 * all the other builtins, because it is special -- it varies between
5106 t
= nasm_malloc(sizeof(*t
));
5108 make_tok_num(t
, apass
);
5110 define_smacro(NULL
, "__PASS__", true, 0, t
);
5113 static char *pp_getline(void)
5124 * Fetch a tokenized line, either from the expansion
5125 * buffer or from the input file.
5129 while (1) { /* until we get a line we can use */
5131 * Fetch a tokenized line from the expansion buffer
5133 if (istk
->expansion
!= NULL
) {
5134 ei
= istk
->expansion
;
5135 if (ei
->current
!= NULL
) {
5136 if (ei
->emitting
== false) {
5141 ei
->current
= l
->next
;
5143 tline
= copy_Token(l
->first
);
5144 if (((ei
->type
== EXP_REP
) ||
5145 (ei
->type
== EXP_MMACRO
) ||
5146 (ei
->type
== EXP_WHILE
))
5147 && (ei
->def
->nolist
== false)) {
5148 char *p
= detoken(tline
, false);
5149 list
->line(LIST_MACRO
, p
);
5152 if (ei
->linnum
> -1) {
5153 src_set_linnum(src_get_linnum() + 1);
5156 } else if ((ei
->type
== EXP_REP
) &&
5157 (ei
->def
->cur_depth
< ei
->def
->max_depth
)) {
5158 ei
->def
->cur_depth
++;
5159 ei
->current
= ei
->def
->line
;
5162 } else if ((ei
->type
== EXP_WHILE
) &&
5163 (ei
->def
->cur_depth
< ei
->def
->max_depth
)) {
5164 ei
->current
= ei
->def
->line
;
5166 tline
= copy_Token(ei
->current
->first
);
5167 j
= if_condition(tline
, PP_WHILE
);
5169 j
= (((j
< 0) ? COND_NEVER
: j
) ? COND_IF_TRUE
: COND_IF_FALSE
);
5170 if (j
== COND_IF_TRUE
) {
5171 ei
->current
= ei
->current
->next
;
5172 ei
->def
->cur_depth
++;
5174 ei
->emitting
= false;
5176 ei
->def
->cur_depth
= ei
->def
->max_depth
;
5180 istk
->expansion
= ei
->prev
;
5183 if ((ei
->emitting
== true) &&
5184 (ed
->max_depth
== DEADMAN_LIMIT
) &&
5185 (ed
->cur_depth
== DEADMAN_LIMIT
)
5187 error(ERR_FATAL
, "runaway expansion detected, aborting");
5189 if (ed
->cur_depth
> 0) {
5191 } else if ((ed
->type
!= EXP_MMACRO
) && (ed
->type
!= EXP_IF
)) {
5192 /***** should this really be right here??? *****/
5194 Line *l = NULL, *ll = NULL;
5195 for (l = ed->line; l != NULL;) {
5196 if (l->first != NULL) {
5197 free_tlist(l->first);
5204 expansions = ed->prev;
5208 if ((ei
->type
== EXP_REP
) ||
5209 (ei
->type
== EXP_MMACRO
) ||
5210 (ei
->type
== EXP_WHILE
)) {
5211 list
->downlevel(LIST_MACRO
);
5212 if (ei
->type
== EXP_MMACRO
) {
5217 if (ei
->linnum
> -1) {
5218 src_set_linnum(ei
->linnum
);
5226 * Read in line from input and tokenize
5229 if (line
) { /* from the current input file */
5230 line
= prepreproc(line
);
5231 tline
= tokenize(line
);
5237 * The current file has ended; work down the istk
5242 if (i
->expansion
!= NULL
) {
5244 "end of file while still in an expansion");
5246 /* only set line and file name if there's a next node */
5248 src_set_linnum(i
->lineno
);
5249 nasm_free(src_set_fname(i
->fname
));
5251 if ((i
->next
== NULL
) && (finals
!= NULL
)) {
5253 ei
= new_ExpInv(EXP_FINAL
, NULL
);
5254 ei
->emitting
= true;
5255 ei
->current
= finals
;
5256 istk
->expansion
= ei
;
5261 list
->downlevel(LIST_INCLUDE
);
5264 if (finals
!= NULL
) {
5274 if (defining
== NULL
) {
5275 tline
= expand_mmac_params(tline
);
5279 * Check the line to see if it's a preprocessor directive.
5281 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5283 } else if (defining
!= NULL
) {
5285 * We're defining an expansion. We emit nothing at all,
5286 * and just shove the tokenized line on to the definition.
5288 if (defining
->ignoring
== false) {
5289 Line
*l
= new_Line();
5291 if (defining
->line
== NULL
) {
5295 defining
->last
->next
= l
;
5299 //free_tlist(tline); /***** sanity check: is this supposed to be here? *****/
5301 defining
->linecount
++;
5303 } else if ((istk
->expansion
!= NULL
) &&
5304 (istk
->expansion
->emitting
!= true)) {
5306 * We're in a non-emitting branch of an expansion.
5307 * Emit nothing at all, not even a blank line: when we
5308 * emerge from the expansion we'll give a line-number
5309 * directive so we keep our place correctly.
5314 tline
= expand_smacro(tline
);
5315 if (expand_mmacro(tline
) != true) {
5317 * De-tokenize the line again, and emit it.
5319 line
= detoken(tline
, true);
5330 static void pp_cleanup(int pass
)
5332 if (defining
!= NULL
) {
5333 error(ERR_NONFATAL
, "end of file while still defining an expansion");
5334 while (defining
!= NULL
) {
5335 ExpDef
*ed
= defining
;
5336 defining
= ed
->prev
;
5341 while (cstk
!= NULL
)
5344 while (istk
!= NULL
) {
5348 nasm_free(i
->fname
);
5350 while (i
->expansion
!= NULL
) {
5351 ExpInv
*ei
= i
->expansion
;
5352 i
->expansion
= ei
->prev
;
5358 nasm_free(src_set_fname(NULL
));
5363 while ((i
= ipath
)) {
5372 void pp_include_path(char *path
)
5376 i
= nasm_malloc(sizeof(IncPath
));
5377 i
->path
= path
? nasm_strdup(path
) : NULL
;
5390 void pp_pre_include(char *fname
)
5392 Token
*inc
, *space
, *name
;
5395 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5396 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5397 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5405 void pp_pre_define(char *definition
)
5411 equals
= strchr(definition
, '=');
5412 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5413 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5416 space
->next
= tokenize(definition
);
5426 void pp_pre_undefine(char *definition
)
5431 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5432 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5433 space
->next
= tokenize(definition
);
5442 * This function is used to assist with "runtime" preprocessor
5443 * directives, e.g. pp_runtime("%define __BITS__ 64");
5445 * ERRORS ARE IGNORED HERE, SO MAKE COMPLETELY SURE THAT YOU
5446 * PASS A VALID STRING TO THIS FUNCTION!!!!!
5449 void pp_runtime(char *definition
)
5453 def
= tokenize(definition
);
5454 if (do_directive(def
) == NO_DIRECTIVE_FOUND
)
5459 void pp_extra_stdmac(macros_t
*macros
)
5461 extrastdmac
= macros
;
5464 static void make_tok_num(Token
* tok
, int64_t val
)
5467 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5468 tok
->text
= nasm_strdup(numbuf
);
5469 tok
->type
= TOK_NUMBER
;