c32398ffddd6e5501bd4f014148768b09af81184
[platform/upstream/binutils.git] / gas / config / obj-macho.c
1 /* Mach-O object file format
2    Copyright 2009, 2011, 2012 Free Software Foundation, Inc.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as
8    published by the Free Software Foundation; either version 3,
9    or (at your option) any later version.
10
11    GAS is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
14    the GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to the Free
18    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
19    02110-1301, USA.  */
20
21 /* Here we handle the mach-o directives that are common to all architectures.
22
23    Most significant are mach-o named sections and a variety of symbol type
24    decorations.  */
25
26 /* Mach-O supports multiple, named segments each of which may contain
27    multiple named sections.  Thus the concept of subsectioning is 
28    handled by (say) having a __TEXT segment with appropriate flags from
29    which subsections are generated like __text, __const etc.  
30    
31    The well-known as short-hand section switch directives like .text, .data
32    etc. are mapped onto predefined segment/section pairs using facilites
33    supplied by the mach-o port of bfd.
34    
35    A number of additional mach-o short-hand section switch directives are
36    also defined.  */
37
38 #define OBJ_HEADER "obj-macho.h"
39
40 #include "as.h"
41 #include "subsegs.h"
42 #include "symbols.h"
43 #include "write.h"
44 #include "mach-o.h"
45 #include "mach-o/loader.h"
46 #include "obj-macho.h"
47
48 #include <string.h>
49
50 /* Forward decls.  */
51 static segT obj_mach_o_segT_from_bfd_name (const char *, int);
52
53 /* TODO: Implement "-dynamic"/"-static" command line options.  */
54
55 static int obj_mach_o_is_static;
56
57 /* TODO: Implement the "-n" command line option to suppress the initial
58    switch to the text segment.  */
59 static int obj_mach_o_start_with_text_section = 1;
60
61 /* Allow for special re-ordering on output.  */
62
63 static int obj_mach_o_seen_objc_section;
64
65 /* Start-up: At present, just create the sections we want.  */
66 void
67 mach_o_begin (void)
68 {
69   /* Mach-O only defines the .text section by default, and even this can
70      be suppressed by a flag.  In the latter event, the first code MUST
71      be a section definition.  */
72   if (obj_mach_o_start_with_text_section)
73     {
74       text_section = obj_mach_o_segT_from_bfd_name (TEXT_SECTION_NAME, 1);
75       subseg_set (text_section, 0);
76       if (obj_mach_o_is_static)
77         {
78           bfd_mach_o_section *mo_sec 
79                         = bfd_mach_o_get_mach_o_section (text_section);
80           mo_sec->flags &= ~BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS;
81         }
82     }
83 }
84
85 /* Remember the subsections_by_symbols state in case we need to reset
86    the file flags.  */
87
88 static int obj_mach_o_subsections_by_symbols;
89
90 /* This will put at most 16 characters (terminated by a ',' or newline) from
91    the input stream into dest.  If there are more than 16 chars before the
92    delimiter, a warning is given and the string is truncated.  On completion of
93    this function, input_line_pointer will point to the char after the ',' or 
94    to the newline.  
95    
96    It trims leading and trailing space.  */
97
98 static int
99 collect_16char_name (char *dest, const char *msg, int require_comma)
100 {
101   char c, *namstart;
102
103   SKIP_WHITESPACE ();
104   namstart = input_line_pointer;
105
106   while ( (c = *input_line_pointer) != ',' 
107          && !is_end_of_line[(unsigned char) c])
108     input_line_pointer++;
109
110   {
111       int len = input_line_pointer - namstart; /* could be zero.  */
112       /* lose any trailing space.  */  
113       while (len > 0 && namstart[len-1] == ' ') 
114         len--;
115       if (len > 16)
116         {
117           *input_line_pointer = '\0'; /* make a temp string.  */
118           as_bad (_("the %s name '%s' is too long (maximum 16 characters)"),
119                      msg, namstart);
120           *input_line_pointer = c; /* restore for printing.  */
121           len = 16;
122         }
123       if (len > 0)
124         memcpy (dest, namstart, len);
125   }
126
127   if (c != ',' && require_comma)
128     {
129       as_bad (_("expected a %s name followed by a `,'"), msg);
130       return 1;
131     }
132
133   return 0;
134 }
135
136 static int
137 obj_mach_o_get_section_names (char *seg, char *sec,
138                               unsigned segl, unsigned secl)
139 {
140   /* Zero-length segment and section names are allowed.  */
141   /* Parse segment name.  */
142   memset (seg, 0, segl);
143   if (collect_16char_name (seg, "segment", 1))
144     {
145       ignore_rest_of_line ();
146       return 0;
147     }
148   input_line_pointer++; /* Skip the terminating ',' */
149
150   /* Parse section name, which can be empty.  */
151   memset (sec, 0, secl);
152   collect_16char_name (sec, "section", 0);
153   return 1;
154 }
155
156 /* Build (or get) a section from the mach-o description - which includes
157    optional definitions for type, attributes, alignment and stub size.
158    
159    BFD supplies default values for sections which have a canonical name.  */
160
161 #define SECT_TYPE_SPECIFIED 0x0001
162 #define SECT_ATTR_SPECIFIED 0x0002
163 #define SECT_ALGN_SPECIFIED 0x0004
164 #define SECT_STUB_SPECIFIED 0x0008
165
166 static segT
167 obj_mach_o_make_or_get_sect (char * segname, char * sectname,
168                              unsigned int specified_mask, 
169                              unsigned int usectype, unsigned int usecattr,
170                              unsigned int ualign, offsetT stub_size)
171 {
172   unsigned int sectype, secattr, secalign;
173   flagword oldflags, flags;
174   const char *name;
175   segT sec;
176   bfd_mach_o_section *msect;
177   const mach_o_section_name_xlat *xlat;
178
179   /* This provides default bfd flags and default mach-o section type and
180      attributes along with the canonical name.  */
181   xlat = bfd_mach_o_section_data_for_mach_sect (stdoutput, segname, sectname);
182
183   /* TODO: more checking of whether overides are acually allowed.  */
184
185   if (xlat != NULL)
186     {
187       name = xstrdup (xlat->bfd_name);
188       sectype = xlat->macho_sectype;
189       if (specified_mask & SECT_TYPE_SPECIFIED)
190         {
191           if ((sectype == BFD_MACH_O_S_ZEROFILL
192                || sectype == BFD_MACH_O_S_GB_ZEROFILL)
193               && sectype != usectype)
194             as_bad (_("cannot overide zerofill section type for `%s,%s'"),
195                     segname, sectname);
196           else
197             sectype = usectype;
198         }
199       secattr = xlat->macho_secattr;
200       secalign = xlat->sectalign;
201       flags = xlat->bfd_flags;
202     }
203   else
204     {
205       /* There is no normal BFD section name for this section.  Create one.
206          The name created doesn't really matter as it will never be written
207          on disk.  */
208       size_t seglen = strlen (segname);
209       size_t sectlen = strlen (sectname);
210       char *n;
211
212       n = xmalloc (seglen + 1 + sectlen + 1);
213       memcpy (n, segname, seglen);
214       n[seglen] = '.';
215       memcpy (n + seglen + 1, sectname, sectlen);
216       n[seglen + 1 + sectlen] = 0;
217       name = n;
218       if (specified_mask & SECT_TYPE_SPECIFIED)
219         sectype = usectype;
220       else
221         sectype = BFD_MACH_O_S_REGULAR;
222       secattr = BFD_MACH_O_S_ATTR_NONE;
223       secalign = 0;
224       flags = SEC_NO_FLAGS;
225     }
226
227   /* For now, just use what the user provided.  */
228
229   if (specified_mask & SECT_ATTR_SPECIFIED)
230     secattr = usecattr;
231
232   if (specified_mask & SECT_ALGN_SPECIFIED)
233     secalign = ualign;
234
235   /* Sub-segments don't exists as is on Mach-O.  */
236   sec = subseg_new (name, 0);
237
238   oldflags = bfd_get_section_flags (stdoutput, sec);
239   msect = bfd_mach_o_get_mach_o_section (sec);
240
241   if (oldflags == SEC_NO_FLAGS)
242     {
243       /* New, so just use the defaults or what's specified.  */
244       if (! bfd_set_section_flags (stdoutput, sec, flags))
245         as_warn (_("failed to set flags for \"%s\": %s"),
246                  bfd_section_name (stdoutput, sec),
247                  bfd_errmsg (bfd_get_error ()));
248  
249       strncpy (msect->segname, segname, sizeof (msect->segname));
250       strncpy (msect->sectname, sectname, sizeof (msect->sectname));
251
252       msect->align = secalign;
253       msect->flags = sectype | secattr;
254       
255       if (sectype == BFD_MACH_O_S_ZEROFILL
256           || sectype == BFD_MACH_O_S_GB_ZEROFILL)
257         seg_info (sec)->bss = 1;
258     }
259   else if (flags != SEC_NO_FLAGS)
260     {
261       if (flags != oldflags
262           || msect->flags != (secattr | sectype))
263         as_warn (_("Ignoring changed section attributes for %s"), name);
264     }
265
266   if (specified_mask & SECT_STUB_SPECIFIED)
267     /* At present, the stub size is not supplied from the BFD tables.  */
268     msect->reserved2 = stub_size;
269
270   return sec;
271 }
272
273 /* .section
274
275    The '.section' specification syntax looks like:
276    .section <segment> , <section> [, type [, attribs [, size]]]
277
278    White space is allowed everywhere between elements.
279
280    <segment> and <section> may be from 0 to 16 chars in length - they may
281    contain spaces but leading and trailing space will be trimmed.  It is 
282    mandatory that they be present (or that zero-length names are indicated
283    by ",,").
284
285    There is only a single section type for any entry.
286
287    There may be multiple attributes, they are delimited by `+'.
288
289    Not all section types and attributes are accepted by the Darwin system
290    assemblers as user-specifiable - although, at present, we do here.  */
291
292 static void
293 obj_mach_o_section (int ignore ATTRIBUTE_UNUSED)
294 {
295   unsigned int sectype = BFD_MACH_O_S_REGULAR;
296   unsigned int specified_mask = 0;
297   unsigned int secattr = 0;
298   offsetT sizeof_stub = 0;
299   segT new_seg;
300   char segname[17];
301   char sectname[17];
302
303 #ifdef md_flush_pending_output
304   md_flush_pending_output ();
305 #endif
306
307   /* Get the User's segment annd section names.  */
308   if (! obj_mach_o_get_section_names (segname, sectname, 17, 17))
309     return;
310
311   /* Parse section type, if present.  */
312   if (*input_line_pointer == ',')
313     {
314       char *p;
315       char c;
316       char tmpc;
317       int len;
318       input_line_pointer++;
319       SKIP_WHITESPACE ();
320       p = input_line_pointer;
321       while ((c = *input_line_pointer) != ','
322               && !is_end_of_line[(unsigned char) c])
323         input_line_pointer++;
324
325       len = input_line_pointer - p;
326       /* strip trailing spaces.  */
327       while (len > 0 && p[len-1] == ' ')
328         len--;
329       tmpc = p[len];
330
331       /* Temporarily make a string from the token.  */
332       p[len] = 0;
333       sectype = bfd_mach_o_get_section_type_from_name (stdoutput, p);
334       if (sectype > 255) /* Max Section ID == 255.  */
335         {
336           as_bad (_("unknown or invalid section type '%s'"), p);
337           p[len] = tmpc;
338           ignore_rest_of_line ();
339           return;
340         }
341       else
342         specified_mask |= SECT_TYPE_SPECIFIED;
343       /* Restore.  */
344       p[len] = tmpc;
345
346       /* Parse attributes.
347          TODO: check validity of attributes for section type.  */
348       if ((specified_mask & SECT_TYPE_SPECIFIED)
349           && c == ',')
350         {
351           do
352             {
353               int attr;
354
355               /* Skip initial `,' and subsequent `+'.  */
356               input_line_pointer++;
357               SKIP_WHITESPACE ();
358               p = input_line_pointer;
359               while ((c = *input_line_pointer) != '+'
360                       && c != ','
361                       && !is_end_of_line[(unsigned char) c])
362                 input_line_pointer++;
363
364               len = input_line_pointer - p;
365               /* strip trailing spaces.  */
366               while (len > 0 && p[len-1] == ' ')
367                 len--;
368               tmpc = p[len];
369
370               /* Temporarily make a string from the token.  */
371               p[len] ='\0';
372               attr = bfd_mach_o_get_section_attribute_from_name (p);
373               if (attr == -1)
374                 {
375                   as_bad (_("unknown or invalid section attribute '%s'"), p);
376                   p[len] = tmpc;
377                   ignore_rest_of_line ();
378                   return;
379                 }
380               else
381                 {
382                   specified_mask |= SECT_ATTR_SPECIFIED;
383                   secattr |= attr;
384                 }
385               /* Restore.  */
386               p[len] = tmpc;
387             }
388           while (*input_line_pointer == '+');
389
390           /* Parse sizeof_stub.  */
391           if ((specified_mask & SECT_ATTR_SPECIFIED) 
392               && *input_line_pointer == ',')
393             {
394               if (sectype != BFD_MACH_O_S_SYMBOL_STUBS)
395                 {
396                   as_bad (_("unexpected section size information"));
397                   ignore_rest_of_line ();
398                   return;
399                 }
400
401               input_line_pointer++;
402               sizeof_stub = get_absolute_expression ();
403               specified_mask |= SECT_STUB_SPECIFIED;
404             }
405           else if ((specified_mask & SECT_ATTR_SPECIFIED) 
406                    && sectype == BFD_MACH_O_S_SYMBOL_STUBS)
407             {
408               as_bad (_("missing sizeof_stub expression"));
409               ignore_rest_of_line ();
410               return;
411             }
412         }
413     }
414
415   new_seg = obj_mach_o_make_or_get_sect (segname, sectname, specified_mask, 
416                                          sectype, secattr, 0 /*align */,
417                                          sizeof_stub);
418   if (new_seg != NULL)
419     {
420       subseg_set (new_seg, 0);
421       demand_empty_rest_of_line ();
422     }
423 }
424
425 /* .zerofill segname, sectname [, symbolname, size [, align]]
426
427    Zerofill switches, temporarily, to a sect of type 'zerofill'.
428
429    If a variable name is given, it defines that in the section.
430    Otherwise it just creates the section if it doesn't exist.  */
431
432 static void
433 obj_mach_o_zerofill (int ignore ATTRIBUTE_UNUSED)
434 {
435   char segname[17];
436   char sectname[17];
437   segT old_seg = now_seg;
438   segT new_seg;
439   symbolS *sym = NULL;
440   unsigned int align = 0;
441   unsigned int specified_mask = 0;
442   offsetT size = 0;
443
444 #ifdef md_flush_pending_output
445   md_flush_pending_output ();
446 #endif
447
448   /* Get the User's segment annd section names.  */
449   if (! obj_mach_o_get_section_names (segname, sectname, 17, 17))
450     return;
451
452   /* Parse variable definition, if present.  */
453   if (*input_line_pointer == ',')
454     {
455       /* Parse symbol, size [.align] 
456          We follow the method of s_common_internal, with the difference
457          that the symbol cannot be a duplicate-common.  */
458       char *name;
459       char c;
460       char *p;
461       expressionS exp;
462   
463       input_line_pointer++; /* Skip ',' */
464       SKIP_WHITESPACE ();
465       name = input_line_pointer;
466       c = get_symbol_end ();
467       /* Just after name is now '\0'.  */
468       p = input_line_pointer;
469       *p = c;
470
471       if (name == p)
472         {
473           as_bad (_("expected symbol name"));
474           ignore_rest_of_line ();
475           goto done;
476         }
477
478       SKIP_WHITESPACE ();  
479       if (*input_line_pointer == ',')
480         input_line_pointer++;
481
482       expression_and_evaluate (&exp);
483       if (exp.X_op != O_constant
484           && exp.X_op != O_absent)
485         {
486             as_bad (_("bad or irreducible absolute expression"));
487           ignore_rest_of_line ();
488           goto done;
489         }
490       else if (exp.X_op == O_absent)
491         {
492           as_bad (_("missing size expression"));
493           ignore_rest_of_line ();
494           goto done;
495         }
496
497       size = exp.X_add_number;
498       size &= ((offsetT) 2 << (stdoutput->arch_info->bits_per_address - 1)) - 1;
499       if (exp.X_add_number != size || !exp.X_unsigned)
500         {
501           as_warn (_("size (%ld) out of range, ignored"),
502                    (long) exp.X_add_number);
503           ignore_rest_of_line ();
504           goto done;
505         }
506
507      *p = 0; /* Make the name into a c string for err messages.  */
508      sym = symbol_find_or_make (name);
509      if (S_IS_DEFINED (sym) || symbol_equated_p (sym))
510         {
511           as_bad (_("symbol `%s' is already defined"), name);
512           *p = c;
513           ignore_rest_of_line ();
514            goto done;
515         }
516
517       size = S_GET_VALUE (sym);
518       if (size == 0)
519         size = exp.X_add_number;
520       else if (size != exp.X_add_number)
521         as_warn (_("size of \"%s\" is already %ld; not changing to %ld"),
522                    name, (long) size, (long) exp.X_add_number);
523
524       *p = c;  /* Restore the termination char.  */
525       
526       SKIP_WHITESPACE ();  
527       if (*input_line_pointer == ',')
528         {
529           align = (unsigned int) parse_align (0);
530           if (align == (unsigned int) -1)
531             {
532               as_warn (_("align value not recognized, using size"));
533               align = size;
534             }
535           if (align > 15)
536             {
537               as_warn (_("Alignment (%lu) too large: 15 assumed."),
538                         (unsigned long)align);
539               align = 15;
540             }
541           specified_mask |= SECT_ALGN_SPECIFIED;
542         }
543     }
544  /* else just a section definition.  */
545
546   specified_mask |= SECT_TYPE_SPECIFIED;
547   new_seg = obj_mach_o_make_or_get_sect (segname, sectname, specified_mask, 
548                                          BFD_MACH_O_S_ZEROFILL,
549                                          BFD_MACH_O_S_ATTR_NONE,
550                                          align, (offsetT) 0 /*stub size*/);
551   if (new_seg == NULL)
552     return;
553
554   /* In case the user specifies the bss section by mach-o name.
555      Create it on demand */
556   if (strcmp (new_seg->name, BSS_SECTION_NAME) == 0
557       && bss_section == NULL)
558     bss_section = new_seg;
559
560   subseg_set (new_seg, 0);
561
562   if (sym != NULL)
563     {
564       char *pfrag;
565
566       if (align)
567         {
568           record_alignment (new_seg, align);
569           frag_align (align, 0, 0);
570         }
571
572       /* Detach from old frag.  */
573       if (S_GET_SEGMENT (sym) == new_seg)
574         symbol_get_frag (sym)->fr_symbol = NULL;
575
576       symbol_set_frag (sym, frag_now);
577       pfrag = frag_var (rs_org, 1, 1, 0, sym, size, NULL);
578       *pfrag = 0;
579
580       S_SET_SEGMENT (sym, new_seg);
581       if (new_seg == bss_section)
582         S_CLEAR_EXTERNAL (sym);
583     }
584
585 done:
586   /* switch back to the section that was current before the .zerofill.  */
587   subseg_set (old_seg, 0);
588 }
589
590 static segT 
591 obj_mach_o_segT_from_bfd_name (const char *nam, int must_succeed)
592 {
593   const mach_o_section_name_xlat *xlat;
594   const char *segn;
595   segT sec;
596
597   /* BFD has tables of flags and default attributes for all the sections that
598      have a 'canonical' name.  */
599   xlat = bfd_mach_o_section_data_for_bfd_name (stdoutput, nam, &segn);
600   if (xlat == NULL)
601     {
602       if (must_succeed)
603         as_fatal (_("BFD is out of sync with GAS, "
604                      "unhandled well-known section type `%s'"), nam);
605       return NULL;
606     }
607
608   sec = bfd_get_section_by_name (stdoutput, nam);
609   if (sec == NULL)
610     {
611       bfd_mach_o_section *msect;
612
613       sec = subseg_force_new (xlat->bfd_name, 0);
614
615       /* Set default type, attributes and alignment.  */
616       msect = bfd_mach_o_get_mach_o_section (sec);
617       msect->flags = xlat->macho_sectype | xlat->macho_secattr;
618       msect->align = xlat->sectalign;
619
620       if ((msect->flags & BFD_MACH_O_SECTION_TYPE_MASK) 
621           == BFD_MACH_O_S_ZEROFILL)
622         seg_info (sec)->bss = 1;
623     }
624
625   return sec;
626 }
627
628 static const char * const known_sections[] =
629 {
630   /*  0 */ NULL,
631   /* __TEXT */
632   /*  1 */ ".const",
633   /*  2 */ ".static_const",
634   /*  3 */ ".cstring",
635   /*  4 */ ".literal4",
636   /*  5 */ ".literal8",
637   /*  6 */ ".literal16",
638   /*  7 */ ".constructor",
639   /*  8 */ ".destructor",
640   /*  9 */ ".eh_frame",
641   /* __DATA */
642   /* 10 */ ".const_data",
643   /* 11 */ ".static_data",
644   /* 12 */ ".mod_init_func",
645   /* 13 */ ".mod_term_func",
646   /* 14 */ ".dyld",
647   /* 15 */ ".cfstring"
648 };
649
650 /* Interface for a known non-optional section directive.  */
651
652 static void
653 obj_mach_o_known_section (int sect_index)
654 {
655   segT section;
656
657 #ifdef md_flush_pending_output
658   md_flush_pending_output ();
659 #endif
660
661   section = obj_mach_o_segT_from_bfd_name (known_sections[sect_index], 1);
662   if (section != NULL)
663     subseg_set (section, 0);
664
665   /* else, we leave the section as it was; there was a fatal error anyway.  */
666 }
667
668 static const char * const objc_sections[] =
669 {
670   /*  0 */ NULL,
671   /*  1 */ ".objc_class",
672   /*  2 */ ".objc_meta_class",
673   /*  3 */ ".objc_cat_cls_meth",
674   /*  4 */ ".objc_cat_inst_meth",
675   /*  5 */ ".objc_protocol",
676   /*  6 */ ".objc_string_object",
677   /*  7 */ ".objc_cls_meth",
678   /*  8 */ ".objc_inst_meth",
679   /*  9 */ ".objc_cls_refs",
680   /* 10 */ ".objc_message_refs",
681   /* 11 */ ".objc_symbols",
682   /* 12 */ ".objc_category",
683   /* 13 */ ".objc_class_vars",
684   /* 14 */ ".objc_instance_vars",
685   /* 15 */ ".objc_module_info",
686   /* 16 */ ".cstring", /* objc_class_names Alias for .cstring */
687   /* 17 */ ".cstring", /* Alias objc_meth_var_types for .cstring */
688   /* 18 */ ".cstring", /* objc_meth_var_names Alias for .cstring */
689   /* 19 */ ".objc_selector_strs",
690   /* 20 */ ".objc_image_info", /* extension.  */
691   /* 21 */ ".objc_selector_fixup", /* extension.  */
692   /* 22 */ ".objc1_class_ext", /* ObjC-1 extension.  */
693   /* 23 */ ".objc1_property_list", /* ObjC-1 extension.  */
694   /* 24 */ ".objc1_protocol_ext" /* ObjC-1 extension.  */
695 };
696
697 /* This currently does the same as known_sections, but kept separate for
698    ease of maintenance.  */
699
700 static void
701 obj_mach_o_objc_section (int sect_index)
702 {
703   segT section;
704   
705 #ifdef md_flush_pending_output
706   md_flush_pending_output ();
707 #endif
708
709   section = obj_mach_o_segT_from_bfd_name (objc_sections[sect_index], 1);
710   if (section != NULL)
711     {
712       obj_mach_o_seen_objc_section = 1; /* We need to ensure that certain
713                                            sections are present and in the
714                                            right order.  */
715       subseg_set (section, 0);
716     }
717
718   /* else, we leave the section as it was; there was a fatal error anyway.  */
719 }
720
721 /* Debug section directives.  */
722
723 static const char * const debug_sections[] =
724 {
725   /*  0 */ NULL,
726   /* __DWARF */
727   /*  1 */ ".debug_frame",
728   /*  2 */ ".debug_info",
729   /*  3 */ ".debug_abbrev",
730   /*  4 */ ".debug_aranges",
731   /*  5 */ ".debug_macinfo",
732   /*  6 */ ".debug_line",
733   /*  7 */ ".debug_loc",
734   /*  8 */ ".debug_pubnames",
735   /*  9 */ ".debug_pubtypes",
736   /* 10 */ ".debug_str",
737   /* 11 */ ".debug_ranges",
738   /* 12 */ ".debug_macro"
739 };
740
741 /* ??? Maybe these should be conditional on gdwarf-*.
742    It`s also likely that we will need to be able to set them from the cfi
743    code.  */
744
745 static void
746 obj_mach_o_debug_section (int sect_index)
747 {
748   segT section;
749
750 #ifdef md_flush_pending_output
751   md_flush_pending_output ();
752 #endif
753
754   section = obj_mach_o_segT_from_bfd_name (debug_sections[sect_index], 1);
755   if (section != NULL)
756     subseg_set (section, 0);
757
758   /* else, we leave the section as it was; there was a fatal error anyway.  */
759 }
760
761 /* This could be moved to the tc-xx files, but there is so little dependency
762    there, that the code might as well be shared.  */
763
764 struct opt_tgt_sect 
765 {
766  const char *name;
767  unsigned x86_val;
768  unsigned ppc_val;
769 };
770
771 /* The extensions here are for specific sections that are generated by GCC
772    and Darwin system tools, but don't have directives in the `system as'.  */
773
774 static const struct opt_tgt_sect tgt_sections[] =
775 {
776   /*  0 */ { NULL, 0, 0},
777   /*  1 */ { ".lazy_symbol_pointer", 0, 0},
778   /*  2 */ { ".lazy_symbol_pointer2", 0, 0}, /* X86 - extension */
779   /*  3 */ { ".lazy_symbol_pointer3", 0, 0}, /* X86 - extension */
780   /*  4 */ { ".non_lazy_symbol_pointer", 0, 0},
781   /*  5 */ { ".non_lazy_symbol_pointer_x86", 0, 0}, /* X86 - extension */
782   /*  6 */ { ".symbol_stub", 16, 20},
783   /*  7 */ { ".symbol_stub1", 0, 16}, /* PPC - extension */
784   /*  8 */ { ".picsymbol_stub", 26, 36},
785   /*  9 */ { ".picsymbol_stub1", 0, 32}, /* PPC - extension */
786   /* 10 */ { ".picsymbol_stub2", 25, 0}, /* X86 - extension */
787   /* 11 */ { ".picsymbol_stub3", 5, 0}, /* X86 - extension  */
788 };
789
790 /* Interface for an optional section directive.  */
791
792 static void
793 obj_mach_o_opt_tgt_section (int sect_index)
794 {
795   const struct opt_tgt_sect *tgtsct = &tgt_sections[sect_index];
796   segT section;
797
798 #ifdef md_flush_pending_output
799   md_flush_pending_output ();
800 #endif
801
802   section = obj_mach_o_segT_from_bfd_name (tgtsct->name, 0);
803   if (section == NULL)
804     {
805       as_bad (_("%s is not used for the selected target"), tgtsct->name);
806       /* Leave the section as it is.  */
807     }
808   else
809     {
810       bfd_mach_o_section *mo_sec = bfd_mach_o_get_mach_o_section (section);
811       subseg_set (section, 0);
812 #if defined (TC_I386)
813       mo_sec->reserved2 = tgtsct->x86_val;
814 #elif defined (TC_PPC)
815       mo_sec->reserved2 = tgtsct->ppc_val;
816 #else
817       mo_sec->reserved2 = 0;
818 #endif
819     }
820 }
821
822 /* We don't necessarily have the three 'base' sections on mach-o.
823    Normally, we would start up with only the 'text' section defined.
824    However, even that can be suppressed with (TODO) c/l option "-n".
825    Thus, we have to be able to create all three sections on-demand.  */
826
827 static void
828 obj_mach_o_base_section (int sect_index)
829 {
830   segT section;
831
832 #ifdef md_flush_pending_output
833   md_flush_pending_output ();
834 #endif
835
836   /* We don't support numeric (or any other) qualifications on the
837      well-known section shorthands.  */
838   demand_empty_rest_of_line ();
839
840   switch (sect_index)
841     {
842       /* Handle the three sections that are globally known within GAS.
843          For Mach-O, these are created on demand rather than at startup.  */
844       case 1:
845         if (text_section == NULL)
846           text_section = obj_mach_o_segT_from_bfd_name (TEXT_SECTION_NAME, 1);
847         if (obj_mach_o_is_static)
848           {
849             bfd_mach_o_section *mo_sec
850                 = bfd_mach_o_get_mach_o_section (text_section);
851             mo_sec->flags &= ~BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS;
852           }
853         section = text_section;
854         break;
855       case 2:
856         if (data_section == NULL)
857           data_section = obj_mach_o_segT_from_bfd_name (DATA_SECTION_NAME, 1);
858         section = data_section;
859         break;
860       case 3:
861         /* ??? maybe this achieves very little, as an addition.  */
862         if (bss_section == NULL)
863           {
864             bss_section = obj_mach_o_segT_from_bfd_name (BSS_SECTION_NAME, 1);
865             seg_info (bss_section)->bss = 1;
866           }
867         section = bss_section;
868         break;
869       default:
870         as_fatal (_("internal error: base section index out of range"));
871         return;
872         break;
873     }
874   subseg_set (section, 0);
875 }
876
877 /* This finishes off parsing a .comm or .lcomm statement, which both can have
878    an (optional) alignment field.  It also allows us to create the bss section
879    on demand.  */
880
881 static symbolS *
882 obj_mach_o_common_parse (int is_local, symbolS *symbolP,
883                          addressT size)
884 {
885   addressT align = 0;
886   bfd_mach_o_asymbol *s;
887
888   SKIP_WHITESPACE ();  
889
890   /* Both comm and lcomm take an optional alignment, as a power
891      of two between 1 and 15.  */
892   if (*input_line_pointer == ',')
893     {
894       /* We expect a power of 2.  */
895       align = parse_align (0);
896       if (align == (addressT) -1)
897         return NULL;
898       if (align > 15)
899         {
900           as_warn (_("Alignment (%lu) too large: 15 assumed."),
901                   (unsigned long)align);
902           align = 15;
903         }
904     }
905
906   s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (symbolP);
907   if (is_local)
908     {
909       /* Create the BSS section on demand.  */
910       if (bss_section == NULL)
911         {
912           bss_section = obj_mach_o_segT_from_bfd_name (BSS_SECTION_NAME, 1);
913           seg_info (bss_section)->bss = 1;        
914         }
915       bss_alloc (symbolP, size, align);
916       s->n_type = BFD_MACH_O_N_SECT;
917       S_CLEAR_EXTERNAL (symbolP);
918     }
919   else
920     {
921       S_SET_VALUE (symbolP, size);
922       S_SET_ALIGN (symbolP, align);
923       S_SET_EXTERNAL (symbolP);
924       S_SET_SEGMENT (symbolP, bfd_com_section_ptr);
925       s->n_type = BFD_MACH_O_N_UNDF | BFD_MACH_O_N_EXT;
926     }
927
928   /* This is a data object (whatever we choose that to mean).  */
929   s->symbol.flags |= BSF_OBJECT;
930
931   /* We've set symbol qualifiers, so validate if you can.  */
932   s->symbol.udata.i = SYM_MACHO_FIELDS_NOT_VALIDATED;
933
934   return symbolP;
935 }
936
937 static void
938 obj_mach_o_comm (int is_local)
939 {
940   s_comm_internal (is_local, obj_mach_o_common_parse);
941 }
942
943 /* Set properties that apply to the whole file.  At present, the only
944    one defined, is subsections_via_symbols.  */
945
946 typedef enum obj_mach_o_file_properties {
947   OBJ_MACH_O_FILE_PROP_NONE = 0,
948   OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS,
949   OBJ_MACH_O_FILE_PROP_MAX
950 } obj_mach_o_file_properties;
951
952 static void 
953 obj_mach_o_fileprop (int prop)
954 {
955   if (prop < 0 || prop >= OBJ_MACH_O_FILE_PROP_MAX)
956     as_fatal (_("internal error: bad file property ID %d"), prop);
957     
958   switch ((obj_mach_o_file_properties) prop)
959     {
960       case OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS:
961         obj_mach_o_subsections_by_symbols = 1;
962         if (!bfd_set_private_flags (stdoutput, 
963                                     BFD_MACH_O_MH_SUBSECTIONS_VIA_SYMBOLS))
964           as_bad (_("failed to set subsections by symbols"));
965         demand_empty_rest_of_line ();
966         break;
967       default:
968         break;
969     }
970 }
971
972 /* Temporary markers for symbol reference data.  
973    Lazy will remain in place.  */
974 #define LAZY 0x01
975 #define REFE 0x02
976
977 /* We have a bunch of qualifiers that may be applied to symbols.
978    .globl is handled here so that we might make sure that conflicting qualifiers
979    are caught where possible.  */
980
981 typedef enum obj_mach_o_symbol_type {
982   OBJ_MACH_O_SYM_UNK = 0,
983   OBJ_MACH_O_SYM_LOCAL = 1,
984   OBJ_MACH_O_SYM_GLOBL = 2,
985   OBJ_MACH_O_SYM_REFERENCE = 3,
986   OBJ_MACH_O_SYM_WEAK_REF = 4,
987   OBJ_MACH_O_SYM_LAZY_REF = 5,
988   OBJ_MACH_O_SYM_WEAK_DEF = 6,
989   OBJ_MACH_O_SYM_PRIV_EXT = 7,
990   OBJ_MACH_O_SYM_NO_DEAD_STRIP = 8,
991   OBJ_MACH_O_SYM_WEAK = 9
992 } obj_mach_o_symbol_type;
993
994 /* Set Mach-O-specific symbol qualifiers. */
995
996 static int
997 obj_mach_o_set_symbol_qualifier (symbolS *sym, int type)
998 {
999   int is_defined;
1000   bfd_mach_o_asymbol *s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (sym);
1001   bfd_mach_o_section *sec;
1002   int sectype = -1;
1003   int err = 0;
1004
1005   /* If the symbol is defined, then we can do more rigorous checking on
1006      the validity of the qualifiers.  Otherwise, we are stuck with waiting 
1007      until it's defined - or until write the file.
1008      
1009      In certain cases (e.g. when a symbol qualifier is intended to introduce
1010      an undefined symbol in a stubs section) we should check that the current
1011      section is appropriate to the qualifier.  */
1012
1013   is_defined = s->symbol.section != bfd_und_section_ptr;
1014   if (is_defined)
1015     sec = bfd_mach_o_get_mach_o_section (s->symbol.section) ;
1016   else
1017     sec = bfd_mach_o_get_mach_o_section (now_seg) ;
1018
1019   if (sec != NULL)
1020     sectype = sec->flags & BFD_MACH_O_SECTION_TYPE_MASK;
1021
1022   switch ((obj_mach_o_symbol_type) type)
1023     {
1024       case OBJ_MACH_O_SYM_LOCAL:
1025         /* This is an extension over the system tools.  */
1026         if (s->n_type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT))
1027           {
1028             as_bad (_("'%s' previously declared as '%s'."), s->symbol.name,
1029                       (s->n_type & BFD_MACH_O_N_PEXT) ? "private extern"
1030                                                       : "global" );
1031             err = 1;
1032           }
1033         else
1034           {
1035             s->n_type &= ~BFD_MACH_O_N_EXT;
1036             S_CLEAR_EXTERNAL (sym);
1037           }
1038         break;
1039
1040       case OBJ_MACH_O_SYM_PRIV_EXT:
1041         s->n_type |= BFD_MACH_O_N_PEXT ;
1042         s->n_desc &= ~LAZY; /* The native tool switches this off too.  */
1043         /* We follow the system tools in marking PEXT as also global.  */
1044         /* Fall through.  */
1045
1046       case OBJ_MACH_O_SYM_GLOBL:
1047         /* It's not an error to define a symbol and then make it global.  */
1048         s->n_type |= BFD_MACH_O_N_EXT;
1049         S_SET_EXTERNAL (sym);
1050         break;
1051
1052       case OBJ_MACH_O_SYM_REFERENCE:
1053         if (is_defined)
1054           s->n_desc |= BFD_MACH_O_N_NO_DEAD_STRIP;
1055         else
1056           s->n_desc |= (REFE | BFD_MACH_O_N_NO_DEAD_STRIP);
1057         break;
1058
1059       case OBJ_MACH_O_SYM_LAZY_REF:
1060         if (is_defined)
1061           s->n_desc |= BFD_MACH_O_N_NO_DEAD_STRIP;
1062         else
1063           s->n_desc |= (REFE | LAZY | BFD_MACH_O_N_NO_DEAD_STRIP);
1064         break;
1065
1066       /* Force ld to retain the symbol - even if it appears unused.  */
1067       case OBJ_MACH_O_SYM_NO_DEAD_STRIP:
1068         s->n_desc |= BFD_MACH_O_N_NO_DEAD_STRIP ;
1069         break;
1070
1071       /* Mach-O's idea of weak ...  */
1072       case OBJ_MACH_O_SYM_WEAK_REF:
1073         s->n_desc |= BFD_MACH_O_N_WEAK_REF ;
1074         break;
1075
1076       case OBJ_MACH_O_SYM_WEAK_DEF:
1077         if (is_defined && sectype != BFD_MACH_O_S_COALESCED)
1078           {
1079             as_bad (_("'%s' can't be a weak_definition (currently only"
1080                       " supported in sections of type coalesced)"),
1081                       s->symbol.name);
1082             err = 1;
1083           }
1084         else
1085           s->n_desc |= BFD_MACH_O_N_WEAK_DEF;
1086         break;
1087
1088       case OBJ_MACH_O_SYM_WEAK:
1089         /* A generic 'weak' - we try to figure out what it means at
1090            symbol frob time.  */
1091         S_SET_WEAK (sym);
1092         break;
1093
1094       default:
1095         break;
1096     }
1097
1098     /* We've seen some kind of qualifier - check validity if or when the entity
1099      is defined.  */
1100   s->symbol.udata.i = SYM_MACHO_FIELDS_NOT_VALIDATED;
1101   return err;
1102 }
1103
1104 /* Respond to symbol qualifiers.
1105    All of the form:
1106    .<qualifier> symbol [, symbol]*
1107    a list of symbols is an extension over the Darwin system as.  */
1108
1109 static void
1110 obj_mach_o_sym_qual (int ntype)
1111 {
1112   char *name;
1113   char c;
1114   symbolS *symbolP;
1115
1116 #ifdef md_flush_pending_output
1117   md_flush_pending_output ();
1118 #endif
1119
1120   do
1121     {
1122       name = input_line_pointer;
1123       c = get_symbol_end ();
1124       symbolP = symbol_find_or_make (name);
1125       obj_mach_o_set_symbol_qualifier (symbolP, ntype);
1126       *input_line_pointer = c;
1127       SKIP_WHITESPACE ();
1128       c = *input_line_pointer;
1129       if (c == ',')
1130         {
1131           input_line_pointer++;
1132           SKIP_WHITESPACE ();
1133           if (is_end_of_line[(unsigned char) *input_line_pointer])
1134             c = '\n';
1135         }
1136     }
1137   while (c == ',');
1138
1139   demand_empty_rest_of_line ();
1140 }
1141
1142 typedef struct obj_mach_o_indirect_sym
1143 {
1144   symbolS *sym;
1145   segT sect;
1146   struct obj_mach_o_indirect_sym *next;
1147 } obj_mach_o_indirect_sym;
1148
1149 /* We store in order an maintain a pointer to the last one - to save reversing
1150    later.  */
1151 obj_mach_o_indirect_sym *indirect_syms;
1152 obj_mach_o_indirect_sym *indirect_syms_tail;
1153
1154 static void
1155 obj_mach_o_indirect_symbol (int arg ATTRIBUTE_UNUSED)
1156 {
1157   bfd_mach_o_section *sec = bfd_mach_o_get_mach_o_section (now_seg);
1158
1159 #ifdef md_flush_pending_output
1160   md_flush_pending_output ();
1161 #endif
1162
1163   if (obj_mach_o_is_static)
1164     as_bad (_("use of .indirect_symbols requires `-dynamic'"));
1165
1166   switch (sec->flags & BFD_MACH_O_SECTION_TYPE_MASK)
1167     {
1168       case BFD_MACH_O_S_SYMBOL_STUBS:
1169       case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
1170       case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
1171         {
1172           obj_mach_o_indirect_sym *isym;
1173           char *name = input_line_pointer;
1174           char c = get_symbol_end ();
1175           symbolS *sym = symbol_find_or_make (name);
1176           unsigned int elsize =
1177                         bfd_mach_o_section_get_entry_size (stdoutput, sec);
1178
1179           if (elsize == 0)
1180             {
1181               as_bad (_("attempt to add an indirect_symbol to a stub or"
1182                         " reference section with a zero-sized element at %s"),
1183                         name);
1184               *input_line_pointer = c;
1185               ignore_rest_of_line ();
1186               return;
1187           }
1188           *input_line_pointer = c;
1189
1190           isym = (obj_mach_o_indirect_sym *)
1191                         xmalloc (sizeof (obj_mach_o_indirect_sym));
1192
1193           /* Just record the data for now, we will validate it when we
1194              compute the output in obj_mach_o_set_indirect_symbols.  */
1195           isym->sym = sym;
1196           isym->sect = now_seg;
1197           isym->next = NULL;
1198           if (indirect_syms == NULL)
1199             indirect_syms = isym;
1200           else
1201             indirect_syms_tail->next = isym;
1202           indirect_syms_tail = isym;
1203         }
1204         break;
1205
1206       default:
1207         as_bad (_("an .indirect_symbol must be in a symbol pointer"
1208                   " or stub section."));
1209         ignore_rest_of_line ();
1210         return;
1211     }
1212   demand_empty_rest_of_line ();
1213 }
1214
1215 const pseudo_typeS mach_o_pseudo_table[] =
1216 {
1217   /* Section directives.  */
1218   { "comm", obj_mach_o_comm, 0 },
1219   { "lcomm", obj_mach_o_comm, 1 },
1220
1221   { "text", obj_mach_o_base_section, 1},
1222   { "data", obj_mach_o_base_section, 2},
1223   { "bss", obj_mach_o_base_section, 3},   /* extension */
1224
1225   { "const", obj_mach_o_known_section, 1},
1226   { "static_const", obj_mach_o_known_section, 2},
1227   { "cstring", obj_mach_o_known_section, 3},
1228   { "literal4", obj_mach_o_known_section, 4},
1229   { "literal8", obj_mach_o_known_section, 5},
1230   { "literal16", obj_mach_o_known_section, 6},
1231   { "constructor", obj_mach_o_known_section, 7},
1232   { "destructor", obj_mach_o_known_section, 8},
1233   { "eh_frame", obj_mach_o_known_section, 9},
1234
1235   { "const_data", obj_mach_o_known_section, 10},
1236   { "static_data", obj_mach_o_known_section, 11},
1237   { "mod_init_func", obj_mach_o_known_section, 12},
1238   { "mod_term_func", obj_mach_o_known_section, 13},
1239   { "dyld", obj_mach_o_known_section, 14},
1240   { "cfstring", obj_mach_o_known_section, 15},
1241
1242   { "objc_class", obj_mach_o_objc_section, 1},
1243   { "objc_meta_class", obj_mach_o_objc_section, 2},
1244   { "objc_cat_cls_meth", obj_mach_o_objc_section, 3},
1245   { "objc_cat_inst_meth", obj_mach_o_objc_section, 4},
1246   { "objc_protocol", obj_mach_o_objc_section, 5},
1247   { "objc_string_object", obj_mach_o_objc_section, 6},
1248   { "objc_cls_meth", obj_mach_o_objc_section, 7},
1249   { "objc_inst_meth", obj_mach_o_objc_section, 8},
1250   { "objc_cls_refs", obj_mach_o_objc_section, 9},
1251   { "objc_message_refs", obj_mach_o_objc_section, 10},
1252   { "objc_symbols", obj_mach_o_objc_section, 11},
1253   { "objc_category", obj_mach_o_objc_section, 12},
1254   { "objc_class_vars", obj_mach_o_objc_section, 13},
1255   { "objc_instance_vars", obj_mach_o_objc_section, 14},
1256   { "objc_module_info", obj_mach_o_objc_section, 15},
1257   { "objc_class_names", obj_mach_o_objc_section, 16}, /* Alias for .cstring */
1258   { "objc_meth_var_types", obj_mach_o_objc_section, 17}, /* Alias for .cstring */
1259   { "objc_meth_var_names", obj_mach_o_objc_section, 18}, /* Alias for .cstring */
1260   { "objc_selector_strs", obj_mach_o_objc_section, 19},
1261   { "objc_image_info", obj_mach_o_objc_section, 20}, /* extension.  */
1262   { "objc_selector_fixup", obj_mach_o_objc_section, 21}, /* extension.  */
1263   { "objc1_class_ext", obj_mach_o_objc_section, 22}, /* ObjC-1 extension.  */
1264   { "objc1_property_list", obj_mach_o_objc_section, 23}, /* ObjC-1 extension.  */
1265   { "objc1_protocol_ext", obj_mach_o_objc_section, 24}, /* ObjC-1 extension.  */
1266
1267   { "debug_frame", obj_mach_o_debug_section, 1}, /* extension.  */
1268   { "debug_info", obj_mach_o_debug_section, 2}, /* extension.  */
1269   { "debug_abbrev", obj_mach_o_debug_section, 3}, /* extension.  */
1270   { "debug_aranges", obj_mach_o_debug_section, 4}, /* extension.  */
1271   { "debug_macinfo", obj_mach_o_debug_section, 5}, /* extension.  */
1272   { "debug_line", obj_mach_o_debug_section, 6}, /* extension.  */
1273   { "debug_loc", obj_mach_o_debug_section, 7}, /* extension.  */
1274   { "debug_pubnames", obj_mach_o_debug_section, 8}, /* extension.  */
1275   { "debug_pubtypes", obj_mach_o_debug_section, 9}, /* extension.  */
1276   { "debug_str", obj_mach_o_debug_section, 10}, /* extension.  */
1277   { "debug_ranges", obj_mach_o_debug_section, 11}, /* extension.  */
1278   { "debug_macro", obj_mach_o_debug_section, 12}, /* extension.  */
1279   
1280   { "lazy_symbol_pointer", obj_mach_o_opt_tgt_section, 1},
1281   { "lazy_symbol_pointer2", obj_mach_o_opt_tgt_section, 2}, /* extension.  */
1282   { "lazy_symbol_pointer3", obj_mach_o_opt_tgt_section, 3}, /* extension.  */
1283   { "non_lazy_symbol_pointer", obj_mach_o_opt_tgt_section, 4},
1284   { "non_lazy_symbol_pointer_x86", obj_mach_o_opt_tgt_section, 5}, /* extension.  */
1285   { "symbol_stub", obj_mach_o_opt_tgt_section, 6},
1286   { "symbol_stub1", obj_mach_o_opt_tgt_section, 7}, /* extension.  */
1287   { "picsymbol_stub", obj_mach_o_opt_tgt_section, 8}, /* extension.  */
1288   { "picsymbol_stub1", obj_mach_o_opt_tgt_section, 9}, /* extension.  */
1289   { "picsymbol_stub2", obj_mach_o_opt_tgt_section, 4}, /* extension.  */
1290   { "picsymbol_stub3", obj_mach_o_opt_tgt_section, 4}, /* extension.  */
1291
1292   { "section", obj_mach_o_section, 0},
1293   { "zerofill", obj_mach_o_zerofill, 0},
1294
1295   /* Symbol qualifiers.  */
1296   {"local",             obj_mach_o_sym_qual, OBJ_MACH_O_SYM_LOCAL},
1297   {"globl",             obj_mach_o_sym_qual, OBJ_MACH_O_SYM_GLOBL},
1298   {"reference",         obj_mach_o_sym_qual, OBJ_MACH_O_SYM_REFERENCE},
1299   {"weak_reference",    obj_mach_o_sym_qual, OBJ_MACH_O_SYM_WEAK_REF},
1300   {"lazy_reference",    obj_mach_o_sym_qual, OBJ_MACH_O_SYM_LAZY_REF},
1301   {"weak_definition",   obj_mach_o_sym_qual, OBJ_MACH_O_SYM_WEAK_DEF},
1302   {"private_extern",    obj_mach_o_sym_qual, OBJ_MACH_O_SYM_PRIV_EXT},
1303   {"no_dead_strip",     obj_mach_o_sym_qual, OBJ_MACH_O_SYM_NO_DEAD_STRIP},
1304   {"weak",              obj_mach_o_sym_qual, OBJ_MACH_O_SYM_WEAK}, /* ext */
1305
1306   { "indirect_symbol",  obj_mach_o_indirect_symbol, 0},
1307
1308   /* File flags.  */
1309   { "subsections_via_symbols", obj_mach_o_fileprop, 
1310                                OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS},
1311
1312   {NULL, NULL, 0}
1313 };
1314
1315 /* Determine the default n_type value for a symbol from its section.  */
1316
1317 static unsigned
1318 obj_mach_o_type_for_symbol (bfd_mach_o_asymbol *s)
1319 {
1320   if (s->symbol.section == bfd_abs_section_ptr)
1321     return BFD_MACH_O_N_ABS;
1322   else if (s->symbol.section == bfd_com_section_ptr
1323            || s->symbol.section == bfd_und_section_ptr)
1324     return BFD_MACH_O_N_UNDF;
1325   else
1326     return BFD_MACH_O_N_SECT;
1327 }
1328
1329 /* We need to check the correspondence between some kinds of symbols and their
1330    sections.  Common and BSS vars will seen via the obj_macho_comm() function.
1331    
1332    The earlier we can pick up a problem, the better the diagnostics will be.
1333    
1334    However, when symbol type information is attached, the symbol section will
1335    quite possibly be unknown.  So we are stuck with checking (most of the)
1336    validity at the time the file is written (unfortunately, then one doesn't
1337    get line number information in the diagnostic).  */
1338
1339 /* Here we pick up the case where symbol qualifiers have been applied that
1340    are possibly incompatible with the section etc. that the symbol is defined
1341    in.  */
1342
1343 void obj_macho_frob_label (struct symbol *sp)
1344 {
1345   bfd_mach_o_asymbol *s;
1346   unsigned base_type;
1347   bfd_mach_o_section *sec;
1348   int sectype = -1;
1349
1350   /* Leave local symbols alone.  */
1351
1352   if (S_IS_LOCAL (sp))
1353     return;
1354
1355   s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (sp);
1356   /* Leave debug symbols alone.  */
1357   if ((s->n_type & BFD_MACH_O_N_STAB) != 0)
1358     return;
1359
1360   /* This is the base symbol type, that we mask in.  */
1361   base_type = obj_mach_o_type_for_symbol (s);
1362
1363   sec = bfd_mach_o_get_mach_o_section (s->symbol.section);  
1364   if (sec != NULL)
1365     sectype = sec->flags & BFD_MACH_O_SECTION_TYPE_MASK;
1366
1367   /* If there is a pre-existing qualifier, we can make some checks about
1368      validity now.  */
1369
1370   if(s->symbol.udata.i == SYM_MACHO_FIELDS_NOT_VALIDATED)
1371     {
1372       if ((s->n_desc & BFD_MACH_O_N_WEAK_DEF)
1373           && sectype != BFD_MACH_O_S_COALESCED)
1374         as_bad (_("'%s' can't be a weak_definition (currently only supported"
1375                   " in sections of type coalesced)"), s->symbol.name);
1376
1377       /* Have we changed from an undefined to defined ref? */
1378       s->n_desc &= ~(REFE | LAZY);
1379     }
1380
1381   s->n_type &= ~BFD_MACH_O_N_TYPE;
1382   s->n_type |= base_type;
1383 }
1384
1385 /* This is the fall-back, we come here when we get to the end of the file and
1386    the symbol is not defined - or there are combinations of qualifiers required
1387    (e.g. global + weak_def).  */
1388
1389 int
1390 obj_macho_frob_symbol (struct symbol *sp)
1391 {
1392   bfd_mach_o_asymbol *s;
1393   unsigned base_type;
1394   bfd_mach_o_section *sec;
1395   int sectype = -1;
1396
1397   /* Leave local symbols alone.  */
1398   if (S_IS_LOCAL (sp))
1399     return 0;
1400
1401   s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (sp);
1402   /* Leave debug symbols alone.  */
1403   if ((s->n_type & BFD_MACH_O_N_STAB) != 0)
1404     return 0;
1405
1406   base_type = obj_mach_o_type_for_symbol (s);
1407   sec = bfd_mach_o_get_mach_o_section (s->symbol.section);  
1408   if (sec != NULL)
1409     sectype = sec->flags & BFD_MACH_O_SECTION_TYPE_MASK;
1410
1411   if (s->symbol.section == bfd_und_section_ptr)
1412     {
1413       /* ??? Do we really gain much from implementing this as well as the
1414          mach-o specific ones?  */
1415       if (s->symbol.flags & BSF_WEAK)
1416         s->n_desc |= BFD_MACH_O_N_WEAK_REF;
1417
1418       /* Undefined syms, become extern.  */
1419       s->n_type |= BFD_MACH_O_N_EXT;
1420       S_SET_EXTERNAL (sp);
1421     }
1422   else if (s->symbol.section == bfd_com_section_ptr)
1423     {
1424       /* ... so do comm.  */
1425       s->n_type |= BFD_MACH_O_N_EXT;
1426       S_SET_EXTERNAL (sp);
1427     }
1428   else
1429     {
1430       if ((s->symbol.flags & BSF_WEAK)
1431            && (sectype == BFD_MACH_O_S_COALESCED)
1432            && (s->n_type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT)))
1433         s->n_desc |= BFD_MACH_O_N_WEAK_DEF;
1434 /* ??? we should do this - but then that reveals that the semantics of weak
1435        are different from what's supported in mach-o object files.
1436       else
1437         as_bad (_("'%s' can't be a weak_definition."),
1438                 s->symbol.name); */
1439     }
1440
1441   if (s->symbol.udata.i == SYM_MACHO_FIELDS_UNSET)
1442     {
1443       /* Anything here that should be added that is non-standard.  */
1444       s->n_desc &= ~BFD_MACH_O_REFERENCE_MASK;
1445       s->symbol.udata.i = SYM_MACHO_FIELDS_NOT_VALIDATED;
1446     }    
1447   else if (s->symbol.udata.i == SYM_MACHO_FIELDS_NOT_VALIDATED)
1448     {
1449       /* Try to validate any combinations.  */
1450       if (s->n_desc & BFD_MACH_O_N_WEAK_DEF)
1451         {
1452           if (s->symbol.section == bfd_und_section_ptr)
1453             as_bad (_("'%s' can't be a weak_definition (since it is"
1454                       " undefined)"), s->symbol.name);
1455           else if (sectype != BFD_MACH_O_S_COALESCED)
1456             as_bad (_("'%s' can't be a weak_definition (currently only supported"
1457                       " in sections of type coalesced)"), s->symbol.name);
1458           else if (! (s->n_type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT)))
1459             as_bad (_("Non-global symbol: '%s' can't be a weak_definition."),
1460                     s->symbol.name);
1461         }
1462
1463     }
1464   else
1465     as_bad (_("internal error: [%s] unexpected code [%lx] in frob symbol"),
1466             s->symbol.name, (unsigned long)s->symbol.udata.i);
1467
1468   s->n_type &= ~BFD_MACH_O_N_TYPE;
1469   s->n_type |= base_type;
1470
1471   if (s->symbol.flags & BSF_GLOBAL)
1472     s->n_type |= BFD_MACH_O_N_EXT;
1473
1474   /* This cuts both ways - we promote some things to external above.  */
1475   if (s->n_type & (BFD_MACH_O_N_PEXT | BFD_MACH_O_N_EXT))
1476     S_SET_EXTERNAL (sp);
1477
1478   return 0;
1479 }
1480
1481 /* Zerofill and GB Zerofill sections must be sorted to follow all other
1482    sections in their segments.
1483
1484    The native 'as' leaves the sections physically in the order they appear in
1485    the source, and adjusts the section VMAs to meet the constraint.
1486    
1487    We follow this for now - if nothing else, it makes comparison easier.
1488
1489    An alternative implementation would be to sort the sections as ld requires.
1490    It might be advantageous to implement such a scheme in the future (or even
1491    to make the style of section ordering user-selectable).  */
1492
1493 typedef struct obj_mach_o_set_vma_data
1494 {
1495   bfd_vma vma;
1496   unsigned vma_pass;
1497   unsigned zerofill_seen;
1498   unsigned gb_zerofill_seen;
1499 } obj_mach_o_set_vma_data;
1500
1501 /* We do (possibly) three passes through to set the vma, so that:
1502
1503    zerofill sections get VMAs after all others in their segment
1504    GB zerofill get VMAs last.
1505    
1506    As we go, we notice if we see any Zerofill or GB Zerofill sections, so that
1507    we can skip the additional passes if there's nothing to do.  */
1508
1509 static void
1510 obj_mach_o_set_section_vma (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *v_p)
1511 {
1512   bfd_mach_o_section *ms = bfd_mach_o_get_mach_o_section (sec);
1513   unsigned bfd_align = bfd_get_section_alignment (abfd, sec);
1514   obj_mach_o_set_vma_data *p = (struct obj_mach_o_set_vma_data *)v_p;
1515   unsigned sectype = (ms->flags & BFD_MACH_O_SECTION_TYPE_MASK);
1516   unsigned zf;
1517
1518   zf = 0;
1519   if (sectype == BFD_MACH_O_S_ZEROFILL)
1520     {
1521       zf = 1;
1522       p->zerofill_seen = zf;
1523     }
1524   else if (sectype == BFD_MACH_O_S_GB_ZEROFILL)
1525     {
1526       zf = 2;
1527       p->gb_zerofill_seen = zf;
1528     }
1529
1530   if (p->vma_pass != zf)
1531     return;
1532
1533   /* We know the section size now - so make a vma for the section just
1534      based on order.  */
1535   ms->size = bfd_get_section_size (sec);
1536   
1537   /* Make sure that the align agrees, and set to the largest value chosen.  */
1538   ms->align = ms->align > bfd_align ? ms->align : bfd_align;
1539   bfd_set_section_alignment (abfd, sec, ms->align);
1540   
1541   p->vma += (1 << ms->align) - 1;
1542   p->vma &= ~((1 << ms->align) - 1);
1543   ms->addr = p->vma;
1544   bfd_set_section_vma (abfd, sec, p->vma);
1545   p->vma += ms->size;
1546 }
1547
1548 /* (potentially) three passes over the sections, setting VMA.  We skip the 
1549   {gb}zerofill passes if we didn't see any of the relevant sections.  */
1550
1551 void obj_mach_o_post_relax_hook (void)
1552 {
1553   obj_mach_o_set_vma_data d;
1554
1555   memset (&d, 0, sizeof (d));
1556   
1557   bfd_map_over_sections (stdoutput, obj_mach_o_set_section_vma, (char *) &d);
1558   if ((d.vma_pass = d.zerofill_seen) != 0)
1559     bfd_map_over_sections (stdoutput, obj_mach_o_set_section_vma, (char *) &d);
1560   if ((d.vma_pass = d.gb_zerofill_seen) != 0)
1561     bfd_map_over_sections (stdoutput, obj_mach_o_set_section_vma, (char *) &d);
1562 }
1563
1564 static void
1565 obj_mach_o_set_indirect_symbols (bfd *abfd, asection *sec,
1566                                  void *xxx ATTRIBUTE_UNUSED)
1567 {
1568   bfd_vma sect_size = bfd_section_size (abfd, sec);
1569   bfd_mach_o_section *ms = bfd_mach_o_get_mach_o_section (sec);
1570   unsigned lazy = 0;
1571
1572   /* See if we have any indirect syms to consider.  */
1573   if (indirect_syms == NULL)
1574     return;
1575
1576   /* Process indirect symbols.
1577      Check for errors, if OK attach them as a flat array to the section
1578      for which they are defined.  */
1579
1580   switch (ms->flags & BFD_MACH_O_SECTION_TYPE_MASK)
1581     {
1582       case BFD_MACH_O_S_SYMBOL_STUBS:
1583       case BFD_MACH_O_S_LAZY_SYMBOL_POINTERS:
1584         lazy = LAZY;
1585         /* Fall through.  */
1586       case BFD_MACH_O_S_NON_LAZY_SYMBOL_POINTERS:
1587         {
1588           unsigned int nactual = 0;
1589           unsigned int ncalc;
1590           obj_mach_o_indirect_sym *isym;
1591           obj_mach_o_indirect_sym *list = NULL;
1592           obj_mach_o_indirect_sym *list_tail = NULL;
1593           unsigned long eltsiz = 
1594                         bfd_mach_o_section_get_entry_size (abfd, ms);
1595
1596           for (isym = indirect_syms; isym != NULL; isym = isym->next)
1597             {
1598               if (isym->sect == sec)
1599                 {
1600                   nactual++;
1601                   if (list == NULL)
1602                     list = isym;
1603                   else
1604                     list_tail->next = isym;
1605                   list_tail = isym;
1606                 }
1607             }
1608
1609           /* If none are in this section, stop here.  */
1610           if (nactual == 0)
1611             break;
1612
1613           /* If we somehow added indirect symbols to a section with a zero
1614              entry size, we're dead ... */
1615           gas_assert (eltsiz != 0);
1616
1617           ncalc = (unsigned int) (sect_size / eltsiz);
1618           if (nactual != ncalc)
1619             as_bad (_("the number of .indirect_symbols defined in section %s"
1620                       " does not match the number expected (%d defined, %d"
1621                       " expected)"), sec->name, nactual, ncalc);
1622           else
1623             {
1624               unsigned n;
1625               bfd_mach_o_asymbol *sym;
1626               ms->indirect_syms =
1627                         bfd_zalloc (abfd,
1628                                     nactual * sizeof (bfd_mach_o_asymbol *));
1629
1630               if (ms->indirect_syms == NULL)
1631                 {
1632                   as_fatal (_("internal error: failed to allocate %d indirect"
1633                               "symbol pointers"), nactual);
1634                 }
1635               
1636               for (isym = list, n = 0; isym != NULL; isym = isym->next, n++)
1637                 {
1638                   sym = (bfd_mach_o_asymbol *)symbol_get_bfdsym (isym->sym);
1639                   /* Array is init to NULL & NULL signals a local symbol
1640                      If the section is lazy-bound, we need to keep the
1641                      reference to the symbol, since dyld can override.
1642                      
1643                      Absolute symbols are handled specially.  */
1644                   if (sym->symbol.section == bfd_abs_section_ptr)
1645                     ms->indirect_syms[n] = sym;
1646                   else if (S_IS_LOCAL (isym->sym) && ! lazy)
1647                     ;
1648                   else
1649                     {
1650                       if (sym == NULL)
1651                         ;
1652                       /* If the symbols is external ...  */
1653                       else if (S_IS_EXTERNAL (isym->sym)
1654                                || (sym->n_type & BFD_MACH_O_N_EXT)
1655                                || ! S_IS_DEFINED (isym->sym)
1656                                || lazy)
1657                         {
1658                           sym->n_desc &= ~LAZY;
1659                           /* ... it can be lazy, if not defined or hidden.  */
1660                           if ((sym->n_type & BFD_MACH_O_N_TYPE) 
1661                                == BFD_MACH_O_N_UNDF 
1662                               && ! (sym->n_type & BFD_MACH_O_N_PEXT)
1663                               && (sym->n_type & BFD_MACH_O_N_EXT))
1664                             sym->n_desc |= lazy;
1665                           ms->indirect_syms[n] = sym;
1666                         }
1667                     }
1668                 }
1669             }
1670         }
1671         break;
1672
1673       default:
1674         break;
1675     }
1676 }
1677
1678 /* The process of relocation could alter what's externally visible, thus we
1679    leave setting the indirect symbols until last.  */
1680
1681 void
1682 obj_mach_o_frob_file_after_relocs (void)
1683 {
1684   bfd_map_over_sections (stdoutput, obj_mach_o_set_indirect_symbols, (char *) 0);
1685 }
1686
1687 /* Reverse relocations order to make ld happy.  */
1688
1689 void
1690 obj_mach_o_reorder_section_relocs (asection *sec, arelent **rels, unsigned int n)
1691 {
1692   unsigned int i;
1693   unsigned int max = n / 2;
1694
1695   for (i = 0; i < max; i++)
1696     {
1697       arelent *r = rels[i];
1698       rels[i] = rels[n - i - 1];
1699       rels[n - i - 1] = r;
1700     }
1701   bfd_set_reloc (stdoutput, sec, rels, n);
1702 }
1703
1704 /* Support stabs for mach-o.  */
1705
1706 void
1707 obj_mach_o_process_stab (int what, const char *string,
1708                          int type, int other, int desc)
1709 {
1710   symbolS *symbolP;
1711   bfd_mach_o_asymbol *s;
1712
1713   switch (what)
1714     {
1715       case 'd':
1716         symbolP = symbol_new ("", now_seg, frag_now_fix (), frag_now);
1717         /* Special stabd NULL name indicator.  */
1718         S_SET_NAME (symbolP, NULL);
1719         break;
1720
1721       case 'n':
1722       case 's':
1723         symbolP = symbol_new (string, undefined_section, (valueT) 0,
1724                               &zero_address_frag);
1725         pseudo_set (symbolP);
1726         break;
1727
1728       default:
1729         as_bad(_("unrecognized stab type '%c'"), (char)what);
1730         abort ();
1731         break;
1732     }
1733
1734   s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (symbolP);
1735   s->n_type = type;
1736   s->n_desc = desc;
1737   /* For stabd, this will eventually get overwritten by the section number.  */
1738   s->n_sect = other;
1739
1740   /* It's a debug symbol.  */
1741   s->symbol.flags |= BSF_DEBUGGING;
1742 }