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