add .zerofill to mach-o GAS.
[external/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 /* Forward decls.  */
49 static segT obj_mach_o_segT_from_bfd_name (const char *, int);
50
51 /* TODO: Implement "-dynamic"/"-static" command line options.  */
52
53 static int obj_mach_o_is_static;
54
55 /* TODO: Implement the "-n" command line option to suppress the initial
56    switch to the text segment.  */
57 static int obj_mach_o_start_with_text_section = 1;
58
59 /* Allow for special re-ordering on output.  */
60
61 static int obj_mach_o_seen_objc_section;
62
63 /* Start-up: At present, just create the sections we want.  */
64 void
65 mach_o_begin (void)
66 {
67   /* Mach-O only defines the .text section by default, and even this can
68      be suppressed by a flag.  In the latter event, the first code MUST
69      be a section definition.  */
70   if (obj_mach_o_start_with_text_section)
71     {
72       text_section = obj_mach_o_segT_from_bfd_name (TEXT_SECTION_NAME, 1);
73       subseg_set (text_section, 0);
74       if (obj_mach_o_is_static)
75         {
76           bfd_mach_o_section *mo_sec 
77                         = bfd_mach_o_get_mach_o_section (text_section);
78           mo_sec->flags &= ~BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS;
79         }
80     }
81 }
82
83 /* Remember the subsections_by_symbols state in case we need to reset
84    the file flags.  */
85 static int obj_mach_o_subsections_by_symbols;
86
87 static void
88 obj_mach_o_weak (int ignore ATTRIBUTE_UNUSED)
89 {
90   char *name;
91   int c;
92   symbolS *symbolP;
93
94   do
95     {
96       /* Get symbol name.  */
97       name = input_line_pointer;
98       c = get_symbol_end ();
99       symbolP = symbol_find_or_make (name);
100       S_SET_WEAK (symbolP);
101       *input_line_pointer = c;
102       SKIP_WHITESPACE ();
103
104       if (c != ',')
105         break;
106       input_line_pointer++;
107       SKIP_WHITESPACE ();
108     }
109   while (*input_line_pointer != '\n');
110   demand_empty_rest_of_line ();
111 }
112
113 /* This will put at most 16 characters (terminated by a ',' or newline) from
114    the input stream into dest.  If there are more than 16 chars before the
115    delimiter, a warning is given and the string is truncated.  On completion of
116    this function, input_line_pointer will point to the char after the ',' or 
117    to the newline.  
118    
119    It trims leading and trailing space.  */
120
121 static int
122 collect_16char_name (char *dest, const char *msg, int require_comma)
123 {
124   char c, *namstart;
125
126   SKIP_WHITESPACE ();
127   namstart = input_line_pointer;
128
129   while ( (c = *input_line_pointer) != ',' 
130          && !is_end_of_line[(unsigned char) c])
131     input_line_pointer++;
132
133   {
134       int len = input_line_pointer - namstart; /* could be zero.  */
135       /* lose any trailing space.  */  
136       while (len > 0 && namstart[len-1] == ' ') 
137         len--;
138       if (len > 16)
139         {
140           *input_line_pointer = '\0'; /* make a temp string.  */
141           as_bad (_("the %s name '%s' is too long (maximum 16 characters)"),
142                      msg, namstart);
143           *input_line_pointer = c; /* restore for printing.  */
144           len = 16;
145         }
146       if (len > 0)
147         memcpy (dest, namstart, len);
148   }
149
150   if (c != ',' && require_comma)
151     {
152       as_bad (_("expected a %s name followed by a `,'"), msg);
153       return 1;
154     }
155
156   return 0;
157 }
158
159 static int
160 obj_mach_o_get_section_names (char *seg, char *sec,
161                               unsigned segl, unsigned secl)
162 {
163   /* Zero-length segment and section names are allowed.  */
164   /* Parse segment name.  */
165   memset (seg, 0, segl);
166   if (collect_16char_name (seg, "segment", 1))
167     {
168       ignore_rest_of_line ();
169       return 0;
170     }
171   input_line_pointer++; /* Skip the terminating ',' */
172
173   /* Parse section name, which can be empty.  */
174   memset (sec, 0, secl);
175   collect_16char_name (sec, "section", 0);
176   return 1;
177 }
178
179 /* Build (or get) a section from the mach-o description - which includes
180    optional definitions for type, attributes, alignment and stub size.
181    
182    BFD supplies default values for sections which have a canonical name.  */
183
184 #define SECT_TYPE_SPECIFIED 0x0001
185 #define SECT_ATTR_SPECIFIED 0x0002
186 #define SECT_ALGN_SPECIFIED 0x0004
187
188 static segT
189 obj_mach_o_make_or_get_sect (char * segname, char * sectname,
190                              unsigned int specified_mask, 
191                              unsigned int usectype, unsigned int usecattr,
192                              unsigned int ualign, offsetT stub_size)
193 {
194   unsigned int sectype, secattr, secalign;
195   flagword oldflags, flags;
196   const char *name;
197   segT sec;
198   bfd_mach_o_section *msect;
199   const mach_o_section_name_xlat *xlat;
200
201   /* This provides default bfd flags and default mach-o section type and
202      attributes along with the canonical name.  */
203   xlat = bfd_mach_o_section_data_for_mach_sect (stdoutput, segname, sectname);
204
205   /* TODO: more checking of whether overides are acually allowed.  */
206
207   if (xlat != NULL)
208     {
209       name = xstrdup (xlat->bfd_name);
210       sectype = xlat->macho_sectype;
211       if (specified_mask & SECT_TYPE_SPECIFIED)
212         {
213           if ((sectype == BFD_MACH_O_S_ZEROFILL
214                || sectype == BFD_MACH_O_S_GB_ZEROFILL)
215               && sectype != usectype)
216             as_bad (_("cannot overide zerofill section type for `%s,%s'"),
217                     segname, sectname);
218           else
219             sectype = usectype;
220         }
221       secattr = xlat->macho_secattr;
222       secalign = xlat->sectalign;
223       flags = xlat->bfd_flags;
224     }
225   else
226     {
227       /* There is no normal BFD section name for this section.  Create one.
228          The name created doesn't really matter as it will never be written
229          on disk.  */
230       size_t seglen = strlen (segname);
231       size_t sectlen = strlen (sectname);
232       char *n;
233
234       n = xmalloc (seglen + 1 + sectlen + 1);
235       memcpy (n, segname, seglen);
236       n[seglen] = '.';
237       memcpy (n + seglen + 1, sectname, sectlen);
238       n[seglen + 1 + sectlen] = 0;
239       name = n;
240       if (specified_mask & SECT_TYPE_SPECIFIED)
241         sectype = usectype;
242       else
243         sectype = BFD_MACH_O_S_REGULAR;
244       secattr = BFD_MACH_O_S_ATTR_NONE;
245       secalign = 0;
246       flags = SEC_NO_FLAGS;
247     }
248
249   /* For now, just use what the user provided.  */
250
251   if (specified_mask & SECT_ATTR_SPECIFIED)
252     secattr = usecattr;
253
254   if (specified_mask & SECT_ALGN_SPECIFIED)
255     secalign = ualign;
256
257   /* Sub-segments don't exists as is on Mach-O.  */
258   sec = subseg_new (name, 0);
259
260   oldflags = bfd_get_section_flags (stdoutput, sec);
261   msect = bfd_mach_o_get_mach_o_section (sec);
262
263   if (oldflags == SEC_NO_FLAGS)
264     {
265       /* New, so just use the defaults or what's specified.  */
266       if (! bfd_set_section_flags (stdoutput, sec, flags))
267         as_warn (_("failed to set flags for \"%s\": %s"),
268                  bfd_section_name (stdoutput, sec),
269                  bfd_errmsg (bfd_get_error ()));
270  
271       strncpy (msect->segname, segname, sizeof (msect->segname));
272       strncpy (msect->sectname, sectname, sizeof (msect->sectname));
273
274       msect->align = secalign;
275       msect->flags = sectype | secattr;
276       msect->reserved2 = stub_size;
277       
278       if (sectype == BFD_MACH_O_S_ZEROFILL
279           || sectype == BFD_MACH_O_S_GB_ZEROFILL)
280         seg_info (sec)->bss = 1;
281     }
282   else if (flags != SEC_NO_FLAGS)
283     {
284       if (flags != oldflags
285           || msect->flags != (secattr | sectype))
286         as_warn (_("Ignoring changed section attributes for %s"), name);
287     }
288
289   return sec;
290 }
291
292 /* .section
293
294    The '.section' specification syntax looks like:
295    .section <segment> , <section> [, type [, attribs [, size]]]
296
297    White space is allowed everywhere between elements.
298
299    <segment> and <section> may be from 0 to 16 chars in length - they may
300    contain spaces but leading and trailing space will be trimmed.  It is 
301    mandatory that they be present (or that zero-length names are indicated
302    by ",,").
303
304    There is only a single section type for any entry.
305
306    There may be multiple attributes, they are delimited by `+'.
307
308    Not all section types and attributes are accepted by the Darwin system
309    assemblers as user-specifiable - although, at present, we do here.  */
310
311 static void
312 obj_mach_o_section (int ignore ATTRIBUTE_UNUSED)
313 {
314   unsigned int sectype = BFD_MACH_O_S_REGULAR;
315   unsigned int specified_mask = 0;
316   unsigned int secattr = 0;
317   offsetT sizeof_stub = 0;
318   segT new_seg;
319   char segname[17];
320   char sectname[17];
321
322 #ifdef md_flush_pending_output
323   md_flush_pending_output ();
324 #endif
325
326   /* Get the User's segment annd section names.  */
327   if (! obj_mach_o_get_section_names (segname, sectname, 17, 17))
328     return;
329
330   /* Parse section type, if present.  */
331   if (*input_line_pointer == ',')
332     {
333       char *p;
334       char c;
335       char tmpc;
336       int len;
337       input_line_pointer++;
338       SKIP_WHITESPACE ();
339       p = input_line_pointer;
340       while ((c = *input_line_pointer) != ','
341               && !is_end_of_line[(unsigned char) c])
342         input_line_pointer++;
343
344       len = input_line_pointer - p;
345       /* strip trailing spaces.  */
346       while (len > 0 && p[len-1] == ' ')
347         len--;
348       tmpc = p[len];
349
350       /* Temporarily make a string from the token.  */
351       p[len] = 0;
352       sectype = bfd_mach_o_get_section_type_from_name (stdoutput, p);
353       if (sectype > 255) /* Max Section ID == 255.  */
354         {
355           as_bad (_("unknown or invalid section type '%s'"), p);
356           p[len] = tmpc;
357           ignore_rest_of_line ();
358           return;
359         }
360       else
361         specified_mask |= SECT_TYPE_SPECIFIED;
362       /* Restore.  */
363       p[len] = tmpc;
364
365       /* Parse attributes.
366          TODO: check validity of attributes for section type.  */
367       if ((specified_mask & SECT_TYPE_SPECIFIED)
368           && c == ',')
369         {
370           do
371             {
372               int attr;
373
374               /* Skip initial `,' and subsequent `+'.  */
375               input_line_pointer++;
376               SKIP_WHITESPACE ();
377               p = input_line_pointer;
378               while ((c = *input_line_pointer) != '+'
379                       && c != ','
380                       && !is_end_of_line[(unsigned char) c])
381                 input_line_pointer++;
382
383               len = input_line_pointer - p;
384               /* strip trailing spaces.  */
385               while (len > 0 && p[len-1] == ' ')
386                 len--;
387               tmpc = p[len];
388
389               /* Temporarily make a string from the token.  */
390               p[len] ='\0';
391               attr = bfd_mach_o_get_section_attribute_from_name (p);
392               if (attr == -1)
393                 {
394                   as_bad (_("unknown or invalid section attribute '%s'"), p);
395                   p[len] = tmpc;
396                   ignore_rest_of_line ();
397                   return;
398                 }
399               else
400                 {
401                   specified_mask |= SECT_ATTR_SPECIFIED;
402                   secattr |= attr;
403                 }
404               /* Restore.  */
405               p[len] = tmpc;
406             }
407           while (*input_line_pointer == '+');
408
409           /* Parse sizeof_stub.  */
410           if ((specified_mask & SECT_ATTR_SPECIFIED) 
411               && *input_line_pointer == ',')
412             {
413               if (sectype != BFD_MACH_O_S_SYMBOL_STUBS)
414                 {
415                   as_bad (_("unexpected section size information"));
416                   ignore_rest_of_line ();
417                   return;
418                 }
419
420               input_line_pointer++;
421               sizeof_stub = get_absolute_expression ();
422             }
423           else if ((specified_mask & SECT_ATTR_SPECIFIED) 
424                    && sectype == BFD_MACH_O_S_SYMBOL_STUBS)
425             {
426               as_bad (_("missing sizeof_stub expression"));
427               ignore_rest_of_line ();
428               return;
429             }
430         }
431     }
432
433   new_seg = obj_mach_o_make_or_get_sect (segname, sectname, specified_mask, 
434                                          sectype, secattr, 0 /*align */,
435                                          sizeof_stub);
436   if (new_seg != NULL)
437     {
438       subseg_set (new_seg, 0);
439       demand_empty_rest_of_line ();
440     }
441 }
442
443 /* .zerofill segname, sectname [, symbolname, size [, align]]
444
445    Zerofill switches, temporarily, to a sect of type 'zerofill'.
446
447    If a variable name is given, it defines that in the section.
448    Otherwise it just creates the section if it doesn't exist.  */
449
450 static void
451 obj_mach_o_zerofill (int ignore ATTRIBUTE_UNUSED)
452 {
453   char segname[17];
454   char sectname[17];
455   segT old_seg = now_seg;
456   segT new_seg;
457   symbolS *sym = NULL;
458   unsigned int align = 0;
459   unsigned int specified_mask = 0;
460   offsetT size;
461
462 #ifdef md_flush_pending_output
463   md_flush_pending_output ();
464 #endif
465
466   /* Get the User's segment annd section names.  */
467   if (! obj_mach_o_get_section_names (segname, sectname, 17, 17))
468     return;
469
470   /* Parse variable definition, if present.  */
471   if (*input_line_pointer == ',')
472     {
473       /* Parse symbol, size [.align] 
474          We follow the method of s_common_internal, with the difference
475          that the symbol cannot be a duplicate-common.  */
476       char *name;
477       char c;
478       char *p;
479       expressionS exp;
480   
481       input_line_pointer++; /* Skip ',' */
482       SKIP_WHITESPACE ();
483       name = input_line_pointer;
484       c = get_symbol_end ();
485       /* Just after name is now '\0'.  */
486       p = input_line_pointer;
487       *p = c;
488
489       if (name == p)
490         {
491           as_bad (_("expected symbol name"));
492           ignore_rest_of_line ();
493           goto done;
494         }
495
496       SKIP_WHITESPACE ();  
497       if (*input_line_pointer == ',')
498         input_line_pointer++;
499
500       expression_and_evaluate (&exp);
501       if (exp.X_op != O_constant
502           && exp.X_op != O_absent)
503         {
504             as_bad (_("bad or irreducible absolute expression"));
505           ignore_rest_of_line ();
506           goto done;
507         }
508       else if (exp.X_op == O_absent)
509         {
510           as_bad (_("missing size expression"));
511           ignore_rest_of_line ();
512           goto done;
513         }
514
515       size = exp.X_add_number;
516       size &= ((offsetT) 2 << (stdoutput->arch_info->bits_per_address - 1)) - 1;
517       if (exp.X_add_number != size || !exp.X_unsigned)
518         {
519           as_warn (_("size (%ld) out of range, ignored"),
520                    (long) exp.X_add_number);
521           ignore_rest_of_line ();
522           goto done;
523         }
524
525      *p = 0; /* Make the name into a c string for err messages.  */
526      sym = symbol_find_or_make (name);
527      if (S_IS_DEFINED (sym) || symbol_equated_p (sym))
528         {
529           as_bad (_("symbol `%s' is already defined"), name);
530           *p = c;
531           ignore_rest_of_line ();
532            goto done;
533         }
534
535       size = S_GET_VALUE (sym);
536       if (size == 0)
537         size = exp.X_add_number;
538       else if (size != exp.X_add_number)
539         as_warn (_("size of \"%s\" is already %ld; not changing to %ld"),
540                    name, (long) size, (long) exp.X_add_number);
541
542       *p = c;  /* Restore the termination char.  */
543       
544       SKIP_WHITESPACE ();  
545       if (*input_line_pointer == ',')
546         {
547           align = (unsigned int) parse_align (0);
548           if (align == (unsigned int) -1)
549             {
550               as_warn (_("align value not recognized, using size"));
551               align = size;
552             }
553           if (align > 15)
554             {
555               as_warn (_("Alignment (%lu) too large: 15 assumed."),
556                         (unsigned long)align);
557               align = 15;
558             }
559           specified_mask |= SECT_ALGN_SPECIFIED;
560         }
561     }
562  /* else just a section definition.  */
563
564   specified_mask |= SECT_TYPE_SPECIFIED;
565   new_seg = obj_mach_o_make_or_get_sect (segname, sectname, specified_mask, 
566                                          BFD_MACH_O_S_ZEROFILL,
567                                          BFD_MACH_O_S_ATTR_NONE,
568                                          align, (offsetT) 0 /*stub size*/);
569   if (new_seg == NULL)
570     return;
571
572   /* In case the user specifies the bss section by mach-o name.
573      Create it on demand */
574   if (strcmp (new_seg->name, BSS_SECTION_NAME) == 0
575       && bss_section == NULL)
576     bss_section = new_seg;
577
578   subseg_set (new_seg, 0);
579
580   if (sym != NULL)
581     {
582       char *pfrag;
583
584       if (align)
585         {
586           record_alignment (new_seg, align);
587           frag_align (align, 0, 0);
588         }
589
590       /* Detach from old frag.  */
591       if (S_GET_SEGMENT (sym) == new_seg)
592         symbol_get_frag (sym)->fr_symbol = NULL;
593
594       symbol_set_frag (sym, frag_now);
595       pfrag = frag_var (rs_org, 1, 1, 0, sym, size, NULL);
596       *pfrag = 0;
597
598       S_SET_SEGMENT (sym, new_seg);
599       if (new_seg == bss_section)
600         S_CLEAR_EXTERNAL (sym);
601     }
602
603 done:
604   /* switch back to the section that was current before the .zerofill.  */
605   subseg_set (old_seg, 0);
606 }
607
608 static segT 
609 obj_mach_o_segT_from_bfd_name (const char *nam, int must_succeed)
610 {
611   const mach_o_section_name_xlat *xlat;
612   const char *segn;
613   segT sec;
614
615   /* BFD has tables of flags and default attributes for all the sections that
616      have a 'canonical' name.  */
617   xlat = bfd_mach_o_section_data_for_bfd_name (stdoutput, nam, &segn);
618   if (xlat == NULL)
619     {
620       if (must_succeed)
621         as_fatal (_("BFD is out of sync with GAS, "
622                      "unhandled well-known section type `%s'"), nam);
623       return NULL;
624     }
625
626   sec = bfd_get_section_by_name (stdoutput, nam);
627   if (sec == NULL)
628     {
629       bfd_mach_o_section *msect;
630
631       sec = subseg_force_new (xlat->bfd_name, 0);
632
633       /* Set default type, attributes and alignment.  */
634       msect = bfd_mach_o_get_mach_o_section (sec);
635       msect->flags = xlat->macho_sectype | xlat->macho_secattr;
636       msect->align = xlat->sectalign;
637
638       if ((msect->flags & BFD_MACH_O_SECTION_TYPE_MASK) 
639           == BFD_MACH_O_S_ZEROFILL)
640         seg_info (sec)->bss = 1;
641     }
642
643   return sec;
644 }
645
646 static const char * const known_sections[] =
647 {
648   /*  0 */ NULL,
649   /* __TEXT */
650   /*  1 */ ".const",
651   /*  2 */ ".static_const",
652   /*  3 */ ".cstring",
653   /*  4 */ ".literal4",
654   /*  5 */ ".literal8",
655   /*  6 */ ".literal16",
656   /*  7 */ ".constructor",
657   /*  8 */ ".destructor",
658   /*  9 */ ".eh_frame",
659   /* __DATA */
660   /* 10 */ ".const_data",
661   /* 11 */ ".static_data",
662   /* 12 */ ".mod_init_func",
663   /* 13 */ ".mod_term_func",
664   /* 14 */ ".dyld",
665   /* 15 */ ".cfstring"
666 };
667
668 /* Interface for a known non-optional section directive.  */
669
670 static void
671 obj_mach_o_known_section (int sect_index)
672 {
673   segT section;
674
675 #ifdef md_flush_pending_output
676   md_flush_pending_output ();
677 #endif
678
679   section = obj_mach_o_segT_from_bfd_name (known_sections[sect_index], 1);
680   if (section != NULL)
681     subseg_set (section, 0);
682
683   /* else, we leave the section as it was; there was a fatal error anyway.  */
684 }
685
686 static const char * const objc_sections[] =
687 {
688   /*  0 */ NULL,
689   /*  1 */ ".objc_class",
690   /*  2 */ ".objc_meta_class",
691   /*  3 */ ".objc_cat_cls_meth",
692   /*  4 */ ".objc_cat_inst_meth",
693   /*  5 */ ".objc_protocol",
694   /*  6 */ ".objc_string_object",
695   /*  7 */ ".objc_cls_meth",
696   /*  8 */ ".objc_inst_meth",
697   /*  9 */ ".objc_cls_refs",
698   /* 10 */ ".objc_message_refs",
699   /* 11 */ ".objc_symbols",
700   /* 12 */ ".objc_category",
701   /* 13 */ ".objc_class_vars",
702   /* 14 */ ".objc_instance_vars",
703   /* 15 */ ".objc_module_info",
704   /* 16 */ ".cstring", /* objc_class_names Alias for .cstring */
705   /* 17 */ ".cstring", /* Alias objc_meth_var_types for .cstring */
706   /* 18 */ ".cstring", /* objc_meth_var_names Alias for .cstring */
707   /* 19 */ ".objc_selector_strs",
708   /* 20 */ ".objc_image_info", /* extension.  */
709   /* 21 */ ".objc_selector_fixup", /* extension.  */
710   /* 22 */ ".objc1_class_ext", /* ObjC-1 extension.  */
711   /* 23 */ ".objc1_property_list", /* ObjC-1 extension.  */
712   /* 24 */ ".objc1_protocol_ext" /* ObjC-1 extension.  */
713 };
714
715 /* This currently does the same as known_sections, but kept separate for
716    ease of maintenance.  */
717
718 static void
719 obj_mach_o_objc_section (int sect_index)
720 {
721   segT section;
722   
723 #ifdef md_flush_pending_output
724   md_flush_pending_output ();
725 #endif
726
727   section = obj_mach_o_segT_from_bfd_name (objc_sections[sect_index], 1);
728   if (section != NULL)
729     {
730       obj_mach_o_seen_objc_section = 1; /* We need to ensure that certain
731                                            sections are present and in the
732                                            right order.  */
733       subseg_set (section, 0);
734     }
735
736   /* else, we leave the section as it was; there was a fatal error anyway.  */
737 }
738
739 /* Debug section directives.  */
740
741 static const char * const debug_sections[] =
742 {
743   /*  0 */ NULL,
744   /* __DWARF */
745   /*  1 */ ".debug_frame",
746   /*  2 */ ".debug_info",
747   /*  3 */ ".debug_abbrev",
748   /*  4 */ ".debug_aranges",
749   /*  5 */ ".debug_macinfo",
750   /*  6 */ ".debug_line",
751   /*  7 */ ".debug_loc",
752   /*  8 */ ".debug_pubnames",
753   /*  9 */ ".debug_pubtypes",
754   /* 10 */ ".debug_str",
755   /* 11 */ ".debug_ranges",
756   /* 12 */ ".debug_macro"
757 };
758
759 /* ??? Maybe these should be conditional on gdwarf-*.
760    It`s also likely that we will need to be able to set them from the cfi
761    code.  */
762
763 static void
764 obj_mach_o_debug_section (int sect_index)
765 {
766   segT section;
767
768 #ifdef md_flush_pending_output
769   md_flush_pending_output ();
770 #endif
771
772   section = obj_mach_o_segT_from_bfd_name (debug_sections[sect_index], 1);
773   if (section != NULL)
774     subseg_set (section, 0);
775
776   /* else, we leave the section as it was; there was a fatal error anyway.  */
777 }
778
779 /* This could be moved to the tc-xx files, but there is so little dependency
780    there, that the code might as well be shared.  */
781
782 struct opt_tgt_sect 
783 {
784  const char *name;
785  unsigned x86_val;
786  unsigned ppc_val;
787 };
788
789 /* The extensions here are for specific sections that are generated by GCC
790    and Darwin system tools, but don't have directives in the `system as'.  */
791
792 static const struct opt_tgt_sect tgt_sections[] =
793 {
794   /*  0 */ { NULL, 0, 0},
795   /*  1 */ { ".lazy_symbol_pointer", 0, 0},
796   /*  2 */ { ".lazy_symbol_pointer2", 0, 0}, /* X86 - extension */
797   /*  3 */ { ".lazy_symbol_pointer3", 0, 0}, /* X86 - extension */
798   /*  4 */ { ".non_lazy_symbol_pointer", 0, 0},
799   /*  5 */ { ".non_lazy_symbol_pointer_x86", 0, 0}, /* X86 - extension */
800   /*  6 */ { ".symbol_stub", 16, 20},
801   /*  7 */ { ".symbol_stub1", 0, 16}, /* PPC - extension */
802   /*  8 */ { ".picsymbol_stub", 26, 36},
803   /*  9 */ { ".picsymbol_stub1", 0, 32}, /* PPC - extension */
804   /* 10 */ { ".picsymbol_stub2", 25, 0}, /* X86 - extension */
805   /* 11 */ { ".picsymbol_stub3", 5, 0}, /* X86 - extension  */
806 };
807
808 /* Interface for an optional section directive.  */
809
810 static void
811 obj_mach_o_opt_tgt_section (int sect_index)
812 {
813   const struct opt_tgt_sect *tgtsct = &tgt_sections[sect_index];
814   segT section;
815
816 #ifdef md_flush_pending_output
817   md_flush_pending_output ();
818 #endif
819
820   section = obj_mach_o_segT_from_bfd_name (tgtsct->name, 0);
821   if (section == NULL)
822     {
823       as_bad (_("%s is not used for the selected target"), tgtsct->name);
824       /* Leave the section as it is.  */
825     }
826   else
827     {
828       bfd_mach_o_section *mo_sec = bfd_mach_o_get_mach_o_section (section);
829       subseg_set (section, 0);
830 #if defined (TC_I386)
831       mo_sec->reserved2 = tgtsct->x86_val;
832 #elif defined (TC_PPC)
833       mo_sec->reserved2 = tgtsct->ppc_val;
834 #else
835       mo_sec->reserved2 = 0;
836 #endif
837     }
838 }
839
840 /* We don't necessarily have the three 'base' sections on mach-o.
841    Normally, we would start up with only the 'text' section defined.
842    However, even that can be suppressed with (TODO) c/l option "-n".
843    Thus, we have to be able to create all three sections on-demand.  */
844
845 static void
846 obj_mach_o_base_section (int sect_index)
847 {
848   segT section;
849
850 #ifdef md_flush_pending_output
851   md_flush_pending_output ();
852 #endif
853
854   /* We don't support numeric (or any other) qualifications on the
855      well-known section shorthands.  */
856   demand_empty_rest_of_line ();
857
858   switch (sect_index)
859     {
860       /* Handle the three sections that are globally known within GAS.
861          For Mach-O, these are created on demand rather than at startup.  */
862       case 1:
863         if (text_section == NULL)
864           text_section = obj_mach_o_segT_from_bfd_name (TEXT_SECTION_NAME, 1);
865         if (obj_mach_o_is_static)
866           {
867             bfd_mach_o_section *mo_sec
868                 = bfd_mach_o_get_mach_o_section (text_section);
869             mo_sec->flags &= ~BFD_MACH_O_S_ATTR_PURE_INSTRUCTIONS;
870           }
871         section = text_section;
872         break;
873       case 2:
874         if (data_section == NULL)
875           data_section = obj_mach_o_segT_from_bfd_name (DATA_SECTION_NAME, 1);
876         section = data_section;
877         break;
878       case 3:
879         /* ??? maybe this achieves very little, as an addition.  */
880         if (bss_section == NULL)
881           {
882             bss_section = obj_mach_o_segT_from_bfd_name (BSS_SECTION_NAME, 1);
883             seg_info (bss_section)->bss = 1;
884           }
885         section = bss_section;
886         break;
887       default:
888         as_fatal (_("internal error: base section index out of range"));
889         return;
890         break;
891     }
892   subseg_set (section, 0);
893 }
894
895 /* This finishes off parsing a .comm or .lcomm statement, which both can have
896    an (optional) alignment field.  It also allows us to create the bss section
897    on demand.  */
898
899 static symbolS *
900 obj_mach_o_common_parse (int is_local, symbolS *symbolP,
901                          addressT size)
902 {
903   addressT align = 0;
904
905   SKIP_WHITESPACE ();  
906
907   /* Both comm and lcomm take an optional alignment, as a power
908      of two between 1 and 15.  */
909   if (*input_line_pointer == ',')
910     {
911       /* We expect a power of 2.  */
912       align = parse_align (0);
913       if (align == (addressT) -1)
914         return NULL;
915       if (align > 15)
916         {
917           as_warn (_("Alignment (%lu) too large: 15 assumed."),
918                   (unsigned long)align);
919           align = 15;
920         }
921     }
922
923   if (is_local)
924     {
925       /* Create the BSS section on demand.  */
926       if (bss_section == NULL)
927         {
928           bss_section = obj_mach_o_segT_from_bfd_name (BSS_SECTION_NAME, 1);
929           seg_info (bss_section)->bss = 1;        
930         }
931       bss_alloc (symbolP, size, align);
932       S_CLEAR_EXTERNAL (symbolP);
933     }
934   else
935     {
936       S_SET_VALUE (symbolP, size);
937       S_SET_ALIGN (symbolP, align);
938       S_SET_EXTERNAL (symbolP);
939       S_SET_SEGMENT (symbolP, bfd_com_section_ptr);
940     }
941
942   symbol_get_bfdsym (symbolP)->flags |= BSF_OBJECT;
943
944   return symbolP;
945 }
946
947 static void
948 obj_mach_o_comm (int is_local)
949 {
950   s_comm_internal (is_local, obj_mach_o_common_parse);
951 }
952
953 /* Set properties that apply to the whole file.  At present, the only
954    one defined, is subsections_via_symbols.  */
955
956 typedef enum obj_mach_o_file_properties {
957   OBJ_MACH_O_FILE_PROP_NONE = 0,
958   OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS,
959   OBJ_MACH_O_FILE_PROP_MAX
960 } obj_mach_o_file_properties;
961
962 static void 
963 obj_mach_o_fileprop (int prop)
964 {
965   if (prop < 0 || prop >= OBJ_MACH_O_FILE_PROP_MAX)
966     as_fatal (_("internal error: bad file property ID %d"), prop);
967     
968   switch ((obj_mach_o_file_properties) prop)
969     {
970       case OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS:
971         obj_mach_o_subsections_by_symbols = 1;
972         if (!bfd_set_private_flags (stdoutput, 
973                                     BFD_MACH_O_MH_SUBSECTIONS_VIA_SYMBOLS))
974           as_bad (_("failed to set subsections by symbols"));
975         demand_empty_rest_of_line ();
976         break;
977       default:
978         break;
979     }
980 }
981
982 /* Dummy function to allow test-code to work while we are working
983    on things.  */
984
985 static void
986 obj_mach_o_placeholder (int arg ATTRIBUTE_UNUSED)
987 {
988   ignore_rest_of_line ();
989 }
990
991 const pseudo_typeS mach_o_pseudo_table[] =
992 {
993   /* Section directives.  */
994   { "comm", obj_mach_o_comm, 0 },
995   { "lcomm", obj_mach_o_comm, 1 },
996
997   { "text", obj_mach_o_base_section, 1},
998   { "data", obj_mach_o_base_section, 2},
999   { "bss", obj_mach_o_base_section, 3},   /* extension */
1000
1001   { "const", obj_mach_o_known_section, 1},
1002   { "static_const", obj_mach_o_known_section, 2},
1003   { "cstring", obj_mach_o_known_section, 3},
1004   { "literal4", obj_mach_o_known_section, 4},
1005   { "literal8", obj_mach_o_known_section, 5},
1006   { "literal16", obj_mach_o_known_section, 6},
1007   { "constructor", obj_mach_o_known_section, 7},
1008   { "destructor", obj_mach_o_known_section, 8},
1009   { "eh_frame", obj_mach_o_known_section, 9},
1010
1011   { "const_data", obj_mach_o_known_section, 10},
1012   { "static_data", obj_mach_o_known_section, 11},
1013   { "mod_init_func", obj_mach_o_known_section, 12},
1014   { "mod_term_func", obj_mach_o_known_section, 13},
1015   { "dyld", obj_mach_o_known_section, 14},
1016   { "cfstring", obj_mach_o_known_section, 15},
1017
1018   { "objc_class", obj_mach_o_objc_section, 1},
1019   { "objc_meta_class", obj_mach_o_objc_section, 2},
1020   { "objc_cat_cls_meth", obj_mach_o_objc_section, 3},
1021   { "objc_cat_inst_meth", obj_mach_o_objc_section, 4},
1022   { "objc_protocol", obj_mach_o_objc_section, 5},
1023   { "objc_string_object", obj_mach_o_objc_section, 6},
1024   { "objc_cls_meth", obj_mach_o_objc_section, 7},
1025   { "objc_inst_meth", obj_mach_o_objc_section, 8},
1026   { "objc_cls_refs", obj_mach_o_objc_section, 9},
1027   { "objc_message_refs", obj_mach_o_objc_section, 10},
1028   { "objc_symbols", obj_mach_o_objc_section, 11},
1029   { "objc_category", obj_mach_o_objc_section, 12},
1030   { "objc_class_vars", obj_mach_o_objc_section, 13},
1031   { "objc_instance_vars", obj_mach_o_objc_section, 14},
1032   { "objc_module_info", obj_mach_o_objc_section, 15},
1033   { "objc_class_names", obj_mach_o_objc_section, 16}, /* Alias for .cstring */
1034   { "objc_meth_var_types", obj_mach_o_objc_section, 17}, /* Alias for .cstring */
1035   { "objc_meth_var_names", obj_mach_o_objc_section, 18}, /* Alias for .cstring */
1036   { "objc_selector_strs", obj_mach_o_objc_section, 19},
1037   { "objc_image_info", obj_mach_o_objc_section, 20}, /* extension.  */
1038   { "objc_selector_fixup", obj_mach_o_objc_section, 21}, /* extension.  */
1039   { "objc1_class_ext", obj_mach_o_objc_section, 22}, /* ObjC-1 extension.  */
1040   { "objc1_property_list", obj_mach_o_objc_section, 23}, /* ObjC-1 extension.  */
1041   { "objc1_protocol_ext", obj_mach_o_objc_section, 24}, /* ObjC-1 extension.  */
1042
1043   { "debug_frame", obj_mach_o_debug_section, 1}, /* extension.  */
1044   { "debug_info", obj_mach_o_debug_section, 2}, /* extension.  */
1045   { "debug_abbrev", obj_mach_o_debug_section, 3}, /* extension.  */
1046   { "debug_aranges", obj_mach_o_debug_section, 4}, /* extension.  */
1047   { "debug_macinfo", obj_mach_o_debug_section, 5}, /* extension.  */
1048   { "debug_line", obj_mach_o_debug_section, 6}, /* extension.  */
1049   { "debug_loc", obj_mach_o_debug_section, 7}, /* extension.  */
1050   { "debug_pubnames", obj_mach_o_debug_section, 8}, /* extension.  */
1051   { "debug_pubtypes", obj_mach_o_debug_section, 9}, /* extension.  */
1052   { "debug_str", obj_mach_o_debug_section, 10}, /* extension.  */
1053   { "debug_ranges", obj_mach_o_debug_section, 11}, /* extension.  */
1054   { "debug_macro", obj_mach_o_debug_section, 12}, /* extension.  */
1055   
1056   { "lazy_symbol_pointer", obj_mach_o_opt_tgt_section, 1},
1057   { "lazy_symbol_pointer2", obj_mach_o_opt_tgt_section, 2}, /* extension.  */
1058   { "lazy_symbol_pointer3", obj_mach_o_opt_tgt_section, 3}, /* extension.  */
1059   { "non_lazy_symbol_pointer", obj_mach_o_opt_tgt_section, 4},
1060   { "non_lazy_symbol_pointer_x86", obj_mach_o_opt_tgt_section, 5}, /* extension.  */
1061   { "symbol_stub", obj_mach_o_opt_tgt_section, 6},
1062   { "symbol_stub1", obj_mach_o_opt_tgt_section, 7}, /* extension.  */
1063   { "picsymbol_stub", obj_mach_o_opt_tgt_section, 8}, /* extension.  */
1064   { "picsymbol_stub1", obj_mach_o_opt_tgt_section, 9}, /* extension.  */
1065   { "picsymbol_stub2", obj_mach_o_opt_tgt_section, 4}, /* extension.  */
1066   { "picsymbol_stub3", obj_mach_o_opt_tgt_section, 4}, /* extension.  */
1067
1068   { "section", obj_mach_o_section, 0},
1069   { "zerofill", obj_mach_o_zerofill, 0},
1070
1071   /* Symbol-related.  */
1072   { "indirect_symbol", obj_mach_o_placeholder, 0},
1073   { "weak_definition", obj_mach_o_placeholder, 0},
1074   { "private_extern", obj_mach_o_placeholder, 0},
1075   { "weak", obj_mach_o_weak, 0},   /* extension */
1076
1077   /* File flags.  */
1078   { "subsections_via_symbols", obj_mach_o_fileprop, 
1079                                OBJ_MACH_O_FILE_PROP_SUBSECTS_VIA_SYMS},
1080
1081   {NULL, NULL, 0}
1082 };
1083
1084 /* Support stabs for mach-o.  */
1085
1086 void
1087 obj_mach_o_process_stab (int what, const char *string,
1088                          int type, int other, int desc)
1089 {
1090   symbolS *symbolP;
1091   bfd_mach_o_asymbol *s;
1092
1093   switch (what)
1094     {
1095       case 'd':
1096         symbolP = symbol_new ("", now_seg, frag_now_fix (), frag_now);
1097         /* Special stabd NULL name indicator.  */
1098         S_SET_NAME (symbolP, NULL);
1099         break;
1100
1101       case 'n':
1102       case 's':
1103         symbolP = symbol_new (string, undefined_section, (valueT) 0,
1104                               &zero_address_frag);
1105         pseudo_set (symbolP);
1106         break;
1107
1108       default:
1109         as_bad(_("unrecognized stab type '%c'"), (char)what);
1110         abort ();
1111         break;
1112     }
1113
1114   s = (bfd_mach_o_asymbol *) symbol_get_bfdsym (symbolP);
1115   s->n_type = type;
1116   s->n_desc = desc;
1117   /* For stabd, this will eventually get overwritten by the section number.  */
1118   s->n_sect = other;
1119
1120   /* It's a debug symbol.  */
1121   s->symbol.flags |= BSF_DEBUGGING;
1122 }