daily update
[external/binutils.git] / ld / ldexp.c
1 /* This module handles expression trees.
2    Copyright (C) 1991-2014 Free Software Foundation, Inc.
3    Written by Steve Chamberlain of Cygnus Support <sac@cygnus.com>.
4
5    This file is part of the GNU Binutils.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21
22
23 /* This module is in charge of working out the contents of expressions.
24
25    It has to keep track of the relative/absness of a symbol etc. This
26    is done by keeping all values in a struct (an etree_value_type)
27    which contains a value, a section to which it is relative and a
28    valid bit.  */
29
30 #include "sysdep.h"
31 #include "bfd.h"
32 #include "bfdlink.h"
33
34 #include "ld.h"
35 #include "ldmain.h"
36 #include "ldmisc.h"
37 #include "ldexp.h"
38 #include "ldlex.h"
39 #include <ldgram.h>
40 #include "ldlang.h"
41 #include "libiberty.h"
42 #include "safe-ctype.h"
43
44 static void exp_fold_tree_1 (etree_type *);
45 static bfd_vma align_n (bfd_vma, bfd_vma);
46
47 segment_type *segments;
48
49 struct ldexp_control expld;
50
51 /* Print the string representation of the given token.  Surround it
52    with spaces if INFIX_P is TRUE.  */
53
54 static void
55 exp_print_token (token_code_type code, int infix_p)
56 {
57   static const struct
58   {
59     token_code_type code;
60     const char * name;
61   }
62   table[] =
63   {
64     { INT, "int" },
65     { NAME, "NAME" },
66     { PLUSEQ, "+=" },
67     { MINUSEQ, "-=" },
68     { MULTEQ, "*=" },
69     { DIVEQ, "/=" },
70     { LSHIFTEQ, "<<=" },
71     { RSHIFTEQ, ">>=" },
72     { ANDEQ, "&=" },
73     { OREQ, "|=" },
74     { OROR, "||" },
75     { ANDAND, "&&" },
76     { EQ, "==" },
77     { NE, "!=" },
78     { LE, "<=" },
79     { GE, ">=" },
80     { LSHIFT, "<<" },
81     { RSHIFT, ">>" },
82     { LOG2CEIL, "LOG2CEIL" },
83     { ALIGN_K, "ALIGN" },
84     { BLOCK, "BLOCK" },
85     { QUAD, "QUAD" },
86     { SQUAD, "SQUAD" },
87     { LONG, "LONG" },
88     { SHORT, "SHORT" },
89     { BYTE, "BYTE" },
90     { SECTIONS, "SECTIONS" },
91     { SIZEOF_HEADERS, "SIZEOF_HEADERS" },
92     { MEMORY, "MEMORY" },
93     { DEFINED, "DEFINED" },
94     { TARGET_K, "TARGET" },
95     { SEARCH_DIR, "SEARCH_DIR" },
96     { MAP, "MAP" },
97     { ENTRY, "ENTRY" },
98     { NEXT, "NEXT" },
99     { ALIGNOF, "ALIGNOF" },
100     { SIZEOF, "SIZEOF" },
101     { ADDR, "ADDR" },
102     { LOADADDR, "LOADADDR" },
103     { CONSTANT, "CONSTANT" },
104     { ABSOLUTE, "ABSOLUTE" },
105     { MAX_K, "MAX" },
106     { MIN_K, "MIN" },
107     { ASSERT_K, "ASSERT" },
108     { REL, "relocatable" },
109     { DATA_SEGMENT_ALIGN, "DATA_SEGMENT_ALIGN" },
110     { DATA_SEGMENT_RELRO_END, "DATA_SEGMENT_RELRO_END" },
111     { DATA_SEGMENT_END, "DATA_SEGMENT_END" },
112     { ORIGIN, "ORIGIN" },
113     { LENGTH, "LENGTH" },
114     { SEGMENT_START, "SEGMENT_START" }
115   };
116   unsigned int idx;
117
118   for (idx = 0; idx < ARRAY_SIZE (table); idx++)
119     if (table[idx].code == code)
120       break;
121
122   if (infix_p)
123     fputc (' ', config.map_file);
124
125   if (idx < ARRAY_SIZE (table))
126     fputs (table[idx].name, config.map_file);
127   else if (code < 127)
128     fputc (code, config.map_file);
129   else
130     fprintf (config.map_file, "<code %d>", code);
131
132   if (infix_p)
133     fputc (' ', config.map_file);
134 }
135
136 static void
137 make_log2ceil (void)
138 {
139   bfd_vma value = expld.result.value;
140   bfd_vma result = -1;
141   bfd_boolean round_up = FALSE;
142
143   do
144     {
145       result++;
146       /* If more than one bit is set in the value we will need to round up.  */
147       if ((value > 1) && (value & 1))
148         round_up = TRUE;
149     }
150   while (value >>= 1);
151
152   if (round_up)
153     result += 1;
154   expld.result.section = NULL;
155   expld.result.value = result;
156 }
157
158 static void
159 make_abs (void)
160 {
161   if (expld.result.section != NULL)
162     expld.result.value += expld.result.section->vma;
163   expld.result.section = bfd_abs_section_ptr;
164 }
165
166 static void
167 new_abs (bfd_vma value)
168 {
169   expld.result.valid_p = TRUE;
170   expld.result.section = bfd_abs_section_ptr;
171   expld.result.value = value;
172   expld.result.str = NULL;
173 }
174
175 etree_type *
176 exp_intop (bfd_vma value)
177 {
178   etree_type *new_e = (etree_type *) stat_alloc (sizeof (new_e->value));
179   new_e->type.node_code = INT;
180   new_e->type.filename = ldlex_filename ();
181   new_e->type.lineno = lineno;
182   new_e->value.value = value;
183   new_e->value.str = NULL;
184   new_e->type.node_class = etree_value;
185   return new_e;
186 }
187
188 etree_type *
189 exp_bigintop (bfd_vma value, char *str)
190 {
191   etree_type *new_e = (etree_type *) stat_alloc (sizeof (new_e->value));
192   new_e->type.node_code = INT;
193   new_e->type.filename = ldlex_filename ();
194   new_e->type.lineno = lineno;
195   new_e->value.value = value;
196   new_e->value.str = str;
197   new_e->type.node_class = etree_value;
198   return new_e;
199 }
200
201 /* Build an expression representing an unnamed relocatable value.  */
202
203 etree_type *
204 exp_relop (asection *section, bfd_vma value)
205 {
206   etree_type *new_e = (etree_type *) stat_alloc (sizeof (new_e->rel));
207   new_e->type.node_code = REL;
208   new_e->type.filename = ldlex_filename ();
209   new_e->type.lineno = lineno;
210   new_e->type.node_class = etree_rel;
211   new_e->rel.section = section;
212   new_e->rel.value = value;
213   return new_e;
214 }
215
216 static void
217 new_number (bfd_vma value)
218 {
219   expld.result.valid_p = TRUE;
220   expld.result.value = value;
221   expld.result.str = NULL;
222   expld.result.section = NULL;
223 }
224
225 static void
226 new_rel (bfd_vma value, asection *section)
227 {
228   expld.result.valid_p = TRUE;
229   expld.result.value = value;
230   expld.result.str = NULL;
231   expld.result.section = section;
232 }
233
234 static void
235 new_rel_from_abs (bfd_vma value)
236 {
237   asection *s = expld.section;
238
239   if (s == bfd_abs_section_ptr && expld.phase == lang_final_phase_enum)
240     s = section_for_dot ();
241   expld.result.valid_p = TRUE;
242   expld.result.value = value - s->vma;
243   expld.result.str = NULL;
244   expld.result.section = s;
245 }
246
247 static void
248 fold_unary (etree_type *tree)
249 {
250   exp_fold_tree_1 (tree->unary.child);
251   if (expld.result.valid_p)
252     {
253       switch (tree->type.node_code)
254         {
255         case ALIGN_K:
256           if (expld.phase != lang_first_phase_enum)
257             new_rel_from_abs (align_n (expld.dot, expld.result.value));
258           else
259             expld.result.valid_p = FALSE;
260           break;
261
262         case ABSOLUTE:
263           make_abs ();
264           break;
265
266         case LOG2CEIL:
267           make_log2ceil ();
268           break;
269
270         case '~':
271           expld.result.value = ~expld.result.value;
272           break;
273
274         case '!':
275           expld.result.value = !expld.result.value;
276           break;
277
278         case '-':
279           expld.result.value = -expld.result.value;
280           break;
281
282         case NEXT:
283           /* Return next place aligned to value.  */
284           if (expld.phase != lang_first_phase_enum)
285             {
286               make_abs ();
287               expld.result.value = align_n (expld.dot, expld.result.value);
288             }
289           else
290             expld.result.valid_p = FALSE;
291           break;
292
293         case DATA_SEGMENT_END:
294           if (expld.phase == lang_first_phase_enum
295               || expld.section != bfd_abs_section_ptr)
296             {
297               expld.result.valid_p = FALSE;
298             }
299           else if (expld.dataseg.phase == exp_dataseg_align_seen
300                    || expld.dataseg.phase == exp_dataseg_relro_seen)
301             {
302               expld.dataseg.phase = exp_dataseg_end_seen;
303               expld.dataseg.end = expld.result.value;
304             }
305           else if (expld.dataseg.phase == exp_dataseg_done
306                    || expld.dataseg.phase == exp_dataseg_adjust
307                    || expld.dataseg.phase == exp_dataseg_relro_adjust)
308             {
309               /* OK.  */
310             }
311           else
312             expld.result.valid_p = FALSE;
313           break;
314
315         default:
316           FAIL ();
317           break;
318         }
319     }
320 }
321
322 static void
323 fold_binary (etree_type *tree)
324 {
325   etree_value_type lhs;
326   exp_fold_tree_1 (tree->binary.lhs);
327
328   /* The SEGMENT_START operator is special because its first
329      operand is a string, not the name of a symbol.  Note that the
330      operands have been swapped, so binary.lhs is second (default)
331      operand, binary.rhs is first operand.  */
332   if (expld.result.valid_p && tree->type.node_code == SEGMENT_START)
333     {
334       const char *segment_name;
335       segment_type *seg;
336
337       /* Check to see if the user has overridden the default
338          value.  */
339       segment_name = tree->binary.rhs->name.name;
340       for (seg = segments; seg; seg = seg->next)
341         if (strcmp (seg->name, segment_name) == 0)
342           {
343             if (!seg->used
344                 && config.magic_demand_paged
345                 && (seg->value % config.maxpagesize) != 0)
346               einfo (_("%P: warning: address of `%s' isn't multiple of maximum page size\n"),
347                      segment_name);
348             seg->used = TRUE;
349             new_rel_from_abs (seg->value);
350             break;
351           }
352       return;
353     }
354
355   lhs = expld.result;
356   exp_fold_tree_1 (tree->binary.rhs);
357   expld.result.valid_p &= lhs.valid_p;
358
359   if (expld.result.valid_p)
360     {
361       if (lhs.section != expld.result.section)
362         {
363           /* If the values are from different sections, and neither is
364              just a number, make both the source arguments absolute.  */
365           if (expld.result.section != NULL
366               && lhs.section != NULL)
367             {
368               make_abs ();
369               lhs.value += lhs.section->vma;
370               lhs.section = bfd_abs_section_ptr;
371             }
372
373           /* If the rhs is just a number, keep the lhs section.  */
374           else if (expld.result.section == NULL)
375             {
376               expld.result.section = lhs.section;
377               /* Make this NULL so that we know one of the operands
378                  was just a number, for later tests.  */
379               lhs.section = NULL;
380             }
381         }
382       /* At this point we know that both operands have the same
383          section, or at least one of them is a plain number.  */
384
385       switch (tree->type.node_code)
386         {
387           /* Arithmetic operators, bitwise AND, bitwise OR and XOR
388              keep the section of one of their operands only when the
389              other operand is a plain number.  Losing the section when
390              operating on two symbols, ie. a result of a plain number,
391              is required for subtraction and XOR.  It's justifiable
392              for the other operations on the grounds that adding,
393              multiplying etc. two section relative values does not
394              really make sense unless they are just treated as
395              numbers.
396              The same argument could be made for many expressions
397              involving one symbol and a number.  For example,
398              "1 << x" and "100 / x" probably should not be given the
399              section of x.  The trouble is that if we fuss about such
400              things the rules become complex and it is onerous to
401              document ld expression evaluation.  */
402 #define BOP(x, y) \
403         case x:                                                 \
404           expld.result.value = lhs.value y expld.result.value;  \
405           if (expld.result.section == lhs.section)              \
406             expld.result.section = NULL;                        \
407           break;
408
409           /* Comparison operators, logical AND, and logical OR always
410              return a plain number.  */
411 #define BOPN(x, y) \
412         case x:                                                 \
413           expld.result.value = lhs.value y expld.result.value;  \
414           expld.result.section = NULL;                          \
415           break;
416
417           BOP ('+', +);
418           BOP ('*', *);
419           BOP ('-', -);
420           BOP (LSHIFT, <<);
421           BOP (RSHIFT, >>);
422           BOP ('&', &);
423           BOP ('^', ^);
424           BOP ('|', |);
425           BOPN (EQ, ==);
426           BOPN (NE, !=);
427           BOPN ('<', <);
428           BOPN ('>', >);
429           BOPN (LE, <=);
430           BOPN (GE, >=);
431           BOPN (ANDAND, &&);
432           BOPN (OROR, ||);
433
434         case '%':
435           if (expld.result.value != 0)
436             expld.result.value = ((bfd_signed_vma) lhs.value
437                                   % (bfd_signed_vma) expld.result.value);
438           else if (expld.phase != lang_mark_phase_enum)
439             einfo (_("%F%S %% by zero\n"), tree->binary.rhs);
440           if (expld.result.section == lhs.section)
441             expld.result.section = NULL;
442           break;
443
444         case '/':
445           if (expld.result.value != 0)
446             expld.result.value = ((bfd_signed_vma) lhs.value
447                                   / (bfd_signed_vma) expld.result.value);
448           else if (expld.phase != lang_mark_phase_enum)
449             einfo (_("%F%S / by zero\n"), tree->binary.rhs);
450           if (expld.result.section == lhs.section)
451             expld.result.section = NULL;
452           break;
453
454         case MAX_K:
455           if (lhs.value > expld.result.value)
456             expld.result.value = lhs.value;
457           break;
458
459         case MIN_K:
460           if (lhs.value < expld.result.value)
461             expld.result.value = lhs.value;
462           break;
463
464         case ALIGN_K:
465           expld.result.value = align_n (lhs.value, expld.result.value);
466           break;
467
468         case DATA_SEGMENT_ALIGN:
469           expld.dataseg.relro = exp_dataseg_relro_start;
470           if (expld.phase == lang_first_phase_enum
471               || expld.section != bfd_abs_section_ptr)
472             expld.result.valid_p = FALSE;
473           else
474             {
475               bfd_vma maxpage = lhs.value;
476               bfd_vma commonpage = expld.result.value;
477
478               expld.result.value = align_n (expld.dot, maxpage);
479               if (expld.dataseg.phase == exp_dataseg_relro_adjust)
480                 expld.result.value = expld.dataseg.base;
481               else if (expld.dataseg.phase == exp_dataseg_adjust)
482                 {
483                   if (commonpage < maxpage)
484                     expld.result.value += ((expld.dot + commonpage - 1)
485                                            & (maxpage - commonpage));
486                 }
487               else
488                 {
489                   expld.result.value += expld.dot & (maxpage - 1);
490                   if (expld.dataseg.phase == exp_dataseg_done)
491                     {
492                       /* OK.  */
493                     }
494                   else if (expld.dataseg.phase == exp_dataseg_none)
495                     {
496                       expld.dataseg.phase = exp_dataseg_align_seen;
497                       expld.dataseg.min_base = expld.dot;
498                       expld.dataseg.base = expld.result.value;
499                       expld.dataseg.pagesize = commonpage;
500                       expld.dataseg.maxpagesize = maxpage;
501                       expld.dataseg.relro_end = 0;
502                     }
503                   else
504                     expld.result.valid_p = FALSE;
505                 }
506             }
507           break;
508
509         case DATA_SEGMENT_RELRO_END:
510           expld.dataseg.relro = exp_dataseg_relro_end;
511           if (expld.phase == lang_first_phase_enum
512               || expld.section != bfd_abs_section_ptr)
513             expld.result.valid_p = FALSE;
514           else if (expld.dataseg.phase == exp_dataseg_align_seen
515                    || expld.dataseg.phase == exp_dataseg_adjust
516                    || expld.dataseg.phase == exp_dataseg_relro_adjust
517                    || expld.dataseg.phase == exp_dataseg_done)
518             {
519               if (expld.dataseg.phase == exp_dataseg_align_seen
520                   || expld.dataseg.phase == exp_dataseg_relro_adjust)
521                 expld.dataseg.relro_end = lhs.value + expld.result.value;
522
523               if (expld.dataseg.phase == exp_dataseg_relro_adjust
524                   && (expld.dataseg.relro_end
525                       & (expld.dataseg.pagesize - 1)))
526                 {
527                   expld.dataseg.relro_end += expld.dataseg.pagesize - 1;
528                   expld.dataseg.relro_end &= ~(expld.dataseg.pagesize - 1);
529                   expld.result.value = (expld.dataseg.relro_end
530                                         - expld.result.value);
531                 }
532               else
533                 expld.result.value = lhs.value;
534
535               if (expld.dataseg.phase == exp_dataseg_align_seen)
536                 expld.dataseg.phase = exp_dataseg_relro_seen;
537             }
538           else
539             expld.result.valid_p = FALSE;
540           break;
541
542         default:
543           FAIL ();
544         }
545     }
546 }
547
548 static void
549 fold_trinary (etree_type *tree)
550 {
551   exp_fold_tree_1 (tree->trinary.cond);
552   if (expld.result.valid_p)
553     exp_fold_tree_1 (expld.result.value
554                      ? tree->trinary.lhs
555                      : tree->trinary.rhs);
556 }
557
558 static void
559 fold_name (etree_type *tree)
560 {
561   memset (&expld.result, 0, sizeof (expld.result));
562
563   switch (tree->type.node_code)
564     {
565     case SIZEOF_HEADERS:
566       if (expld.phase != lang_first_phase_enum)
567         {
568           bfd_vma hdr_size = 0;
569           /* Don't find the real header size if only marking sections;
570              The bfd function may cache incorrect data.  */
571           if (expld.phase != lang_mark_phase_enum)
572             hdr_size = bfd_sizeof_headers (link_info.output_bfd, &link_info);
573           new_number (hdr_size);
574         }
575       break;
576
577     case DEFINED:
578       if (expld.phase != lang_first_phase_enum)
579         {
580           struct bfd_link_hash_entry *h;
581           struct lang_definedness_hash_entry *def;
582
583           h = bfd_wrapped_link_hash_lookup (link_info.output_bfd,
584                                             &link_info,
585                                             tree->name.name,
586                                             FALSE, FALSE, TRUE);
587           new_number (h != NULL
588                       && (h->type == bfd_link_hash_defined
589                           || h->type == bfd_link_hash_defweak
590                           || h->type == bfd_link_hash_common)
591                       && ((def = lang_symbol_defined (tree->name.name)) == NULL
592                           || def->by_object
593                           || def->iteration == (lang_statement_iteration & 1)));
594         }
595       break;
596
597     case NAME:
598       if (expld.assign_name != NULL
599           && strcmp (expld.assign_name, tree->name.name) == 0)
600         {
601           /* Self-assignment is only allowed for absolute symbols
602              defined in a linker script.  */
603           struct bfd_link_hash_entry *h;
604           struct lang_definedness_hash_entry *def;
605
606           h = bfd_wrapped_link_hash_lookup (link_info.output_bfd,
607                                             &link_info,
608                                             tree->name.name,
609                                             FALSE, FALSE, TRUE);
610           if (!(h != NULL
611                 && (h->type == bfd_link_hash_defined
612                     || h->type == bfd_link_hash_defweak)
613                 && h->u.def.section == bfd_abs_section_ptr
614                 && (def = lang_symbol_defined (tree->name.name)) != NULL
615                 && def->iteration == (lang_statement_iteration & 1)))
616             expld.assign_name = NULL;
617         }
618       if (expld.phase == lang_first_phase_enum)
619         ;
620       else if (tree->name.name[0] == '.' && tree->name.name[1] == 0)
621         new_rel_from_abs (expld.dot);
622       else
623         {
624           struct bfd_link_hash_entry *h;
625
626           h = bfd_wrapped_link_hash_lookup (link_info.output_bfd,
627                                             &link_info,
628                                             tree->name.name,
629                                             TRUE, FALSE, TRUE);
630           if (!h)
631             einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
632           else if (h->type == bfd_link_hash_defined
633                    || h->type == bfd_link_hash_defweak)
634             {
635               asection *output_section;
636
637               output_section = h->u.def.section->output_section;
638               if (output_section == NULL)
639                 {
640                   if (expld.phase == lang_mark_phase_enum)
641                     new_rel (h->u.def.value, h->u.def.section);
642                   else
643                     einfo (_("%X%S: unresolvable symbol `%s'"
644                              " referenced in expression\n"),
645                            tree, tree->name.name);
646                 }
647               else if (output_section == bfd_abs_section_ptr
648                        && (expld.section != bfd_abs_section_ptr
649                            || config.sane_expr))
650                 new_number (h->u.def.value + h->u.def.section->output_offset);
651               else
652                 new_rel (h->u.def.value + h->u.def.section->output_offset,
653                          output_section);
654             }
655           else if (expld.phase == lang_final_phase_enum
656                    || (expld.phase != lang_mark_phase_enum
657                        && expld.assigning_to_dot))
658             einfo (_("%F%S: undefined symbol `%s'"
659                      " referenced in expression\n"),
660                    tree, tree->name.name);
661           else if (h->type == bfd_link_hash_new)
662             {
663               h->type = bfd_link_hash_undefined;
664               h->u.undef.abfd = NULL;
665               if (h->u.undef.next == NULL && h != link_info.hash->undefs_tail)
666                 bfd_link_add_undef (link_info.hash, h);
667             }
668         }
669       break;
670
671     case ADDR:
672       if (expld.phase != lang_first_phase_enum)
673         {
674           lang_output_section_statement_type *os;
675
676           os = lang_output_section_find (tree->name.name);
677           if (os == NULL)
678             {
679               if (expld.phase == lang_final_phase_enum)
680                 einfo (_("%F%S: undefined section `%s'"
681                          " referenced in expression\n"),
682                        tree, tree->name.name);
683             }
684           else if (os->processed_vma)
685             new_rel (0, os->bfd_section);
686         }
687       break;
688
689     case LOADADDR:
690       if (expld.phase != lang_first_phase_enum)
691         {
692           lang_output_section_statement_type *os;
693
694           os = lang_output_section_find (tree->name.name);
695           if (os == NULL)
696             {
697               if (expld.phase == lang_final_phase_enum)
698                 einfo (_("%F%S: undefined section `%s'"
699                          " referenced in expression\n"),
700                        tree, tree->name.name);
701             }
702           else if (os->processed_lma)
703             {
704               if (os->load_base == NULL)
705                 new_abs (os->bfd_section->lma);
706               else
707                 {
708                   exp_fold_tree_1 (os->load_base);
709                   if (expld.result.valid_p)
710                     make_abs ();
711                 }
712             }
713         }
714       break;
715
716     case SIZEOF:
717     case ALIGNOF:
718       if (expld.phase != lang_first_phase_enum)
719         {
720           lang_output_section_statement_type *os;
721
722           os = lang_output_section_find (tree->name.name);
723           if (os == NULL)
724             {
725               if (expld.phase == lang_final_phase_enum)
726                 einfo (_("%F%S: undefined section `%s'"
727                          " referenced in expression\n"),
728                        tree, tree->name.name);
729               new_number (0);
730             }
731           else if (os->bfd_section != NULL)
732             {
733               bfd_vma val;
734
735               if (tree->type.node_code == SIZEOF)
736                 val = (os->bfd_section->size
737                        / bfd_octets_per_byte (link_info.output_bfd));
738               else
739                 val = (bfd_vma)1 << os->bfd_section->alignment_power;
740
741               new_number (val);
742             }
743           else
744             new_number (0);
745         }
746       break;
747
748     case LENGTH:
749       {
750         lang_memory_region_type *mem;
751
752         mem = lang_memory_region_lookup (tree->name.name, FALSE);
753         if (mem != NULL)
754           new_number (mem->length);
755         else
756           einfo (_("%F%S: undefined MEMORY region `%s'"
757                    " referenced in expression\n"),
758                  tree, tree->name.name);
759       }
760       break;
761
762     case ORIGIN:
763       if (expld.phase != lang_first_phase_enum)
764         {
765           lang_memory_region_type *mem;
766
767           mem = lang_memory_region_lookup (tree->name.name, FALSE);
768           if (mem != NULL)
769             new_rel_from_abs (mem->origin);
770           else
771             einfo (_("%F%S: undefined MEMORY region `%s'"
772                      " referenced in expression\n"),
773                    tree, tree->name.name);
774         }
775       break;
776
777     case CONSTANT:
778       if (strcmp (tree->name.name, "MAXPAGESIZE") == 0)
779         new_number (config.maxpagesize);
780       else if (strcmp (tree->name.name, "COMMONPAGESIZE") == 0)
781         new_number (config.commonpagesize);
782       else
783         einfo (_("%F%S: unknown constant `%s' referenced in expression\n"),
784                tree, tree->name.name);
785       break;
786
787     default:
788       FAIL ();
789       break;
790     }
791 }
792
793 /* Return true if TREE is '.'.  */
794  
795 static bfd_boolean
796 is_dot (const etree_type *tree)
797 {
798   return (tree->type.node_class == etree_name
799           && tree->type.node_code == NAME
800           && tree->name.name[0] == '.'
801           && tree->name.name[1] == 0);
802 }
803
804 /* Return true if TREE is a constant equal to VAL.  */
805
806 static bfd_boolean
807 is_value (const etree_type *tree, bfd_vma val)
808 {
809   return (tree->type.node_class == etree_value
810           && tree->value.value == val);
811 }
812
813 /* Return true if TREE is an absolute symbol equal to VAL defined in
814    a linker script.  */
815
816 static bfd_boolean
817 is_sym_value (const etree_type *tree, bfd_vma val)
818 {
819   struct bfd_link_hash_entry *h;
820   struct lang_definedness_hash_entry *def;
821
822   return (tree->type.node_class == etree_name
823           && tree->type.node_code == NAME
824           && (def = lang_symbol_defined (tree->name.name)) != NULL
825           && def->by_script
826           && def->iteration == (lang_statement_iteration & 1)
827           && (h = bfd_wrapped_link_hash_lookup (link_info.output_bfd,
828                                                 &link_info,
829                                                 tree->name.name,
830                                                 FALSE, FALSE, TRUE)) != NULL
831           && h->type == bfd_link_hash_defined
832           && h->u.def.section == bfd_abs_section_ptr
833           && h->u.def.value == val);
834 }
835
836 /* Return true if TREE is ". != 0".  */
837
838 static bfd_boolean
839 is_dot_ne_0 (const etree_type *tree)
840 {
841   return (tree->type.node_class == etree_binary
842           && tree->type.node_code == NE
843           && is_dot (tree->binary.lhs)
844           && is_value (tree->binary.rhs, 0));
845 }
846
847 /* Return true if TREE is ". = . + 0" or ". = . + sym" where sym is an
848    absolute constant with value 0 defined in a linker script.  */
849
850 static bfd_boolean
851 is_dot_plus_0 (const etree_type *tree)
852 {
853   return (tree->type.node_class == etree_binary
854           && tree->type.node_code == '+'
855           && is_dot (tree->binary.lhs)
856           && (is_value (tree->binary.rhs, 0)
857               || is_sym_value (tree->binary.rhs, 0)));
858 }
859
860 /* Return true if TREE is "ALIGN (. != 0 ? some_expression : 1)".  */
861
862 static bfd_boolean
863 is_align_conditional (const etree_type *tree)
864 {
865   if (tree->type.node_class == etree_unary
866       && tree->type.node_code == ALIGN_K)
867     {
868       tree = tree->unary.child;
869       return (tree->type.node_class == etree_trinary
870               && is_dot_ne_0 (tree->trinary.cond)
871               && is_value (tree->trinary.rhs, 1));
872     }
873   return 0;
874 }
875
876 static void
877 exp_fold_tree_1 (etree_type *tree)
878 {
879   if (tree == NULL)
880     {
881       memset (&expld.result, 0, sizeof (expld.result));
882       return;
883     }
884
885   switch (tree->type.node_class)
886     {
887     case etree_value:
888       if (expld.section == bfd_abs_section_ptr
889           && !config.sane_expr)
890         new_abs (tree->value.value);
891       else
892         new_number (tree->value.value);
893       expld.result.str = tree->value.str;
894       break;
895
896     case etree_rel:
897       if (expld.phase != lang_first_phase_enum)
898         {
899           asection *output_section = tree->rel.section->output_section;
900           new_rel (tree->rel.value + tree->rel.section->output_offset,
901                    output_section);
902         }
903       else
904         memset (&expld.result, 0, sizeof (expld.result));
905       break;
906
907     case etree_assert:
908       exp_fold_tree_1 (tree->assert_s.child);
909       if (expld.phase == lang_final_phase_enum && !expld.result.value)
910         einfo ("%X%P: %s\n", tree->assert_s.message);
911       break;
912
913     case etree_unary:
914       fold_unary (tree);
915       break;
916
917     case etree_binary:
918       fold_binary (tree);
919       break;
920
921     case etree_trinary:
922       fold_trinary (tree);
923       break;
924
925     case etree_assign:
926     case etree_provide:
927     case etree_provided:
928       if (tree->assign.dst[0] == '.' && tree->assign.dst[1] == 0)
929         {
930           if (tree->type.node_class != etree_assign)
931             einfo (_("%F%S can not PROVIDE assignment to"
932                      " location counter\n"), tree);
933           if (expld.phase != lang_first_phase_enum)
934             {
935               /* Notify the folder that this is an assignment to dot.  */
936               expld.assigning_to_dot = TRUE;
937               exp_fold_tree_1 (tree->assign.src);
938               expld.assigning_to_dot = FALSE;
939
940               /* If we are assigning to dot inside an output section
941                  arrange to keep the section, except for certain
942                  expressions that evaluate to zero.  We ignore . = 0,
943                  . = . + 0, and . = ALIGN (. != 0 ? expr : 1).  */
944               if (expld.phase == lang_mark_phase_enum
945                   && expld.section != bfd_abs_section_ptr
946                   && !(expld.result.valid_p
947                        && expld.result.value == 0
948                        && (is_value (tree->assign.src, 0)
949                            || is_sym_value (tree->assign.src, 0)
950                            || is_dot_plus_0 (tree->assign.src)
951                            || is_align_conditional (tree->assign.src))))
952                 expld.section->flags |= SEC_KEEP;
953
954               if (!expld.result.valid_p)
955                 {
956                   if (expld.phase != lang_mark_phase_enum)
957                     einfo (_("%F%S invalid assignment to"
958                              " location counter\n"), tree);
959                 }
960               else if (expld.dotp == NULL)
961                 einfo (_("%F%S assignment to location counter"
962                          " invalid outside of SECTIONS\n"), tree);
963
964               /* After allocation, assignment to dot should not be
965                  done inside an output section since allocation adds a
966                  padding statement that effectively duplicates the
967                  assignment.  */
968               else if (expld.phase <= lang_allocating_phase_enum
969                        || expld.section == bfd_abs_section_ptr)
970                 {
971                   bfd_vma nextdot;
972
973                   nextdot = expld.result.value;
974                   if (expld.result.section != NULL)
975                     nextdot += expld.result.section->vma;
976                   else
977                     nextdot += expld.section->vma;
978                   if (nextdot < expld.dot
979                       && expld.section != bfd_abs_section_ptr)
980                     einfo (_("%F%S cannot move location counter backwards"
981                              " (from %V to %V)\n"),
982                            tree, expld.dot, nextdot);
983                   else
984                     {
985                       expld.dot = nextdot;
986                       *expld.dotp = nextdot;
987                     }
988                 }
989             }
990           else
991             memset (&expld.result, 0, sizeof (expld.result));
992         }
993       else
994         {
995           struct bfd_link_hash_entry *h = NULL;
996
997           if (tree->type.node_class == etree_provide)
998             {
999               h = bfd_link_hash_lookup (link_info.hash, tree->assign.dst,
1000                                         FALSE, FALSE, TRUE);
1001               if (h == NULL
1002                   || (h->type != bfd_link_hash_new
1003                       && h->type != bfd_link_hash_undefined
1004                       && h->type != bfd_link_hash_common))
1005                 {
1006                   /* Do nothing.  The symbol was never referenced, or was
1007                      defined by some object.  */
1008                   break;
1009                 }
1010             }
1011
1012           expld.assign_name = tree->assign.dst;
1013           exp_fold_tree_1 (tree->assign.src);
1014           /* expld.assign_name remaining equal to tree->assign.dst
1015              below indicates the evaluation of tree->assign.src did
1016              not use the value of tree->assign.dst.  We don't allow
1017              self assignment until the final phase for two reasons:
1018              1) Expressions are evaluated multiple times.  With
1019              relaxation, the number of times may vary.
1020              2) Section relative symbol values cannot be correctly
1021              converted to absolute values, as is required by many
1022              expressions, until final section sizing is complete.  */
1023           if ((expld.result.valid_p
1024                && (expld.phase == lang_final_phase_enum
1025                    || expld.assign_name != NULL))
1026               || (expld.phase <= lang_mark_phase_enum
1027                   && tree->type.node_class == etree_assign
1028                   && tree->assign.defsym))
1029             {
1030               if (h == NULL)
1031                 {
1032                   h = bfd_link_hash_lookup (link_info.hash, tree->assign.dst,
1033                                             TRUE, FALSE, TRUE);
1034                   if (h == NULL)
1035                     einfo (_("%P%F:%s: hash creation failed\n"),
1036                            tree->assign.dst);
1037                 }
1038
1039               /* FIXME: Should we worry if the symbol is already
1040                  defined?  */
1041               lang_update_definedness (tree->assign.dst, h);
1042               h->type = bfd_link_hash_defined;
1043               h->u.def.value = expld.result.value;
1044               if (expld.result.section == NULL)
1045                 expld.result.section = expld.section;
1046               h->u.def.section = expld.result.section;
1047               if (tree->type.node_class == etree_provide)
1048                 tree->type.node_class = etree_provided;
1049
1050               /* Copy the symbol type if this is a simple assignment of
1051                  one symbol to another.  This could be more general
1052                  (e.g. a ?: operator with NAMEs in each branch).  */
1053               if (tree->assign.src->type.node_class == etree_name)
1054                 {
1055                   struct bfd_link_hash_entry *hsrc;
1056
1057                   hsrc = bfd_link_hash_lookup (link_info.hash,
1058                                                tree->assign.src->name.name,
1059                                                FALSE, FALSE, TRUE);
1060                   if (hsrc)
1061                     bfd_copy_link_hash_symbol_type (link_info.output_bfd, h,
1062                                                     hsrc);
1063                 }
1064             }
1065           else if (expld.phase == lang_final_phase_enum)
1066             {
1067               h = bfd_link_hash_lookup (link_info.hash, tree->assign.dst,
1068                                         FALSE, FALSE, TRUE);
1069               if (h != NULL
1070                   && h->type == bfd_link_hash_new)
1071                 h->type = bfd_link_hash_undefined;
1072             }
1073           expld.assign_name = NULL;
1074         }
1075       break;
1076
1077     case etree_name:
1078       fold_name (tree);
1079       break;
1080
1081     default:
1082       FAIL ();
1083       memset (&expld.result, 0, sizeof (expld.result));
1084       break;
1085     }
1086 }
1087
1088 void
1089 exp_fold_tree (etree_type *tree, asection *current_section, bfd_vma *dotp)
1090 {
1091   expld.dot = *dotp;
1092   expld.dotp = dotp;
1093   expld.section = current_section;
1094   exp_fold_tree_1 (tree);
1095 }
1096
1097 void
1098 exp_fold_tree_no_dot (etree_type *tree)
1099 {
1100   expld.dot = 0;
1101   expld.dotp = NULL;
1102   expld.section = bfd_abs_section_ptr;
1103   exp_fold_tree_1 (tree);
1104 }
1105
1106 etree_type *
1107 exp_binop (int code, etree_type *lhs, etree_type *rhs)
1108 {
1109   etree_type value, *new_e;
1110
1111   value.type.node_code = code;
1112   value.type.filename = lhs->type.filename;
1113   value.type.lineno = lhs->type.lineno;
1114   value.binary.lhs = lhs;
1115   value.binary.rhs = rhs;
1116   value.type.node_class = etree_binary;
1117   exp_fold_tree_no_dot (&value);
1118   if (expld.result.valid_p)
1119     return exp_intop (expld.result.value);
1120
1121   new_e = (etree_type *) stat_alloc (sizeof (new_e->binary));
1122   memcpy (new_e, &value, sizeof (new_e->binary));
1123   return new_e;
1124 }
1125
1126 etree_type *
1127 exp_trinop (int code, etree_type *cond, etree_type *lhs, etree_type *rhs)
1128 {
1129   etree_type value, *new_e;
1130
1131   value.type.node_code = code;
1132   value.type.filename = cond->type.filename;
1133   value.type.lineno = cond->type.lineno;
1134   value.trinary.lhs = lhs;
1135   value.trinary.cond = cond;
1136   value.trinary.rhs = rhs;
1137   value.type.node_class = etree_trinary;
1138   exp_fold_tree_no_dot (&value);
1139   if (expld.result.valid_p)
1140     return exp_intop (expld.result.value);
1141
1142   new_e = (etree_type *) stat_alloc (sizeof (new_e->trinary));
1143   memcpy (new_e, &value, sizeof (new_e->trinary));
1144   return new_e;
1145 }
1146
1147 etree_type *
1148 exp_unop (int code, etree_type *child)
1149 {
1150   etree_type value, *new_e;
1151
1152   value.unary.type.node_code = code;
1153   value.unary.type.filename = child->type.filename;
1154   value.unary.type.lineno = child->type.lineno;
1155   value.unary.child = child;
1156   value.unary.type.node_class = etree_unary;
1157   exp_fold_tree_no_dot (&value);
1158   if (expld.result.valid_p)
1159     return exp_intop (expld.result.value);
1160
1161   new_e = (etree_type *) stat_alloc (sizeof (new_e->unary));
1162   memcpy (new_e, &value, sizeof (new_e->unary));
1163   return new_e;
1164 }
1165
1166 etree_type *
1167 exp_nameop (int code, const char *name)
1168 {
1169   etree_type value, *new_e;
1170
1171   value.name.type.node_code = code;
1172   value.name.type.filename = ldlex_filename ();
1173   value.name.type.lineno = lineno;
1174   value.name.name = name;
1175   value.name.type.node_class = etree_name;
1176
1177   exp_fold_tree_no_dot (&value);
1178   if (expld.result.valid_p)
1179     return exp_intop (expld.result.value);
1180
1181   new_e = (etree_type *) stat_alloc (sizeof (new_e->name));
1182   memcpy (new_e, &value, sizeof (new_e->name));
1183   return new_e;
1184
1185 }
1186
1187 static etree_type *
1188 exp_assop (const char *dst,
1189            etree_type *src,
1190            enum node_tree_enum class,
1191            bfd_boolean defsym,
1192            bfd_boolean hidden)
1193 {
1194   etree_type *n;
1195
1196   n = (etree_type *) stat_alloc (sizeof (n->assign));
1197   n->assign.type.node_code = '=';
1198   n->assign.type.filename = src->type.filename;
1199   n->assign.type.lineno = src->type.lineno;
1200   n->assign.type.node_class = class;
1201   n->assign.src = src;
1202   n->assign.dst = dst;
1203   n->assign.defsym = defsym;
1204   n->assign.hidden = hidden;
1205   return n;
1206 }
1207
1208 /* Handle linker script assignments and HIDDEN.  */
1209
1210 etree_type *
1211 exp_assign (const char *dst, etree_type *src, bfd_boolean hidden)
1212 {
1213   return exp_assop (dst, src, etree_assign, FALSE, hidden);
1214 }
1215
1216 /* Handle --defsym command-line option.  */
1217
1218 etree_type *
1219 exp_defsym (const char *dst, etree_type *src)
1220 {
1221   return exp_assop (dst, src, etree_assign, TRUE, FALSE);
1222 }
1223
1224 /* Handle PROVIDE.  */
1225
1226 etree_type *
1227 exp_provide (const char *dst, etree_type *src, bfd_boolean hidden)
1228 {
1229   return exp_assop (dst, src, etree_provide, FALSE, hidden);
1230 }
1231
1232 /* Handle ASSERT.  */
1233
1234 etree_type *
1235 exp_assert (etree_type *exp, const char *message)
1236 {
1237   etree_type *n;
1238
1239   n = (etree_type *) stat_alloc (sizeof (n->assert_s));
1240   n->assert_s.type.node_code = '!';
1241   n->assert_s.type.filename = exp->type.filename;
1242   n->assert_s.type.lineno = exp->type.lineno;
1243   n->assert_s.type.node_class = etree_assert;
1244   n->assert_s.child = exp;
1245   n->assert_s.message = message;
1246   return n;
1247 }
1248
1249 void
1250 exp_print_tree (etree_type *tree)
1251 {
1252   bfd_boolean function_like;
1253
1254   if (config.map_file == NULL)
1255     config.map_file = stderr;
1256
1257   if (tree == NULL)
1258     {
1259       minfo ("NULL TREE\n");
1260       return;
1261     }
1262
1263   switch (tree->type.node_class)
1264     {
1265     case etree_value:
1266       minfo ("0x%v", tree->value.value);
1267       return;
1268     case etree_rel:
1269       if (tree->rel.section->owner != NULL)
1270         minfo ("%B:", tree->rel.section->owner);
1271       minfo ("%s+0x%v", tree->rel.section->name, tree->rel.value);
1272       return;
1273     case etree_assign:
1274       fputs (tree->assign.dst, config.map_file);
1275       exp_print_token (tree->type.node_code, TRUE);
1276       exp_print_tree (tree->assign.src);
1277       break;
1278     case etree_provide:
1279     case etree_provided:
1280       fprintf (config.map_file, "PROVIDE (%s, ", tree->assign.dst);
1281       exp_print_tree (tree->assign.src);
1282       fputc (')', config.map_file);
1283       break;
1284     case etree_binary:
1285       function_like = FALSE;
1286       switch (tree->type.node_code)
1287         {
1288         case MAX_K:
1289         case MIN_K:
1290         case ALIGN_K:
1291         case DATA_SEGMENT_ALIGN:
1292         case DATA_SEGMENT_RELRO_END:
1293           function_like = TRUE;
1294           break;
1295         case SEGMENT_START:
1296           /* Special handling because arguments are in reverse order and
1297              the segment name is quoted.  */
1298           exp_print_token (tree->type.node_code, FALSE);
1299           fputs (" (\"", config.map_file);
1300           exp_print_tree (tree->binary.rhs);
1301           fputs ("\", ", config.map_file);
1302           exp_print_tree (tree->binary.lhs);
1303           fputc (')', config.map_file);
1304           return;
1305         }
1306       if (function_like)
1307         {
1308           exp_print_token (tree->type.node_code, FALSE);
1309           fputc (' ', config.map_file);
1310         }
1311       fputc ('(', config.map_file);
1312       exp_print_tree (tree->binary.lhs);
1313       if (function_like)
1314         fprintf (config.map_file, ", ");
1315       else
1316         exp_print_token (tree->type.node_code, TRUE);
1317       exp_print_tree (tree->binary.rhs);
1318       fputc (')', config.map_file);
1319       break;
1320     case etree_trinary:
1321       exp_print_tree (tree->trinary.cond);
1322       fputc ('?', config.map_file);
1323       exp_print_tree (tree->trinary.lhs);
1324       fputc (':', config.map_file);
1325       exp_print_tree (tree->trinary.rhs);
1326       break;
1327     case etree_unary:
1328       exp_print_token (tree->unary.type.node_code, FALSE);
1329       if (tree->unary.child)
1330         {
1331           fprintf (config.map_file, " (");
1332           exp_print_tree (tree->unary.child);
1333           fputc (')', config.map_file);
1334         }
1335       break;
1336
1337     case etree_assert:
1338       fprintf (config.map_file, "ASSERT (");
1339       exp_print_tree (tree->assert_s.child);
1340       fprintf (config.map_file, ", %s)", tree->assert_s.message);
1341       break;
1342
1343     case etree_name:
1344       if (tree->type.node_code == NAME)
1345         fputs (tree->name.name, config.map_file);
1346       else
1347         {
1348           exp_print_token (tree->type.node_code, FALSE);
1349           if (tree->name.name)
1350             fprintf (config.map_file, " (%s)", tree->name.name);
1351         }
1352       break;
1353     default:
1354       FAIL ();
1355       break;
1356     }
1357 }
1358
1359 bfd_vma
1360 exp_get_vma (etree_type *tree, bfd_vma def, char *name)
1361 {
1362   if (tree != NULL)
1363     {
1364       exp_fold_tree_no_dot (tree);
1365       if (expld.result.valid_p)
1366         return expld.result.value;
1367       else if (name != NULL && expld.phase != lang_mark_phase_enum)
1368         einfo (_("%F%S: nonconstant expression for %s\n"),
1369                tree, name);
1370     }
1371   return def;
1372 }
1373
1374 int
1375 exp_get_value_int (etree_type *tree, int def, char *name)
1376 {
1377   return exp_get_vma (tree, def, name);
1378 }
1379
1380 fill_type *
1381 exp_get_fill (etree_type *tree, fill_type *def, char *name)
1382 {
1383   fill_type *fill;
1384   size_t len;
1385   unsigned int val;
1386
1387   if (tree == NULL)
1388     return def;
1389
1390   exp_fold_tree_no_dot (tree);
1391   if (!expld.result.valid_p)
1392     {
1393       if (name != NULL && expld.phase != lang_mark_phase_enum)
1394         einfo (_("%F%S: nonconstant expression for %s\n"),
1395                tree, name);
1396       return def;
1397     }
1398
1399   if (expld.result.str != NULL && (len = strlen (expld.result.str)) != 0)
1400     {
1401       unsigned char *dst;
1402       unsigned char *s;
1403       fill = (fill_type *) xmalloc ((len + 1) / 2 + sizeof (*fill) - 1);
1404       fill->size = (len + 1) / 2;
1405       dst = fill->data;
1406       s = (unsigned char *) expld.result.str;
1407       val = 0;
1408       do
1409         {
1410           unsigned int digit;
1411
1412           digit = *s++ - '0';
1413           if (digit > 9)
1414             digit = (digit - 'A' + '0' + 10) & 0xf;
1415           val <<= 4;
1416           val += digit;
1417           --len;
1418           if ((len & 1) == 0)
1419             {
1420               *dst++ = val;
1421               val = 0;
1422             }
1423         }
1424       while (len != 0);
1425     }
1426   else
1427     {
1428       fill = (fill_type *) xmalloc (4 + sizeof (*fill) - 1);
1429       val = expld.result.value;
1430       fill->data[0] = (val >> 24) & 0xff;
1431       fill->data[1] = (val >> 16) & 0xff;
1432       fill->data[2] = (val >>  8) & 0xff;
1433       fill->data[3] = (val >>  0) & 0xff;
1434       fill->size = 4;
1435     }
1436   return fill;
1437 }
1438
1439 bfd_vma
1440 exp_get_abs_int (etree_type *tree, int def, char *name)
1441 {
1442   if (tree != NULL)
1443     {
1444       exp_fold_tree_no_dot (tree);
1445
1446       if (expld.result.valid_p)
1447         {
1448           if (expld.result.section != NULL)
1449             expld.result.value += expld.result.section->vma;
1450           return expld.result.value;
1451         }
1452       else if (name != NULL && expld.phase != lang_mark_phase_enum)
1453         {
1454           einfo (_("%F%S: nonconstant expression for %s\n"),
1455                  tree, name);
1456         }
1457     }
1458   return def;
1459 }
1460
1461 static bfd_vma
1462 align_n (bfd_vma value, bfd_vma align)
1463 {
1464   if (align <= 1)
1465     return value;
1466
1467   value = (value + align - 1) / align;
1468   return value * align;
1469 }