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