Home | History | Annotate | Line # | Download | only in bfd
format.c revision 1.1.1.12
      1 /* Generic BFD support for file formats.
      2    Copyright (C) 1990-2025 Free Software Foundation, Inc.
      3    Written by Cygnus Support.
      4 
      5    This file is part of BFD, the Binary File Descriptor library.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program; if not, write to the Free Software
     19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
     20    MA 02110-1301, USA.  */
     21 
     22 
     23 /*
     24 SECTION
     25 	File formats
     26 
     27 	A format is a BFD concept of high level file contents type. The
     28 	formats supported by BFD are:
     29 
     30 	o <<bfd_object>>
     31 
     32 	The BFD may contain data, symbols, relocations and debug info.
     33 
     34 	o <<bfd_archive>>
     35 
     36 	The BFD contains other BFDs and an optional index.
     37 
     38 	o <<bfd_core>>
     39 
     40 	The BFD contains the result of an executable core dump.
     41 
     42 SUBSECTION
     43 	File format functions
     44 */
     45 
     46 #include "sysdep.h"
     47 #include "bfd.h"
     48 #include "libbfd.h"
     49 #include "plugin.h"
     50 
     51 /* IMPORT from targets.c.  */
     52 extern const size_t _bfd_target_vector_entries;
     53 
     54 /*
     55 FUNCTION
     56 	bfd_check_format
     57 
     58 SYNOPSIS
     59 	bool bfd_check_format (bfd *abfd, bfd_format format);
     60 
     61 DESCRIPTION
     62 	Verify if the file attached to the BFD @var{abfd} is compatible
     63 	with the format @var{format} (i.e., one of <<bfd_object>>,
     64 	<<bfd_archive>> or <<bfd_core>>).
     65 
     66 	If the BFD has been set to a specific target before the
     67 	call, only the named target and format combination is
     68 	checked. If the target has not been set, or has been set to
     69 	<<default>>, then all the known target backends is
     70 	interrogated to determine a match.  If the default target
     71 	matches, it is used.  If not, exactly one target must recognize
     72 	the file, or an error results.
     73 
     74 	The function returns <<TRUE>> on success, otherwise <<FALSE>>
     75 	with one of the following error codes:
     76 
     77 	o <<bfd_error_invalid_operation>> -
     78 	if <<format>> is not one of <<bfd_object>>, <<bfd_archive>> or
     79 	<<bfd_core>>.
     80 
     81 	o <<bfd_error_system_call>> -
     82 	if an error occured during a read - even some file mismatches
     83 	can cause bfd_error_system_calls.
     84 
     85 	o <<file_not_recognised>> -
     86 	none of the backends recognised the file format.
     87 
     88 	o <<bfd_error_file_ambiguously_recognized>> -
     89 	more than one backend recognised the file format.
     90 
     91 	When calling bfd_check_format (or bfd_check_format_matches),
     92 	any underlying file descriptor will be kept open for the
     93 	duration of the call.  This is done to avoid races when
     94 	another thread calls bfd_cache_close_all.  In this scenario,
     95 	the thread calling bfd_check_format must call bfd_cache_close
     96 	itself.
     97 */
     98 
     99 bool
    100 bfd_check_format (bfd *abfd, bfd_format format)
    101 {
    102   return bfd_check_format_matches (abfd, format, NULL);
    103 }
    104 
    105 struct bfd_preserve
    106 {
    107   void *marker;
    108   void *tdata;
    109   flagword flags;
    110   const struct bfd_iovec *iovec;
    111   void *iostream;
    112   const struct bfd_arch_info *arch_info;
    113   const struct bfd_build_id *build_id;
    114   bfd_cleanup cleanup;
    115   struct bfd_section *sections;
    116   struct bfd_section *section_last;
    117   unsigned int section_count;
    118   unsigned int section_id;
    119   unsigned int symcount;
    120   bool read_only;
    121   bfd_vma start_address;
    122   struct bfd_hash_table section_htab;
    123 };
    124 
    125 /* When testing an object for compatibility with a particular target
    126    back-end, the back-end object_p function needs to set up certain
    127    fields in the bfd on successfully recognizing the object.  This
    128    typically happens in a piecemeal fashion, with failures possible at
    129    many points.  On failure, the bfd is supposed to be restored to its
    130    initial state, which is virtually impossible.  However, restoring a
    131    subset of the bfd state works in practice.  This function stores
    132    the subset.  */
    133 
    134 static bool
    135 bfd_preserve_save (bfd *abfd, struct bfd_preserve *preserve,
    136 		   bfd_cleanup cleanup)
    137 {
    138   preserve->tdata = abfd->tdata.any;
    139   preserve->arch_info = abfd->arch_info;
    140   preserve->flags = abfd->flags;
    141   preserve->iovec = abfd->iovec;
    142   preserve->iostream = abfd->iostream;
    143   preserve->sections = abfd->sections;
    144   preserve->section_last = abfd->section_last;
    145   preserve->section_count = abfd->section_count;
    146   preserve->section_id = _bfd_section_id;
    147   preserve->symcount = abfd->symcount;
    148   preserve->read_only = abfd->read_only;
    149   preserve->start_address = abfd->start_address;
    150   preserve->section_htab = abfd->section_htab;
    151   preserve->marker = bfd_alloc (abfd, 1);
    152   preserve->build_id = abfd->build_id;
    153   preserve->cleanup = cleanup;
    154   if (preserve->marker == NULL)
    155     return false;
    156 
    157   return bfd_hash_table_init (&abfd->section_htab, bfd_section_hash_newfunc,
    158 			      sizeof (struct section_hash_entry));
    159 }
    160 
    161 /* A back-end object_p function may flip a bfd from file backed to
    162    in-memory, eg. pe_ILF_object_p.  In that case to restore the
    163    original IO state we need to reopen the file.  Conversely, if we
    164    are restoring a previously matched pe ILF format and have been
    165    checking further target matches using file IO then we need to close
    166    the file and detach the bfd from the cache lru list.  */
    167 
    168 static void
    169 io_reinit (bfd *abfd, struct bfd_preserve *preserve)
    170 {
    171   if (abfd->iovec != preserve->iovec)
    172     {
    173       /* Handle file backed to in-memory transition.  bfd_cache_close
    174 	 won't do anything unless abfd->iovec is the cache_iovec.
    175 	 Don't be tempted to call iovec->bclose here.  We don't want
    176 	 to call memory_bclose, which would free the bim.  The bim
    177 	 must be kept if bfd_check_format_matches is going to decide
    178 	 later that the PE format needing it is in fact the correct
    179 	 target match.  */
    180       bfd_cache_close (abfd);
    181       abfd->iovec = preserve->iovec;
    182       abfd->iostream = preserve->iostream;
    183 
    184       /* Handle in-memory to file backed transition.  */
    185       if ((abfd->flags & BFD_CLOSED_BY_CACHE) != 0
    186 	  && (abfd->flags & BFD_IN_MEMORY) != 0
    187 	  && (preserve->flags & BFD_CLOSED_BY_CACHE) == 0
    188 	  && (preserve->flags & BFD_IN_MEMORY) == 0)
    189 	bfd_open_file (abfd);
    190     }
    191   abfd->flags = preserve->flags;
    192 }
    193 
    194 /* Clear out a subset of BFD state.  */
    195 
    196 static void
    197 bfd_reinit (bfd *abfd, unsigned int section_id,
    198 	    struct bfd_preserve *preserve, bfd_cleanup cleanup)
    199 {
    200   _bfd_section_id = section_id;
    201   if (cleanup)
    202     cleanup (abfd);
    203   abfd->tdata.any = NULL;
    204   abfd->arch_info = &bfd_default_arch_struct;
    205   io_reinit (abfd, preserve);
    206   abfd->symcount = 0;
    207   abfd->read_only = 0;
    208   abfd->start_address = 0;
    209   abfd->build_id = NULL;
    210   bfd_section_list_clear (abfd);
    211 }
    212 
    213 /* Restores bfd state saved by bfd_preserve_save.  */
    214 
    215 static bfd_cleanup
    216 bfd_preserve_restore (bfd *abfd, struct bfd_preserve *preserve)
    217 {
    218   bfd_hash_table_free (&abfd->section_htab);
    219 
    220   abfd->tdata.any = preserve->tdata;
    221   abfd->arch_info = preserve->arch_info;
    222   io_reinit (abfd, preserve);
    223   abfd->section_htab = preserve->section_htab;
    224   abfd->sections = preserve->sections;
    225   abfd->section_last = preserve->section_last;
    226   abfd->section_count = preserve->section_count;
    227   _bfd_section_id = preserve->section_id;
    228   abfd->symcount = preserve->symcount;
    229   abfd->read_only = preserve->read_only;
    230   abfd->start_address = preserve->start_address;
    231   abfd->build_id = preserve->build_id;
    232 
    233   /* bfd_release frees all memory more recently bfd_alloc'd than
    234      its arg, as well as its arg.  */
    235   bfd_release (abfd, preserve->marker);
    236   preserve->marker = NULL;
    237   return preserve->cleanup;
    238 }
    239 
    240 /* Called when the bfd state saved by bfd_preserve_save is no longer
    241    needed.  */
    242 
    243 static void
    244 bfd_preserve_finish (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_preserve *preserve)
    245 {
    246   if (preserve->cleanup)
    247     {
    248       /* Run the cleanup, assuming that all it will need is the
    249 	 tdata at the time the cleanup was returned.  */
    250       void *tdata = abfd->tdata.any;
    251       abfd->tdata.any = preserve->tdata;
    252       preserve->cleanup (abfd);
    253       abfd->tdata.any = tdata;
    254     }
    255   /* It would be nice to be able to free more memory here, eg. old
    256      tdata, but that's not possible since these blocks are sitting
    257      inside bfd_alloc'd memory.  The section hash is on a separate
    258      objalloc.  */
    259   bfd_hash_table_free (&preserve->section_htab);
    260   preserve->marker = NULL;
    261 }
    262 
    263 static void
    264 print_warnmsg (struct per_xvec_message **list)
    265 {
    266   for (struct per_xvec_message *warn = *list; warn; warn = warn->next)
    267     _bfd_error_handler ("%s", warn->message);
    268 }
    269 
    270 static void
    271 clear_warnmsg (struct per_xvec_message **list)
    272 {
    273   struct per_xvec_message *warn = *list;
    274   while (warn)
    275     {
    276       struct per_xvec_message *next = warn->next;
    277       free (warn);
    278       warn = next;
    279     }
    280   *list = NULL;
    281 }
    282 
    283 /* Free all the storage in LIST.  Note that the first element of LIST
    284    is special and is assumed to be stack-allocated.  TARG is used for
    285    re-issuing warning messages.  If TARG is PER_XVEC_NO_TARGET, then
    286    it acts like a sort of wildcard -- messages are reissued if all
    287    targets with messages have identical messages.  One copy of the
    288    messages are then reissued.  If TARG is anything else, then only
    289    messages associated with TARG are emitted.  */
    290 
    291 static void
    292 print_and_clear_messages (struct per_xvec_messages *list,
    293 			  const bfd_target *targ)
    294 {
    295   struct per_xvec_messages *iter;
    296 
    297   if (targ == PER_XVEC_NO_TARGET)
    298     {
    299       iter = list->next;
    300       while (iter != NULL)
    301 	{
    302 	  struct per_xvec_message *msg1 = list->messages;
    303 	  struct per_xvec_message *msg2 = iter->messages;
    304 	  do
    305 	    {
    306 	      if (strcmp (msg1->message, msg2->message))
    307 		break;
    308 	      msg1 = msg1->next;
    309 	      msg2 = msg2->next;
    310 	    } while (msg1 && msg2);
    311 	  if (msg1 || msg2)
    312 	    break;
    313 	  iter = iter->next;
    314 	}
    315       if (iter == NULL)
    316 	targ = list->targ;
    317     }
    318 
    319   iter = list;
    320   while (iter != NULL)
    321     {
    322       struct per_xvec_messages *next = iter->next;
    323 
    324       if (iter->targ == targ)
    325 	print_warnmsg (&iter->messages);
    326       clear_warnmsg (&iter->messages);
    327       if (iter != list)
    328 	free (iter);
    329       iter = next;
    330     }
    331 
    332   /* Don't retain a pointer to free'd memory.  */
    333   list->next = NULL;
    334 }
    335 
    336 /* Discard all messages associated with TARG in LIST.  Unlike
    337    print_and_clear_messages, PER_XVEC_NO_TARGET is not valid for TARG.  */
    338 
    339 static void
    340 clear_messages (struct per_xvec_messages *list,
    341 		const bfd_target *targ)
    342 {
    343   struct per_xvec_messages *iter;
    344 
    345   for (iter = list; iter != NULL; iter = iter->next)
    346     {
    347       if (iter->targ == targ)
    348 	clear_warnmsg (&iter->messages);
    349     }
    350 }
    351 
    352 /* This a copy of lto_section defined in GCC (lto-streamer.h).  */
    353 
    354 struct lto_section
    355 {
    356   int16_t major_version;
    357   int16_t minor_version;
    358   unsigned char slim_object;
    359 
    360   /* Flags is a private field that is not defined publicly.  */
    361   uint16_t flags;
    362 };
    363 
    364 /* Set lto_type in ABFD.  */
    365 
    366 static void
    367 bfd_set_lto_type (bfd *abfd)
    368 {
    369   if (abfd->format == bfd_object
    370       && abfd->lto_type == lto_non_object
    371       && (abfd->flags
    372 	  & (DYNAMIC
    373 	     | (bfd_get_flavour (abfd) == bfd_target_elf_flavour
    374 		? EXEC_P : 0))) == 0)
    375     {
    376       asection *sec = abfd->sections;
    377       enum bfd_lto_object_type type = lto_non_ir_object;
    378       if (sec == NULL)
    379 	{
    380 	  /* If there are no sections, check for slim LLVM IR object whose
    381 	     first 4 bytes are: 'B', 'C', 0xc0, 0xde.  */
    382 	  bfd_byte llvm_ir_magic[4];
    383 	  if (bfd_seek (abfd, 0, SEEK_SET) == 0
    384 	      && bfd_read (llvm_ir_magic, 4, abfd) == 4
    385 	      && llvm_ir_magic[0] == 'B'
    386 	      && llvm_ir_magic[1] == 'C'
    387 	      && llvm_ir_magic[2] == 0xc0
    388 	      && llvm_ir_magic[3] == 0xde)
    389 	    type = lto_slim_ir_object;
    390 	}
    391       else
    392 	{
    393 	  struct lto_section lsection = { 0, 0, 0, 0 };
    394 	  /* GCC uses .gnu.lto_.lto.<some_hash> as a LTO bytecode
    395 	     information section.  */
    396 	  for (; sec != NULL; sec = sec->next)
    397 	    if (strcmp (sec->name, GNU_OBJECT_ONLY_SECTION_NAME) == 0)
    398 	      {
    399 		type = lto_mixed_object;
    400 		abfd->object_only_section = sec;
    401 		break;
    402 	      }
    403 	    else if (strcmp (sec->name, ".llvm.lto") == 0)
    404 	      {
    405 		type = lto_fat_ir_object;
    406 		break;
    407 	      }
    408 	    else if (lsection.major_version == 0
    409 		     && startswith (sec->name, ".gnu.lto_.lto.")
    410 		     && bfd_get_section_contents (abfd, sec, &lsection, 0,
    411 						  sizeof (struct lto_section)))
    412 	      {
    413 		if (lsection.slim_object)
    414 		  type = lto_slim_ir_object;
    415 		else
    416 		  type = lto_fat_ir_object;
    417 	  }
    418 	}
    419 
    420       abfd->lto_type = type;
    421     }
    422 }
    423 
    424 /*
    425 FUNCTION
    426 	bfd_check_format_matches
    427 
    428 SYNOPSIS
    429 	bool bfd_check_format_matches
    430 	  (bfd *abfd, bfd_format format, char ***matching);
    431 
    432 DESCRIPTION
    433 	Like <<bfd_check_format>>, except when it returns FALSE with
    434 	<<bfd_errno>> set to <<bfd_error_file_ambiguously_recognized>>.
    435 	In that case, if @var{matching} is not NULL, it will be filled
    436 	in with a NULL-terminated list of the names of the formats
    437 	that matched, allocated with <<malloc>>.
    438 	Then the user may choose a format and try again.
    439 
    440 	When done with the list that @var{matching} points to, the caller
    441 	should free it.
    442 */
    443 
    444 bool
    445 bfd_check_format_matches (bfd *abfd, bfd_format format, char ***matching)
    446 {
    447   extern const bfd_target binary_vec;
    448   const bfd_target * const *target;
    449   const bfd_target **matching_vector = NULL;
    450   const bfd_target *save_targ, *right_targ, *ar_right_targ, *match_targ;
    451   const bfd_target *fail_targ;
    452   int match_count, best_count, best_match;
    453   int ar_match_index;
    454   unsigned int initial_section_id = _bfd_section_id;
    455   struct bfd_preserve preserve, preserve_match;
    456   bfd_cleanup cleanup = NULL;
    457   struct per_xvec_messages messages = { abfd, PER_XVEC_NO_TARGET, NULL, NULL };
    458   struct per_xvec_messages *orig_messages;
    459   bool old_in_format_matches;
    460 
    461   if (matching != NULL)
    462     *matching = NULL;
    463 
    464   if (!bfd_read_p (abfd)
    465       || (unsigned int) abfd->format >= (unsigned int) bfd_type_end)
    466     {
    467       bfd_set_error (bfd_error_invalid_operation);
    468       return false;
    469     }
    470 
    471   if (abfd->format != bfd_unknown)
    472     return abfd->format == format;
    473 
    474   if (matching != NULL || *bfd_associated_vector != NULL)
    475     {
    476       size_t amt;
    477 
    478       amt = sizeof (*matching_vector) * 2 * _bfd_target_vector_entries;
    479       matching_vector = (const bfd_target **) bfd_malloc (amt);
    480       if (!matching_vector)
    481 	return false;
    482     }
    483 
    484   /* Avoid clashes with bfd_cache_close_all running in another
    485      thread.  */
    486   if (!bfd_cache_set_uncloseable (abfd, true, &old_in_format_matches))
    487     {
    488       free (matching_vector);
    489       return false;
    490     }
    491 
    492   /* Locking is required here in order to manage _bfd_section_id.  */
    493   if (!bfd_lock ())
    494     {
    495       bfd_cache_set_uncloseable (abfd, old_in_format_matches, NULL);
    496       free (matching_vector);
    497       return false;
    498     }
    499 
    500   /* Presume the answer is yes.  */
    501   abfd->format = format;
    502   save_targ = abfd->xvec;
    503 
    504   /* Don't report errors on recursive calls checking the first element
    505      of an archive.  */
    506   orig_messages = _bfd_set_error_handler_caching (&messages);
    507 
    508   preserve_match.marker = NULL;
    509   if (!bfd_preserve_save (abfd, &preserve, NULL))
    510     goto err_ret;
    511 
    512   /* First try matching the plugin target if appropriate.  Next try
    513      the current target.  The current target may have been set due to
    514      a user option, or due to the linker trying optimistically to load
    515      input files for the same target as the output.  Either will
    516      have target_defaulted false.  Failing that, bfd_find_target will
    517      have chosen a default target, and target_defaulted will be true.  */
    518   fail_targ = NULL;
    519   if (bfd_plugin_enabled ()
    520       && abfd->format == bfd_object
    521       && abfd->target_defaulted
    522       && !abfd->is_linker_input
    523       && abfd->plugin_format != bfd_plugin_no)
    524     {
    525       if (bfd_seek (abfd, 0, SEEK_SET) != 0)
    526 	goto err_ret;
    527 
    528       BFD_ASSERT (save_targ != bfd_plugin_vec ());
    529       abfd->xvec = bfd_plugin_vec ();
    530       bfd_set_error (bfd_error_no_error);
    531       cleanup = BFD_SEND_FMT (abfd, _bfd_check_format, (abfd));
    532       if (cleanup)
    533 	goto ok_ret;
    534 
    535       bfd_reinit (abfd, initial_section_id, &preserve, cleanup);
    536       bfd_release (abfd, preserve.marker);
    537       preserve.marker = bfd_alloc (abfd, 1);
    538       abfd->xvec = save_targ;
    539     }
    540 
    541   /* bfd_plugin_no excluding the plugin target is an optimisation.
    542      The test can be removed if desired.  */
    543   if (!(abfd->plugin_format == bfd_plugin_no
    544 	&& bfd_plugin_target_p (save_targ)))
    545     {
    546       if (bfd_seek (abfd, 0, SEEK_SET) != 0)
    547 	goto err_ret;
    548 
    549       bfd_set_error (bfd_error_no_error);
    550       cleanup = BFD_SEND_FMT (abfd, _bfd_check_format, (abfd));
    551       if (cleanup)
    552 	{
    553 	  if (abfd->format != bfd_archive
    554 	      /* An archive with object files matching the archive
    555 		 target is OK.  Other archives should be further
    556 		 tested.  */
    557 	      || (bfd_has_map (abfd)
    558 		  && bfd_get_error () != bfd_error_wrong_object_format)
    559 	      /* Empty archives can match the current target.
    560 		 Attempting to read the armap will result in a file
    561 		 truncated error.  */
    562 	      || (!bfd_has_map (abfd)
    563 		  && bfd_get_error () == bfd_error_file_truncated))
    564 	    goto ok_ret;
    565 	}
    566       else
    567 	{
    568 	  if (!abfd->target_defaulted && !abfd->is_linker_input)
    569 	    goto err_unrecog;
    570 	  fail_targ = save_targ;
    571 	}
    572     }
    573 
    574   /* Check all targets in the hope that one will be recognized.  */
    575   right_targ = NULL;
    576   ar_right_targ = NULL;
    577   match_targ = NULL;
    578   best_match = 256;
    579   best_count = 0;
    580   match_count = 0;
    581   ar_match_index = _bfd_target_vector_entries;
    582 
    583   for (target = bfd_target_vector; *target != NULL; target++)
    584     {
    585       void **high_water;
    586 
    587       /* The binary target matches anything, so don't return it when
    588 	 searching.  Also, don't check the current target twice when
    589 	 it has failed already.
    590 	 Don't match the plugin target during linking if we have
    591 	 another alternative since we want to properly set the input
    592 	 format before allowing a plugin to claim the file.
    593 	 Also as an optimisation don't match the plugin target when
    594 	 abfd->plugin_format is set to bfd_plugin_no.  (This occurs
    595 	 when LTO sections have been stripped or when we have a
    596 	 recursive call here from the plugin object_p via
    597 	 bfd_plugin_get_symbols_in_object_only.)  */
    598       if (*target == &binary_vec
    599 	  || *target == fail_targ
    600 	  || (((abfd->is_linker_input && match_count != 0)
    601 	       || abfd->plugin_format == bfd_plugin_no)
    602 	      && bfd_plugin_target_p (*target)))
    603 	continue;
    604 
    605       /* If we already tried a match, the bfd is modified and may
    606 	 have sections attached, which will confuse the next
    607 	 _bfd_check_format call.  */
    608       bfd_reinit (abfd, initial_section_id, &preserve, cleanup);
    609       /* Free bfd_alloc memory too.  If we have matched and preserved
    610 	 a target then the high water mark is that much higher.  */
    611       if (preserve_match.marker)
    612 	high_water = &preserve_match.marker;
    613       else
    614 	high_water = &preserve.marker;
    615       bfd_release (abfd, *high_water);
    616       *high_water = bfd_alloc (abfd, 1);
    617 
    618       /* Change BFD's target temporarily.  */
    619       abfd->xvec = *target;
    620 
    621       /* It is possible that targets appear multiple times in
    622 	 bfd_target_vector.  If this is the case, then we want to avoid
    623 	 accumulating duplicate messages for a target in MESSAGES, so
    624 	 discard any previous messages associated with this target.  */
    625       clear_messages (&messages, abfd->xvec);
    626 
    627       if (bfd_seek (abfd, 0, SEEK_SET) != 0)
    628 	goto err_ret;
    629 
    630       bfd_set_error (bfd_error_no_error);
    631       cleanup = BFD_SEND_FMT (abfd, _bfd_check_format, (abfd));
    632       if (cleanup)
    633 	{
    634 	  int match_priority = abfd->xvec->match_priority;
    635 
    636 	  if (abfd->format != bfd_archive
    637 	      || (bfd_has_map (abfd)
    638 		  && bfd_get_error () != bfd_error_wrong_object_format))
    639 	    {
    640 	      /* If this is the default target, accept it, even if
    641 		 other targets might match.  People who want those
    642 		 other targets have to set the GNUTARGET variable.  */
    643 	      if (abfd->xvec == bfd_default_vector[0])
    644 		goto ok_ret;
    645 
    646 	      if (matching_vector)
    647 		matching_vector[match_count] = abfd->xvec;
    648 	      match_count++;
    649 
    650 	      if (match_priority < best_match)
    651 		{
    652 		  best_match = match_priority;
    653 		  best_count = 0;
    654 		}
    655 	      if (match_priority <= best_match)
    656 		{
    657 		  /* This format checks out as ok!  */
    658 		  right_targ = abfd->xvec;
    659 		  best_count++;
    660 		}
    661 	    }
    662 	  else
    663 	    {
    664 	      /* An archive with no armap or objects of the wrong
    665 		 type.  We want this target to match if we get no
    666 		 better matches.  */
    667 	      if (ar_right_targ != bfd_default_vector[0])
    668 		ar_right_targ = *target;
    669 	      if (matching_vector)
    670 		matching_vector[ar_match_index] = *target;
    671 	      ar_match_index++;
    672 	    }
    673 
    674 	  if (preserve_match.marker == NULL)
    675 	    {
    676 	      match_targ = abfd->xvec;
    677 	      if (!bfd_preserve_save (abfd, &preserve_match, cleanup))
    678 		goto err_ret;
    679 	      cleanup = NULL;
    680 	    }
    681 	}
    682     }
    683 
    684   if (best_count == 1)
    685     match_count = 1;
    686 
    687   if (match_count == 0)
    688     {
    689       /* Try partial matches.  */
    690       right_targ = ar_right_targ;
    691 
    692       if (right_targ == bfd_default_vector[0])
    693 	{
    694 	  match_count = 1;
    695 	}
    696       else
    697 	{
    698 	  match_count = ar_match_index - _bfd_target_vector_entries;
    699 
    700 	  if (matching_vector && match_count > 1)
    701 	    memcpy (matching_vector,
    702 		    matching_vector + _bfd_target_vector_entries,
    703 		    sizeof (*matching_vector) * match_count);
    704 	}
    705     }
    706 
    707   /* We have more than one equally good match.  If any of the best
    708      matches is a target in config.bfd targ_defvec or targ_selvecs,
    709      choose it.  */
    710   if (match_count > 1)
    711     {
    712       const bfd_target * const *assoc = bfd_associated_vector;
    713 
    714       while ((right_targ = *assoc++) != NULL)
    715 	{
    716 	  int i = match_count;
    717 
    718 	  while (--i >= 0)
    719 	    if (matching_vector[i] == right_targ
    720 		&& right_targ->match_priority <= best_match)
    721 	      break;
    722 
    723 	  if (i >= 0)
    724 	    {
    725 	      match_count = 1;
    726 	      break;
    727 	    }
    728 	}
    729     }
    730 
    731   /* We still have more than one equally good match, and at least some
    732      of the targets support match priority.  Choose the first of the
    733      best matches.  */
    734   if (matching_vector && match_count > 1 && best_count != match_count)
    735     {
    736       int i;
    737 
    738       for (i = 0; i < match_count; i++)
    739 	{
    740 	  right_targ = matching_vector[i];
    741 	  if (right_targ->match_priority <= best_match)
    742 	    break;
    743 	}
    744       match_count = 1;
    745     }
    746 
    747   /* There is way too much undoing of half-known state here.  We
    748      really shouldn't iterate on live bfd's.  Note that saving the
    749      whole bfd and restoring it would be even worse; the first thing
    750      you notice is that the cached bfd file position gets out of sync.  */
    751   if (preserve_match.marker != NULL)
    752     cleanup = bfd_preserve_restore (abfd, &preserve_match);
    753 
    754   if (match_count == 1)
    755     {
    756       abfd->xvec = right_targ;
    757       /* If we come out of the loop knowing that the last target that
    758 	 matched is the one we want, then ABFD should still be in a usable
    759 	 state (except possibly for XVEC).  This is not just an
    760 	 optimisation.  In the case of plugins a match against the
    761 	 plugin target can result in the bfd being changed such that
    762 	 it no longer matches the plugin target, nor will it match
    763 	 RIGHT_TARG again.  */
    764       if (match_targ != right_targ)
    765 	{
    766 	  bfd_reinit (abfd, initial_section_id, &preserve, cleanup);
    767 	  bfd_release (abfd, preserve.marker);
    768 	  if (bfd_seek (abfd, 0, SEEK_SET) != 0)
    769 	    goto err_ret;
    770 	  cleanup = BFD_SEND_FMT (abfd, _bfd_check_format, (abfd));
    771 	  BFD_ASSERT (cleanup != NULL);
    772 	}
    773 
    774     ok_ret:
    775       /* If the file was opened for update, then `output_has_begun'
    776 	 some time ago when the file was created.  Do not recompute
    777 	 sections sizes or alignments in _bfd_set_section_contents.
    778 	 We can not set this flag until after checking the format,
    779 	 because it will interfere with creation of BFD sections.  */
    780       if (abfd->direction == both_direction)
    781 	abfd->output_has_begun = true;
    782 
    783       free (matching_vector);
    784       if (preserve_match.marker != NULL)
    785 	bfd_preserve_finish (abfd, &preserve_match);
    786       bfd_preserve_finish (abfd, &preserve);
    787       _bfd_restore_error_handler_caching (orig_messages);
    788 
    789       print_and_clear_messages (&messages, abfd->xvec);
    790 
    791       bfd_set_lto_type (abfd);
    792 
    793       /* File position has moved, BTW.  */
    794       bool ret = bfd_cache_set_uncloseable (abfd, old_in_format_matches, NULL);
    795       if (!bfd_unlock ())
    796 	return false;
    797       return ret;
    798     }
    799 
    800   if (match_count == 0)
    801     {
    802     err_unrecog:
    803       bfd_set_error (bfd_error_file_not_recognized);
    804     err_ret:
    805       if (cleanup)
    806 	cleanup (abfd);
    807       abfd->xvec = save_targ;
    808       abfd->format = bfd_unknown;
    809       free (matching_vector);
    810       goto out;
    811     }
    812 
    813   /* Restore original target type and format.  */
    814   abfd->xvec = save_targ;
    815   abfd->format = bfd_unknown;
    816   bfd_set_error (bfd_error_file_ambiguously_recognized);
    817 
    818   if (matching)
    819     {
    820       *matching = (char **) matching_vector;
    821       matching_vector[match_count] = NULL;
    822       /* Return target names.  This is a little nasty.  Maybe we
    823 	 should do another bfd_malloc?  */
    824       while (--match_count >= 0)
    825 	{
    826 	  const char *name = matching_vector[match_count]->name;
    827 	  *(const char **) &matching_vector[match_count] = name;
    828 	}
    829     }
    830   else
    831     free (matching_vector);
    832   if (cleanup)
    833     cleanup (abfd);
    834  out:
    835   if (preserve_match.marker != NULL)
    836     bfd_preserve_finish (abfd, &preserve_match);
    837   if (preserve.marker != NULL)
    838     bfd_preserve_restore (abfd, &preserve);
    839   _bfd_restore_error_handler_caching (orig_messages);
    840   print_and_clear_messages (&messages, PER_XVEC_NO_TARGET);
    841   bfd_cache_set_uncloseable (abfd, old_in_format_matches, NULL);
    842   bfd_unlock ();
    843   return false;
    844 }
    845 
    846 /*
    847 FUNCTION
    848 	bfd_set_format
    849 
    850 SYNOPSIS
    851 	bool bfd_set_format (bfd *abfd, bfd_format format);
    852 
    853 DESCRIPTION
    854 	This function sets the file format of the BFD @var{abfd} to the
    855 	format @var{format}. If the target set in the BFD does not
    856 	support the format requested, the format is invalid, or the BFD
    857 	is not open for writing, then an error occurs.
    858 */
    859 
    860 bool
    861 bfd_set_format (bfd *abfd, bfd_format format)
    862 {
    863   if (bfd_read_p (abfd)
    864       || (unsigned int) abfd->format >= (unsigned int) bfd_type_end)
    865     {
    866       bfd_set_error (bfd_error_invalid_operation);
    867       return false;
    868     }
    869 
    870   if (abfd->format != bfd_unknown)
    871     return abfd->format == format;
    872 
    873   /* Presume the answer is yes.  */
    874   abfd->format = format;
    875 
    876   if (!BFD_SEND_FMT (abfd, _bfd_set_format, (abfd)))
    877     {
    878       abfd->format = bfd_unknown;
    879       return false;
    880     }
    881 
    882   return true;
    883 }
    884 
    885 /*
    886 FUNCTION
    887 	bfd_format_string
    888 
    889 SYNOPSIS
    890 	const char *bfd_format_string (bfd_format format);
    891 
    892 DESCRIPTION
    893 	Return a pointer to a const string
    894 	<<invalid>>, <<object>>, <<archive>>, <<core>>, or <<unknown>>,
    895 	depending upon the value of @var{format}.
    896 */
    897 
    898 const char *
    899 bfd_format_string (bfd_format format)
    900 {
    901   if (((int) format < (int) bfd_unknown)
    902       || ((int) format >= (int) bfd_type_end))
    903     return "invalid";
    904 
    905   switch (format)
    906     {
    907     case bfd_object:
    908       return "object";		/* Linker/assembler/compiler output.  */
    909     case bfd_archive:
    910       return "archive";		/* Object archive file.  */
    911     case bfd_core:
    912       return "core";		/* Core dump.  */
    913     default:
    914       return "unknown";
    915     }
    916 }
    917