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