Home | History | Annotate | Line # | Download | only in bfd
opncls.c revision 1.1.1.10
      1 /* opncls.c -- open and close a BFD.
      2    Copyright (C) 1990-2024 Free Software Foundation, Inc.
      3 
      4    Written by Cygnus Support.
      5 
      6    This file is part of BFD, the Binary File Descriptor library.
      7 
      8    This program is free software; you can redistribute it and/or modify
      9    it under the terms of the GNU General Public License as published by
     10    the Free Software Foundation; either version 3 of the License, or
     11    (at your option) any later version.
     12 
     13    This program is distributed in the hope that it will be useful,
     14    but WITHOUT ANY WARRANTY; without even the implied warranty of
     15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16    GNU General Public License for more details.
     17 
     18    You should have received a copy of the GNU General Public License
     19    along with this program; if not, write to the Free Software
     20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
     21    MA 02110-1301, USA.  */
     22 
     23 #include "sysdep.h"
     24 #include "bfd.h"
     25 #include "objalloc.h"
     26 #include "libbfd.h"
     27 #include "libiberty.h"
     28 #include "elf-bfd.h"
     29 
     30 #ifndef S_IXUSR
     31 #define S_IXUSR 0100	/* Execute by owner.  */
     32 #endif
     33 #ifndef S_IXGRP
     34 #define S_IXGRP 0010	/* Execute by group.  */
     35 #endif
     36 #ifndef S_IXOTH
     37 #define S_IXOTH 0001	/* Execute by others.  */
     38 #endif
     39 
     40 /*
     41 SECTION
     42 	Opening and closing BFDs
     43 
     44 SUBSECTION
     45 	Functions for opening and closing
     46 */
     47 
     48 /* Counter used to initialize the unique bfd identifier.  */
     49 
     50 static unsigned int bfd_id_counter = 0;
     51 
     52 /* fdopen is a loser -- we should use stdio exclusively.  Unfortunately
     53    if we do that we can't use fcntl.  */
     54 
     55 /*
     56 INTERNAL_FUNCTION
     57 	_bfd_new_bfd
     58 
     59 SYNOPSIS
     60 	bfd *_bfd_new_bfd (void);
     61 
     62 DESCRIPTION
     63 	Return a new BFD.  All BFD's are allocated through this routine.
     64 */
     65 
     66 bfd *
     67 _bfd_new_bfd (void)
     68 {
     69   bfd *nbfd;
     70 
     71   nbfd = (bfd *) bfd_zmalloc (sizeof (bfd));
     72   if (nbfd == NULL)
     73     return NULL;
     74 
     75   if (!bfd_lock ())
     76     return NULL;
     77   nbfd->id = bfd_id_counter++;
     78   if (!bfd_unlock ())
     79     {
     80       free (nbfd);
     81       return NULL;
     82     }
     83 
     84   nbfd->memory = objalloc_create ();
     85   if (nbfd->memory == NULL)
     86     {
     87       bfd_set_error (bfd_error_no_memory);
     88       free (nbfd);
     89       return NULL;
     90     }
     91 
     92   nbfd->arch_info = &bfd_default_arch_struct;
     93 
     94   if (!bfd_hash_table_init_n (& nbfd->section_htab, bfd_section_hash_newfunc,
     95 			      sizeof (struct section_hash_entry), 13))
     96     {
     97       objalloc_free ((struct objalloc *) nbfd->memory);
     98       free (nbfd);
     99       return NULL;
    100     }
    101 
    102   nbfd->archive_plugin_fd = -1;
    103 
    104   return nbfd;
    105 }
    106 
    107 static const struct bfd_iovec opncls_iovec;
    108 
    109 /*
    110 INTERNAL_FUNCTION
    111 	_bfd_new_bfd_contained_in
    112 
    113 SYNOPSIS
    114 	bfd *_bfd_new_bfd_contained_in (bfd *);
    115 
    116 DESCRIPTION
    117 	Allocate a new BFD as a member of archive OBFD.
    118 */
    119 
    120 bfd *
    121 _bfd_new_bfd_contained_in (bfd *obfd)
    122 {
    123   bfd *nbfd;
    124 
    125   /* Nested archives in bims are unsupported.  */
    126   if ((obfd->flags & BFD_IN_MEMORY) != 0)
    127     {
    128       bfd_set_error (bfd_error_malformed_archive);
    129       return NULL;
    130     }
    131   nbfd = _bfd_new_bfd ();
    132   if (nbfd == NULL)
    133     return NULL;
    134   nbfd->xvec = obfd->xvec;
    135   nbfd->iovec = obfd->iovec;
    136   if (obfd->iovec == &opncls_iovec)
    137     nbfd->iostream = obfd->iostream;
    138   nbfd->my_archive = obfd;
    139   nbfd->direction = read_direction;
    140   nbfd->target_defaulted = obfd->target_defaulted;
    141   nbfd->lto_output = obfd->lto_output;
    142   nbfd->no_export = obfd->no_export;
    143   return nbfd;
    144 }
    145 
    146 /* Delete a BFD.  */
    147 
    148 static void
    149 _bfd_delete_bfd (bfd *abfd)
    150 {
    151 #ifdef USE_MMAP
    152   if (abfd->xvec
    153       && abfd->xvec->flavour == bfd_target_elf_flavour)
    154     {
    155       asection *sec;
    156       for (sec = abfd->sections; sec != NULL; sec = sec->next)
    157 	if (sec->mmapped_p)
    158 	  munmap (elf_section_data (sec)->contents_addr,
    159 		  elf_section_data (sec)->contents_size);
    160     }
    161 #endif
    162 
    163   /* Give the target _bfd_free_cached_info a chance to free memory.  */
    164   if (abfd->memory && abfd->xvec)
    165     bfd_free_cached_info (abfd);
    166 
    167   /* The target _bfd_free_cached_info may not have done anything..  */
    168   if (abfd->memory)
    169     {
    170       bfd_hash_table_free (&abfd->section_htab);
    171       objalloc_free ((struct objalloc *) abfd->memory);
    172     }
    173   else
    174     free ((char *) bfd_get_filename (abfd));
    175 
    176 #ifdef USE_MMAP
    177   struct bfd_mmapped *mmapped, *next;
    178   for (mmapped = abfd->mmapped; mmapped != NULL; mmapped = next)
    179     {
    180       struct bfd_mmapped_entry *entries = mmapped->entries;
    181       next = mmapped->next;
    182       for (unsigned int i = 0; i < mmapped->next_entry; i++)
    183 	munmap (entries[i].addr, entries[i].size);
    184       munmap (mmapped, _bfd_pagesize);
    185     }
    186 #endif
    187 
    188   free (abfd->arelt_data);
    189   free (abfd);
    190 }
    191 
    192 /*
    193 INTERNAL_FUNCTION
    194 	_bfd_free_cached_info
    195 
    196 SYNOPSIS
    197 	bool _bfd_free_cached_info (bfd *);
    198 
    199 DESCRIPTION
    200 	Free objalloc memory.
    201 */
    202 
    203 bool
    204 _bfd_free_cached_info (bfd *abfd)
    205 {
    206   if (abfd->memory)
    207     {
    208       const char *filename = bfd_get_filename (abfd);
    209       if (filename)
    210 	{
    211 	  /* We can't afford to lose the bfd filename when freeing
    212 	     abfd->memory, because that would kill the cache.c scheme
    213 	     of closing and reopening files in order to limit the
    214 	     number of open files.  To reopen, you need the filename.
    215 	     And indeed _bfd_compute_and_write_armap calls
    216 	     _bfd_free_cached_info to free up space used by symbols
    217 	     and by check_format_matches.  Which we want to continue
    218 	     doing to handle very large archives.  Later the archive
    219 	     elements are copied, which might require reopening files.
    220 	     We also want to keep using objalloc memory for the
    221 	     filename since that allows the name to be updated
    222 	     without either leaking memory or implementing some sort
    223 	     of reference counted string for copies of the filename.  */
    224 	  size_t len = strlen (filename) + 1;
    225 	  char *copy = bfd_malloc (len);
    226 	  if (copy == NULL)
    227 	    return false;
    228 	  memcpy (copy, filename, len);
    229 	  abfd->filename = copy;
    230 	}
    231       bfd_hash_table_free (&abfd->section_htab);
    232       objalloc_free ((struct objalloc *) abfd->memory);
    233 
    234       abfd->sections = NULL;
    235       abfd->section_last = NULL;
    236       abfd->outsymbols = NULL;
    237       abfd->tdata.any = NULL;
    238       abfd->usrdata = NULL;
    239       abfd->memory = NULL;
    240     }
    241 
    242   return true;
    243 }
    244 
    245 /*
    246 FUNCTION
    247 	bfd_fopen
    248 
    249 SYNOPSIS
    250 	bfd *bfd_fopen (const char *filename, const char *target,
    251 			const char *mode, int fd);
    252 
    253 DESCRIPTION
    254 	Open the file @var{filename} with the target @var{target}.
    255 	Return a pointer to the created BFD.  If @var{fd} is not -1,
    256 	then <<fdopen>> is used to open the file; otherwise, <<fopen>>
    257 	is used.  @var{mode} is passed directly to <<fopen>> or
    258 	<<fdopen>>.
    259 
    260 	Calls <<bfd_find_target>>, so @var{target} is interpreted as by
    261 	that function.
    262 
    263 	The new BFD is marked as cacheable iff @var{fd} is -1.
    264 
    265 	If <<NULL>> is returned then an error has occured.   Possible errors
    266 	are <<bfd_error_no_memory>>, <<bfd_error_invalid_target>> or
    267 	<<system_call>> error.
    268 
    269 	On error, @var{fd} is always closed.
    270 
    271 	A copy of the @var{filename} argument is stored in the newly created
    272 	BFD.  It can be accessed via the bfd_get_filename() macro.
    273 */
    274 
    275 bfd *
    276 bfd_fopen (const char *filename, const char *target, const char *mode, int fd)
    277 {
    278   bfd *nbfd;
    279   const bfd_target *target_vec;
    280 
    281   nbfd = _bfd_new_bfd ();
    282   if (nbfd == NULL)
    283     {
    284       if (fd != -1)
    285 	close (fd);
    286       return NULL;
    287     }
    288 
    289   target_vec = bfd_find_target (target, nbfd);
    290   if (target_vec == NULL)
    291     {
    292       if (fd != -1)
    293 	close (fd);
    294       _bfd_delete_bfd (nbfd);
    295       return NULL;
    296     }
    297 
    298 #ifdef HAVE_FDOPEN
    299   if (fd != -1)
    300     nbfd->iostream = fdopen (fd, mode);
    301   else
    302 #endif
    303     nbfd->iostream = _bfd_real_fopen (filename, mode);
    304   if (nbfd->iostream == NULL)
    305     {
    306       bfd_set_error (bfd_error_system_call);
    307       if (fd != -1)
    308 	close (fd);
    309       _bfd_delete_bfd (nbfd);
    310       return NULL;
    311     }
    312 
    313   /* OK, put everything where it belongs.  */
    314 
    315   /* PR 11983: Do not cache the original filename, but
    316      rather make a copy - the original might go away.  */
    317   if (!bfd_set_filename (nbfd, filename))
    318     {
    319       fclose (nbfd->iostream);
    320       _bfd_delete_bfd (nbfd);
    321       return NULL;
    322     }
    323 
    324   /* Figure out whether the user is opening the file for reading,
    325      writing, or both, by looking at the MODE argument.  */
    326   if ((mode[0] == 'r' || mode[0] == 'w' || mode[0] == 'a')
    327       && mode[1] == '+')
    328     nbfd->direction = both_direction;
    329   else if (mode[0] == 'r')
    330     nbfd->direction = read_direction;
    331   else
    332     nbfd->direction = write_direction;
    333 
    334   if (!bfd_cache_init (nbfd))
    335     {
    336       fclose (nbfd->iostream);
    337       _bfd_delete_bfd (nbfd);
    338       return NULL;
    339     }
    340   nbfd->opened_once = true;
    341 
    342   /* If we opened the file by name, mark it cacheable; we can close it
    343      and reopen it later.  However, if a file descriptor was provided,
    344      then it may have been opened with special flags that make it
    345      unsafe to close and reopen the file.  */
    346   if (fd == -1)
    347     (void) bfd_set_cacheable (nbfd, true);
    348 
    349   return nbfd;
    350 }
    351 
    352 /*
    353 FUNCTION
    354 	bfd_openr
    355 
    356 SYNOPSIS
    357 	bfd *bfd_openr (const char *filename, const char *target);
    358 
    359 DESCRIPTION
    360 	Open the file @var{filename} (using <<fopen>>) with the target
    361 	@var{target}.  Return a pointer to the created BFD.
    362 
    363 	Calls <<bfd_find_target>>, so @var{target} is interpreted as by
    364 	that function.
    365 
    366 	If <<NULL>> is returned then an error has occured.   Possible errors
    367 	are <<bfd_error_no_memory>>, <<bfd_error_invalid_target>> or
    368 	<<system_call>> error.
    369 
    370 	A copy of the @var{filename} argument is stored in the newly created
    371 	BFD.  It can be accessed via the bfd_get_filename() macro.
    372 */
    373 
    374 bfd *
    375 bfd_openr (const char *filename, const char *target)
    376 {
    377   return bfd_fopen (filename, target, FOPEN_RB, -1);
    378 }
    379 
    380 /* Don't try to `optimize' this function:
    381 
    382    o - We lock using stack space so that interrupting the locking
    383        won't cause a storage leak.
    384    o - We open the file stream last, since we don't want to have to
    385        close it if anything goes wrong.  Closing the stream means closing
    386        the file descriptor too, even though we didn't open it.  */
    387 /*
    388 FUNCTION
    389 	bfd_fdopenr
    390 
    391 SYNOPSIS
    392 	bfd *bfd_fdopenr (const char *filename, const char *target, int fd);
    393 
    394 DESCRIPTION
    395 	<<bfd_fdopenr>> is to <<bfd_fopenr>> much like <<fdopen>> is to
    396 	<<fopen>>.  It opens a BFD on a file already described by the
    397 	@var{fd} supplied.
    398 
    399 	When the file is later <<bfd_close>>d, the file descriptor will
    400 	be closed.  If the caller desires that this file descriptor be
    401 	cached by BFD (opened as needed, closed as needed to free
    402 	descriptors for other opens), with the supplied @var{fd} used as
    403 	an initial file descriptor (but subject to closure at any time),
    404 	call bfd_set_cacheable(bfd, 1) on the returned BFD.  The default
    405 	is to assume no caching; the file descriptor will remain open
    406 	until <<bfd_close>>, and will not be affected by BFD operations
    407 	on other files.
    408 
    409 	Possible errors are <<bfd_error_no_memory>>,
    410 	<<bfd_error_invalid_target>> and <<bfd_error_system_call>>.
    411 
    412 	On error, @var{fd} is closed.
    413 
    414 	A copy of the @var{filename} argument is stored in the newly created
    415 	BFD.  It can be accessed via the bfd_get_filename() macro.
    416 */
    417 
    418 bfd *
    419 bfd_fdopenr (const char *filename, const char *target, int fd)
    420 {
    421   const char *mode;
    422 #if defined(HAVE_FCNTL) && defined(F_GETFL)
    423   int fdflags;
    424 #endif
    425 
    426 #if ! defined(HAVE_FCNTL) || ! defined(F_GETFL)
    427   mode = FOPEN_RUB; /* Assume full access.  */
    428 #else
    429   fdflags = fcntl (fd, F_GETFL, NULL);
    430   if (fdflags == -1)
    431     {
    432       int save = errno;
    433 
    434       close (fd);
    435       errno = save;
    436       bfd_set_error (bfd_error_system_call);
    437       return NULL;
    438     }
    439 
    440   /* (O_ACCMODE) parens are to avoid Ultrix header file bug.  */
    441   switch (fdflags & (O_ACCMODE))
    442     {
    443     case O_RDONLY: mode = FOPEN_RB; break;
    444     case O_WRONLY: mode = FOPEN_RUB; break;
    445     case O_RDWR:   mode = FOPEN_RUB; break;
    446     default: abort ();
    447     }
    448 #endif
    449 
    450   return bfd_fopen (filename, target, mode, fd);
    451 }
    452 
    453 /*
    454 FUNCTION
    455 	bfd_fdopenw
    456 
    457 SYNOPSIS
    458 	bfd *bfd_fdopenw (const char *filename, const char *target, int fd);
    459 
    460 DESCRIPTION
    461 	<<bfd_fdopenw>> is exactly like <<bfd_fdopenr>> with the exception that
    462 	the resulting BFD is suitable for output.
    463 */
    464 
    465 bfd *
    466 bfd_fdopenw (const char *filename, const char *target, int fd)
    467 {
    468   bfd *out = bfd_fdopenr (filename, target, fd);
    469 
    470   if (out != NULL)
    471     {
    472       if (!bfd_write_p (out))
    473 	{
    474 	  close (fd);
    475 	  _bfd_delete_bfd (out);
    476 	  out = NULL;
    477 	  bfd_set_error (bfd_error_invalid_operation);
    478 	}
    479       else
    480 	out->direction = write_direction;
    481     }
    482 
    483   return out;
    484 }
    485 
    486 /*
    487 FUNCTION
    488 	bfd_openstreamr
    489 
    490 SYNOPSIS
    491 	bfd *bfd_openstreamr (const char * filename, const char * target,
    492 			      void * stream);
    493 
    494 DESCRIPTION
    495 	Open a BFD for read access on an existing stdio stream.  When
    496 	the BFD is passed to <<bfd_close>>, the stream will be closed.
    497 
    498 	A copy of the @var{filename} argument is stored in the newly created
    499 	BFD.  It can be accessed via the bfd_get_filename() macro.
    500 */
    501 
    502 bfd *
    503 bfd_openstreamr (const char *filename, const char *target, void *streamarg)
    504 {
    505   FILE *stream = (FILE *) streamarg;
    506   bfd *nbfd;
    507   const bfd_target *target_vec;
    508 
    509   nbfd = _bfd_new_bfd ();
    510   if (nbfd == NULL)
    511     return NULL;
    512 
    513   target_vec = bfd_find_target (target, nbfd);
    514   if (target_vec == NULL)
    515     {
    516       _bfd_delete_bfd (nbfd);
    517       return NULL;
    518     }
    519 
    520   nbfd->iostream = stream;
    521   /* PR 11983: Do not cache the original filename, but
    522      rather make a copy - the original might go away.  */
    523   if (!bfd_set_filename (nbfd, filename))
    524     {
    525       _bfd_delete_bfd (nbfd);
    526       return NULL;
    527     }
    528   nbfd->direction = read_direction;
    529 
    530   if (! bfd_cache_init (nbfd))
    531     {
    532       _bfd_delete_bfd (nbfd);
    533       return NULL;
    534     }
    535 
    536   return nbfd;
    537 }
    538 
    539 /*
    540 FUNCTION
    541 	bfd_openr_iovec
    542 
    543 SYNOPSIS
    544 	bfd *bfd_openr_iovec (const char *filename, const char *target,
    545 			      void *(*open_func) (struct bfd *nbfd,
    546 						  void *open_closure),
    547 			      void *open_closure,
    548 			      file_ptr (*pread_func) (struct bfd *nbfd,
    549 						      void *stream,
    550 						      void *buf,
    551 						      file_ptr nbytes,
    552 						      file_ptr offset),
    553 			      int (*close_func) (struct bfd *nbfd,
    554 						 void *stream),
    555 			      int (*stat_func) (struct bfd *abfd,
    556 						void *stream,
    557 						struct stat *sb));
    558 
    559 DESCRIPTION
    560 	Create and return a BFD backed by a read-only @var{stream}.
    561 	The @var{stream} is created using @var{open_func}, accessed using
    562 	@var{pread_func} and destroyed using @var{close_func}.
    563 
    564 	Calls <<bfd_find_target>>, so @var{target} is interpreted as by
    565 	that function.
    566 
    567 	Calls @var{open_func} (which can call <<bfd_zalloc>> and
    568 	<<bfd_get_filename>>) to obtain the read-only stream backing
    569 	the BFD.  @var{open_func} either succeeds returning the
    570 	non-<<NULL>> @var{stream}, or fails returning <<NULL>>
    571 	(setting <<bfd_error>>).
    572 
    573 	Calls @var{pread_func} to request @var{nbytes} of data from
    574 	@var{stream} starting at @var{offset} (e.g., via a call to
    575 	<<bfd_read>>).  @var{pread_func} either succeeds returning the
    576 	number of bytes read (which can be less than @var{nbytes} when
    577 	end-of-file), or fails returning -1 (setting <<bfd_error>>).
    578 
    579 	Calls @var{close_func} when the BFD is later closed using
    580 	<<bfd_close>>.  @var{close_func} either succeeds returning 0, or
    581 	fails returning -1 (setting <<bfd_error>>).
    582 
    583 	Calls @var{stat_func} to fill in a stat structure for bfd_stat,
    584 	bfd_get_size, and bfd_get_mtime calls.  @var{stat_func} returns 0
    585 	on success, or returns -1 on failure (setting <<bfd_error>>).
    586 
    587 	If <<bfd_openr_iovec>> returns <<NULL>> then an error has
    588 	occurred.  Possible errors are <<bfd_error_no_memory>>,
    589 	<<bfd_error_invalid_target>> and <<bfd_error_system_call>>.
    590 
    591 	A copy of the @var{filename} argument is stored in the newly created
    592 	BFD.  It can be accessed via the bfd_get_filename() macro.
    593 */
    594 
    595 struct opncls
    596 {
    597   void *stream;
    598   file_ptr (*pread) (struct bfd *abfd, void *stream, void *buf,
    599 		     file_ptr nbytes, file_ptr offset);
    600   int (*close) (struct bfd *abfd, void *stream);
    601   int (*stat) (struct bfd *abfd, void *stream, struct stat *sb);
    602   file_ptr where;
    603 };
    604 
    605 static file_ptr
    606 opncls_btell (struct bfd *abfd)
    607 {
    608   struct opncls *vec = (struct opncls *) abfd->iostream;
    609   return vec->where;
    610 }
    611 
    612 static int
    613 opncls_bseek (struct bfd *abfd, file_ptr offset, int whence)
    614 {
    615   struct opncls *vec = (struct opncls *) abfd->iostream;
    616   switch (whence)
    617     {
    618     case SEEK_SET: vec->where = offset; break;
    619     case SEEK_CUR: vec->where += offset; break;
    620     case SEEK_END: return -1;
    621     }
    622   return 0;
    623 }
    624 
    625 static file_ptr
    626 opncls_bread (struct bfd *abfd, void *buf, file_ptr nbytes)
    627 {
    628   struct opncls *vec = (struct opncls *) abfd->iostream;
    629   file_ptr nread = (vec->pread) (abfd, vec->stream, buf, nbytes, vec->where);
    630 
    631   if (nread < 0)
    632     return nread;
    633   vec->where += nread;
    634   return nread;
    635 }
    636 
    637 static file_ptr
    638 opncls_bwrite (struct bfd *abfd ATTRIBUTE_UNUSED,
    639 	      const void *where ATTRIBUTE_UNUSED,
    640 	      file_ptr nbytes ATTRIBUTE_UNUSED)
    641 {
    642   return -1;
    643 }
    644 
    645 static int
    646 opncls_bclose (struct bfd *abfd)
    647 {
    648   struct opncls *vec = (struct opncls *) abfd->iostream;
    649   /* Since the VEC's memory is bound to the bfd deleting the bfd will
    650      free it.  */
    651   int status = 0;
    652 
    653   if (vec->close != NULL)
    654     status = (vec->close) (abfd, vec->stream);
    655   abfd->iostream = NULL;
    656   return status;
    657 }
    658 
    659 static int
    660 opncls_bflush (struct bfd *abfd ATTRIBUTE_UNUSED)
    661 {
    662   return 0;
    663 }
    664 
    665 static int
    666 opncls_bstat (struct bfd *abfd, struct stat *sb)
    667 {
    668   struct opncls *vec = (struct opncls *) abfd->iostream;
    669 
    670   memset (sb, 0, sizeof (*sb));
    671   if (vec->stat == NULL)
    672     return 0;
    673 
    674   return (vec->stat) (abfd, vec->stream, sb);
    675 }
    676 
    677 static void *
    678 opncls_bmmap (struct bfd *abfd ATTRIBUTE_UNUSED,
    679 	      void *addr ATTRIBUTE_UNUSED,
    680 	      size_t len ATTRIBUTE_UNUSED,
    681 	      int prot ATTRIBUTE_UNUSED,
    682 	      int flags ATTRIBUTE_UNUSED,
    683 	      file_ptr offset ATTRIBUTE_UNUSED,
    684 	      void **map_addr ATTRIBUTE_UNUSED,
    685 	      size_t *map_len ATTRIBUTE_UNUSED)
    686 {
    687   return MAP_FAILED;
    688 }
    689 
    690 static const struct bfd_iovec opncls_iovec =
    691 {
    692   &opncls_bread, &opncls_bwrite, &opncls_btell, &opncls_bseek,
    693   &opncls_bclose, &opncls_bflush, &opncls_bstat, &opncls_bmmap
    694 };
    695 
    696 bfd *
    697 bfd_openr_iovec (const char *filename, const char *target,
    698 		 void *(*open_p) (struct bfd *, void *),
    699 		 void *open_closure,
    700 		 file_ptr (*pread_p) (struct bfd *, void *, void *,
    701 				      file_ptr, file_ptr),
    702 		 int (*close_p) (struct bfd *, void *),
    703 		 int (*stat_p) (struct bfd *, void *, struct stat *))
    704 {
    705   bfd *nbfd;
    706   const bfd_target *target_vec;
    707   struct opncls *vec;
    708   void *stream;
    709 
    710   nbfd = _bfd_new_bfd ();
    711   if (nbfd == NULL)
    712     return NULL;
    713 
    714   target_vec = bfd_find_target (target, nbfd);
    715   if (target_vec == NULL)
    716     {
    717       _bfd_delete_bfd (nbfd);
    718       return NULL;
    719     }
    720 
    721   /* PR 11983: Do not cache the original filename, but
    722      rather make a copy - the original might go away.  */
    723   if (!bfd_set_filename (nbfd, filename))
    724     {
    725       _bfd_delete_bfd (nbfd);
    726       return NULL;
    727     }
    728   nbfd->direction = read_direction;
    729 
    730   /* `open_p (...)' would get expanded by an the open(2) syscall macro.  */
    731   stream = (*open_p) (nbfd, open_closure);
    732   if (stream == NULL)
    733     {
    734       _bfd_delete_bfd (nbfd);
    735       return NULL;
    736     }
    737 
    738   vec = (struct opncls *) bfd_zalloc (nbfd, sizeof (struct opncls));
    739   vec->stream = stream;
    740   vec->pread = pread_p;
    741   vec->close = close_p;
    742   vec->stat = stat_p;
    743 
    744   nbfd->iovec = &opncls_iovec;
    745   nbfd->iostream = vec;
    746 
    747   return nbfd;
    748 }
    749 
    750 /* bfd_openw -- open for writing.
    752    Returns a pointer to a freshly-allocated BFD on success, or NULL.
    753 
    754    See comment by bfd_fdopenr before you try to modify this function.  */
    755 
    756 /*
    757 FUNCTION
    758 	bfd_openw
    759 
    760 SYNOPSIS
    761 	bfd *bfd_openw (const char *filename, const char *target);
    762 
    763 DESCRIPTION
    764 	Create a BFD, associated with file @var{filename}, using the
    765 	file format @var{target}, and return a pointer to it.
    766 
    767 	Possible errors are <<bfd_error_system_call>>, <<bfd_error_no_memory>>,
    768 	<<bfd_error_invalid_target>>.
    769 
    770 	A copy of the @var{filename} argument is stored in the newly created
    771 	BFD.  It can be accessed via the bfd_get_filename() macro.
    772 */
    773 
    774 bfd *
    775 bfd_openw (const char *filename, const char *target)
    776 {
    777   bfd *nbfd;
    778   const bfd_target *target_vec;
    779 
    780   /* nbfd has to point to head of malloc'ed block so that bfd_close may
    781      reclaim it correctly.  */
    782   nbfd = _bfd_new_bfd ();
    783   if (nbfd == NULL)
    784     return NULL;
    785 
    786   target_vec = bfd_find_target (target, nbfd);
    787   if (target_vec == NULL)
    788     {
    789       _bfd_delete_bfd (nbfd);
    790       return NULL;
    791     }
    792 
    793   /* PR 11983: Do not cache the original filename, but
    794      rather make a copy - the original might go away.  */
    795   if (!bfd_set_filename (nbfd, filename))
    796     {
    797       _bfd_delete_bfd (nbfd);
    798       return NULL;
    799     }
    800   nbfd->direction = write_direction;
    801 
    802   if (bfd_open_file (nbfd) == NULL)
    803     {
    804       /* File not writeable, etc.  */
    805       bfd_set_error (bfd_error_system_call);
    806       _bfd_delete_bfd (nbfd);
    807       return NULL;
    808   }
    809 
    810   return nbfd;
    811 }
    812 
    813 /*
    814 FUNCTION
    815 	bfd_elf_bfd_from_remote_memory
    816 
    817 SYNOPSIS
    818 	bfd *bfd_elf_bfd_from_remote_memory
    819 	  (bfd *templ, bfd_vma ehdr_vma, bfd_size_type size, bfd_vma *loadbasep,
    820 	   int (*target_read_memory)
    821 	     (bfd_vma vma, bfd_byte *myaddr, bfd_size_type len));
    822 
    823 DESCRIPTION
    824 	Create a new BFD as if by bfd_openr.  Rather than opening a
    825 	file, reconstruct an ELF file by reading the segments out of
    826 	remote memory based on the ELF file header at EHDR_VMA and the
    827 	ELF program headers it points to.  If non-zero, SIZE is the
    828 	known extent of the object.  If not null, *LOADBASEP is filled
    829 	in with the difference between the VMAs from which the
    830 	segments were read, and the VMAs the file headers (and hence
    831 	BFD's idea of each section's VMA) put them at.
    832 
    833 	The function TARGET_READ_MEMORY is called to copy LEN bytes
    834 	from the remote memory at target address VMA into the local
    835 	buffer at MYADDR; it should return zero on success or an
    836 	errno code on failure.  TEMPL must be a BFD for an ELF
    837 	target with the word size and byte order found in the remote
    838 	memory.
    839 */
    840 
    841 bfd *
    842 bfd_elf_bfd_from_remote_memory
    843   (bfd *templ,
    844    bfd_vma ehdr_vma,
    845    bfd_size_type size,
    846    bfd_vma *loadbasep,
    847    int (*target_read_memory) (bfd_vma, bfd_byte *, bfd_size_type))
    848 {
    849   if (bfd_get_flavour (templ) != bfd_target_elf_flavour)
    850     {
    851       bfd_set_error (bfd_error_invalid_operation);
    852       return NULL;
    853     }
    854   return (*get_elf_backend_data (templ)->elf_backend_bfd_from_remote_memory)
    855     (templ, ehdr_vma, size, loadbasep, target_read_memory);
    856 }
    857 
    858 static inline void
    859 _maybe_make_executable (bfd * abfd)
    860 {
    861   /* If the file was open for writing and is now executable,
    862      make it so.  */
    863   if (abfd->direction == write_direction
    864       && (abfd->flags & (EXEC_P | DYNAMIC)) != 0)
    865     {
    866       struct stat buf;
    867 
    868       if (stat (bfd_get_filename (abfd), &buf) == 0
    869 	  /* Do not attempt to change non-regular files.  This is
    870 	     here especially for configure scripts and kernel builds
    871 	     which run tests with "ld [...] -o /dev/null".  */
    872 	  && S_ISREG(buf.st_mode))
    873 	{
    874 	  unsigned int mask = umask (0);
    875 
    876 	  umask (mask);
    877 	  chmod (bfd_get_filename (abfd),
    878 		 (0777
    879 		  & (buf.st_mode | ((S_IXUSR | S_IXGRP | S_IXOTH) &~ mask))));
    880 	}
    881     }
    882 }
    883 
    884 /*
    885 FUNCTION
    886 	bfd_close
    887 
    888 SYNOPSIS
    889 	bool bfd_close (bfd *abfd);
    890 
    891 DESCRIPTION
    892 	Close a BFD. If the BFD was open for writing, then pending
    893 	operations are completed and the file written out and closed.
    894 	If the created file is executable, then <<chmod>> is called
    895 	to mark it as such.
    896 
    897 	All memory attached to the BFD is released.
    898 
    899 	The file descriptor associated with the BFD is closed (even
    900 	if it was passed in to BFD by <<bfd_fdopenr>>).
    901 
    902 	<<TRUE>> is returned if all is ok, otherwise <<FALSE>>.
    903 */
    904 
    905 bool
    906 bfd_close (bfd *abfd)
    907 {
    908   bool ret = (!bfd_write_p (abfd)
    909 	      || BFD_SEND_FMT (abfd, _bfd_write_contents, (abfd)));
    910 
    911   return bfd_close_all_done (abfd) && ret;
    912 }
    913 
    914 /*
    915 FUNCTION
    916 	bfd_close_all_done
    917 
    918 SYNOPSIS
    919 	bool bfd_close_all_done (bfd *);
    920 
    921 DESCRIPTION
    922 	Close a BFD.  Differs from <<bfd_close>> since it does not
    923 	complete any pending operations.  This routine would be used
    924 	if the application had just used BFD for swapping and didn't
    925 	want to use any of the writing code.
    926 
    927 	If the created file is executable, then <<chmod>> is called
    928 	to mark it as such.
    929 
    930 	All memory attached to the BFD is released.
    931 
    932 	<<TRUE>> is returned if all is ok, otherwise <<FALSE>>.
    933 */
    934 
    935 bool
    936 bfd_close_all_done (bfd *abfd)
    937 {
    938   bool ret = BFD_SEND (abfd, _close_and_cleanup, (abfd));
    939 
    940   if (abfd->iovec != NULL)
    941     ret &= abfd->iovec->bclose (abfd) == 0;
    942 
    943   if (ret)
    944     _maybe_make_executable (abfd);
    945 
    946   _bfd_delete_bfd (abfd);
    947   _bfd_clear_error_data ();
    948 
    949   return ret;
    950 }
    951 
    952 /*
    953 FUNCTION
    954 	bfd_create
    955 
    956 SYNOPSIS
    957 	bfd *bfd_create (const char *filename, bfd *templ);
    958 
    959 DESCRIPTION
    960 	Create a new BFD in the manner of <<bfd_openw>>, but without
    961 	opening a file. The new BFD takes the target from the target
    962 	used by @var{templ}. The format is always set to <<bfd_object>>.
    963 
    964 	A copy of the @var{filename} argument is stored in the newly created
    965 	BFD.  It can be accessed via the bfd_get_filename() macro.
    966 */
    967 
    968 bfd *
    969 bfd_create (const char *filename, bfd *templ)
    970 {
    971   bfd *nbfd;
    972 
    973   nbfd = _bfd_new_bfd ();
    974   if (nbfd == NULL)
    975     return NULL;
    976   /* PR 11983: Do not cache the original filename, but
    977      rather make a copy - the original might go away.  */
    978   if (!bfd_set_filename (nbfd, filename))
    979     {
    980       _bfd_delete_bfd (nbfd);
    981       return NULL;
    982     }
    983   if (templ)
    984     nbfd->xvec = templ->xvec;
    985   nbfd->direction = no_direction;
    986   bfd_set_format (nbfd, bfd_object);
    987 
    988   return nbfd;
    989 }
    990 
    991 /*
    992 FUNCTION
    993 	bfd_make_writable
    994 
    995 SYNOPSIS
    996 	bool bfd_make_writable (bfd *abfd);
    997 
    998 DESCRIPTION
    999 	Takes a BFD as created by <<bfd_create>> and converts it
   1000 	into one like as returned by <<bfd_openw>>.  It does this
   1001 	by converting the BFD to BFD_IN_MEMORY.  It's assumed that
   1002 	you will call <<bfd_make_readable>> on this bfd later.
   1003 
   1004 	<<TRUE>> is returned if all is ok, otherwise <<FALSE>>.
   1005 */
   1006 
   1007 bool
   1008 bfd_make_writable (bfd *abfd)
   1009 {
   1010   struct bfd_in_memory *bim;
   1011 
   1012   if (abfd->direction != no_direction)
   1013     {
   1014       bfd_set_error (bfd_error_invalid_operation);
   1015       return false;
   1016     }
   1017 
   1018   bim = (struct bfd_in_memory *) bfd_malloc (sizeof (struct bfd_in_memory));
   1019   if (bim == NULL)
   1020     return false;	/* bfd_error already set.  */
   1021   abfd->iostream = bim;
   1022   /* bfd_write will grow these as needed.  */
   1023   bim->size = 0;
   1024   bim->buffer = 0;
   1025 
   1026   abfd->flags |= BFD_IN_MEMORY;
   1027   abfd->iovec = &_bfd_memory_iovec;
   1028   abfd->origin = 0;
   1029   abfd->direction = write_direction;
   1030   abfd->where = 0;
   1031 
   1032   return true;
   1033 }
   1034 
   1035 /*
   1036 FUNCTION
   1037 	bfd_make_readable
   1038 
   1039 SYNOPSIS
   1040 	bool bfd_make_readable (bfd *abfd);
   1041 
   1042 DESCRIPTION
   1043 	Takes a BFD as created by <<bfd_create>> and
   1044 	<<bfd_make_writable>> and converts it into one like as
   1045 	returned by <<bfd_openr>>.  It does this by writing the
   1046 	contents out to the memory buffer, then reversing the
   1047 	direction.
   1048 
   1049 	<<TRUE>> is returned if all is ok, otherwise <<FALSE>>.  */
   1050 
   1051 bool
   1052 bfd_make_readable (bfd *abfd)
   1053 {
   1054   if (abfd->direction != write_direction || !(abfd->flags & BFD_IN_MEMORY))
   1055     {
   1056       bfd_set_error (bfd_error_invalid_operation);
   1057       return false;
   1058     }
   1059 
   1060   if (! BFD_SEND_FMT (abfd, _bfd_write_contents, (abfd)))
   1061     return false;
   1062 
   1063   if (! BFD_SEND (abfd, _close_and_cleanup, (abfd)))
   1064     return false;
   1065 
   1066   abfd->arch_info = &bfd_default_arch_struct;
   1067 
   1068   abfd->where = 0;
   1069   abfd->format = bfd_unknown;
   1070   abfd->my_archive = NULL;
   1071   abfd->origin = 0;
   1072   abfd->opened_once = false;
   1073   abfd->output_has_begun = false;
   1074   abfd->section_count = 0;
   1075   abfd->usrdata = NULL;
   1076   abfd->cacheable = false;
   1077   abfd->mtime_set = false;
   1078 
   1079   abfd->target_defaulted = true;
   1080   abfd->direction = read_direction;
   1081   abfd->sections = 0;
   1082   abfd->symcount = 0;
   1083   abfd->outsymbols = 0;
   1084   abfd->tdata.any = 0;
   1085   abfd->size = 0;
   1086 
   1087   bfd_section_list_clear (abfd);
   1088   bfd_check_format (abfd, bfd_object);
   1089 
   1090   return true;
   1091 }
   1092 
   1093 /*
   1094    GNU Extension: separate debug-info files
   1095 
   1096    The idea here is that a special section called .gnu_debuglink might be
   1097    embedded in a binary file, which indicates that some *other* file
   1098    contains the real debugging information. This special section contains a
   1099    filename and CRC32 checksum, which we read and resolve to another file,
   1100    if it exists.
   1101 
   1102    This facilitates "optional" provision of debugging information, without
   1103    having to provide two complete copies of every binary object (with and
   1104    without debug symbols).  */
   1105 
   1106 #define GNU_DEBUGLINK		".gnu_debuglink"
   1107 #define GNU_DEBUGALTLINK	".gnu_debugaltlink"
   1108 
   1109 /*
   1110 FUNCTION
   1111 	bfd_calc_gnu_debuglink_crc32
   1112 
   1113 SYNOPSIS
   1114 	uint32_t bfd_calc_gnu_debuglink_crc32
   1115 	  (uint32_t crc, const bfd_byte *buf, bfd_size_type len);
   1116 
   1117 DESCRIPTION
   1118 	Computes a CRC value as used in the .gnu_debuglink section.
   1119 	Advances the previously computed @var{crc} value by computing
   1120 	and adding in the crc32 for @var{len} bytes of @var{buf}.
   1121 
   1122 	Return the updated CRC32 value.
   1123 */
   1124 
   1125 uint32_t
   1126 bfd_calc_gnu_debuglink_crc32 (uint32_t crc,
   1127 			      const bfd_byte *buf,
   1128 			      bfd_size_type len)
   1129 {
   1130   static const uint32_t crc32_table[256] =
   1131     {
   1132       0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
   1133       0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
   1134       0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
   1135       0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
   1136       0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
   1137       0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
   1138       0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
   1139       0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
   1140       0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
   1141       0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
   1142       0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
   1143       0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
   1144       0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
   1145       0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
   1146       0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
   1147       0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
   1148       0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
   1149       0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
   1150       0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
   1151       0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
   1152       0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
   1153       0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
   1154       0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
   1155       0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
   1156       0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
   1157       0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
   1158       0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
   1159       0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
   1160       0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
   1161       0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
   1162       0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
   1163       0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
   1164       0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
   1165       0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
   1166       0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
   1167       0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
   1168       0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
   1169       0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
   1170       0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
   1171       0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
   1172       0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
   1173       0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
   1174       0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
   1175       0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
   1176       0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
   1177       0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
   1178       0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
   1179       0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
   1180       0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
   1181       0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
   1182       0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
   1183       0x2d02ef8d
   1184     };
   1185   const bfd_byte *end;
   1186 
   1187   crc = ~crc & 0xffffffff;
   1188   for (end = buf + len; buf < end; ++ buf)
   1189     crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
   1190   return ~crc & 0xffffffff;
   1191 }
   1192 
   1193 
   1194 /* Extracts the filename and CRC32 value for any separate debug
   1195    information file associated with @var{abfd}.
   1196 
   1197    The @var{crc32_out} parameter is an untyped pointer because
   1198    this routine is used as a @code{get_func_type} function, but it
   1199    is expected to be a uint32_t pointer.
   1200 
   1201    Returns the filename of the associated debug information file,
   1202    or NULL if there is no such file.  If the filename was found
   1203    then the contents of @var{crc32_out} are updated to hold the
   1204    corresponding CRC32 value for the file.
   1205 
   1206    The returned filename is allocated with @code{malloc}; freeing
   1207    it is the responsibility of the caller.  */
   1208 
   1209 static char *
   1210 bfd_get_debug_link_info_1 (bfd *abfd, void *crc32_out)
   1211 {
   1212   asection *sect;
   1213   uint32_t *crc32 = crc32_out;
   1214   bfd_byte *contents;
   1215   unsigned int crc_offset;
   1216   char *name;
   1217   bfd_size_type size;
   1218 
   1219   BFD_ASSERT (abfd);
   1220   BFD_ASSERT (crc32_out);
   1221 
   1222   sect = bfd_get_section_by_name (abfd, GNU_DEBUGLINK);
   1223 
   1224   if (sect == NULL || (sect->flags & SEC_HAS_CONTENTS) == 0)
   1225     return NULL;
   1226 
   1227   size = bfd_section_size (sect);
   1228 
   1229   /* PR 22794: Make sure that the section has a reasonable size.  */
   1230   if (size < 8)
   1231     return NULL;
   1232 
   1233   if (!bfd_malloc_and_get_section (abfd, sect, &contents))
   1234     return NULL;
   1235 
   1236   /* CRC value is stored after the filename, aligned up to 4 bytes.  */
   1237   name = (char *) contents;
   1238   /* PR 17597: Avoid reading off the end of the buffer.  */
   1239   crc_offset = strnlen (name, size) + 1;
   1240   crc_offset = (crc_offset + 3) & ~3;
   1241   if (crc_offset + 4 > size)
   1242     {
   1243       free (name);
   1244       return NULL;
   1245     }
   1246 
   1247   *crc32 = bfd_get_32 (abfd, contents + crc_offset);
   1248   return name;
   1249 }
   1250 
   1251 
   1252 /*
   1253 FUNCTION
   1254 	bfd_get_debug_link_info
   1255 
   1256 SYNOPSIS
   1257 	char *bfd_get_debug_link_info (bfd *abfd, uint32_t *crc32_out);
   1258 
   1259 DESCRIPTION
   1260 	Extracts the filename and CRC32 value for any separate debug
   1261 	information file associated with @var{abfd}.
   1262 
   1263 	Returns the filename of the associated debug information file,
   1264 	or NULL if there is no such file.  If the filename was found
   1265 	then the contents of @var{crc32_out} are updated to hold the
   1266 	corresponding CRC32 value for the file.
   1267 
   1268 	The returned filename is allocated with @code{malloc}; freeing
   1269 	it is the responsibility of the caller.
   1270 */
   1271 
   1272 char *
   1273 bfd_get_debug_link_info (bfd *abfd, uint32_t *crc32_out)
   1274 {
   1275   return bfd_get_debug_link_info_1 (abfd, crc32_out);
   1276 }
   1277 
   1278 /*
   1279 FUNCTION
   1280 	bfd_get_alt_debug_link_info
   1281 
   1282 SYNOPSIS
   1283 	char *bfd_get_alt_debug_link_info (bfd * abfd,
   1284 					   bfd_size_type *buildid_len,
   1285 					   bfd_byte **buildid_out);
   1286 
   1287 DESCRIPTION
   1288 	Fetch the filename and BuildID value for any alternate debuginfo
   1289 	associated with @var{abfd}.  Return NULL if no such info found,
   1290 	otherwise return filename and update @var{buildid_len} and
   1291 	@var{buildid_out}.  The returned filename and build_id are
   1292 	allocated with @code{malloc}; freeing them is the responsibility
   1293 	of the caller.
   1294 */
   1295 
   1296 char *
   1297 bfd_get_alt_debug_link_info (bfd * abfd, bfd_size_type *buildid_len,
   1298 			     bfd_byte **buildid_out)
   1299 {
   1300   asection *sect;
   1301   bfd_byte *contents;
   1302   unsigned int buildid_offset;
   1303   char *name;
   1304   bfd_size_type size;
   1305 
   1306   BFD_ASSERT (abfd);
   1307   BFD_ASSERT (buildid_len);
   1308   BFD_ASSERT (buildid_out);
   1309 
   1310   sect = bfd_get_section_by_name (abfd, GNU_DEBUGALTLINK);
   1311 
   1312   if (sect == NULL || (sect->flags & SEC_HAS_CONTENTS) == 0)
   1313     return NULL;
   1314 
   1315   size = bfd_section_size (sect);
   1316   if (size < 8)
   1317     return NULL;
   1318 
   1319   if (!bfd_malloc_and_get_section (abfd, sect, & contents))
   1320     return NULL;
   1321 
   1322   /* BuildID value is stored after the filename.  */
   1323   name = (char *) contents;
   1324   buildid_offset = strnlen (name, size) + 1;
   1325   if (buildid_offset >= bfd_section_size (sect))
   1326     return NULL;
   1327 
   1328   *buildid_len = size - buildid_offset;
   1329   *buildid_out = bfd_malloc (*buildid_len);
   1330   memcpy (*buildid_out, contents + buildid_offset, *buildid_len);
   1331 
   1332   return name;
   1333 }
   1334 
   1335 /* Checks to see if @var{name} is a file and if its contents match
   1336    @var{crc32}, which is a pointer to a @code{uint32_t}
   1337    containing a CRC32.
   1338 
   1339    The @var{crc32_p} parameter is an untyped pointer because this
   1340    routine is used as a @code{check_func_type} function.  */
   1341 
   1342 static bool
   1343 separate_debug_file_exists (const char *name, void *crc32_p)
   1344 {
   1345   unsigned char buffer[8 * 1024];
   1346   uint32_t file_crc = 0;
   1347   FILE *f;
   1348   bfd_size_type count;
   1349   uint32_t crc;
   1350 
   1351   BFD_ASSERT (name);
   1352   BFD_ASSERT (crc32_p);
   1353 
   1354   crc = *(uint32_t *) crc32_p;
   1355 
   1356   f = _bfd_real_fopen (name, FOPEN_RB);
   1357   if (f == NULL)
   1358     return false;
   1359 
   1360   while ((count = fread (buffer, 1, sizeof (buffer), f)) > 0)
   1361     file_crc = bfd_calc_gnu_debuglink_crc32 (file_crc, buffer, count);
   1362 
   1363   fclose (f);
   1364 
   1365   return crc == file_crc;
   1366 }
   1367 
   1368 /* Checks to see if @var{name} is a file.  */
   1369 
   1370 static bool
   1371 separate_alt_debug_file_exists (const char *name, void *unused ATTRIBUTE_UNUSED)
   1372 {
   1373   FILE *f;
   1374 
   1375   BFD_ASSERT (name);
   1376 
   1377   f = _bfd_real_fopen (name, FOPEN_RB);
   1378   if (f == NULL)
   1379     return false;
   1380 
   1381   fclose (f);
   1382 
   1383   return true;
   1384 }
   1385 
   1386 /* Searches for a debug information file corresponding to @var{abfd}.
   1387 
   1388    The name of the separate debug info file is returned by the
   1389    @var{get} function.  This function scans various fixed locations
   1390    in the filesystem, including the file tree rooted at @var{dir}.
   1391    If the @var{include_dirs} parameter is true then the directory
   1392    components of @var{abfd}'s filename will be included in the
   1393    searched locations.
   1394 
   1395    @var{data} is passed unmodified to the @var{get} and @var{check}
   1396    functions.  It is generally used to implement build-id-like
   1397    matching in the callback functions.
   1398 
   1399    Returns the filename of the first file to be found which
   1400    receives a TRUE result from the @var{check} function.
   1401    Returns NULL if no valid file could be found.  */
   1402 
   1403 typedef char * (*get_func_type) (bfd *, void *);
   1404 typedef bool (*check_func_type) (const char *, void *);
   1405 
   1406 static char *
   1407 find_separate_debug_file (bfd *abfd,
   1408 			  const char *debug_file_directory,
   1409 			  bool include_dirs,
   1410 			  get_func_type get_func,
   1411 			  check_func_type check_func,
   1412 			  void *func_data)
   1413 {
   1414   char *base;
   1415   char *dir;
   1416   char *debugfile;
   1417   char *canon_dir;
   1418   size_t dirlen;
   1419   size_t canon_dirlen;
   1420 
   1421   BFD_ASSERT (abfd);
   1422   if (debug_file_directory == NULL)
   1423     debug_file_directory = ".";
   1424 
   1425   /* BFD may have been opened from a stream.  */
   1426   if (bfd_get_filename (abfd) == NULL)
   1427     {
   1428       bfd_set_error (bfd_error_invalid_operation);
   1429       return NULL;
   1430     }
   1431 
   1432   base = get_func (abfd, func_data);
   1433 
   1434   if (base == NULL)
   1435     return NULL;
   1436 
   1437   if (base[0] == '\0')
   1438     {
   1439       free (base);
   1440       bfd_set_error (bfd_error_no_debug_section);
   1441       return NULL;
   1442     }
   1443 
   1444   if (include_dirs)
   1445     {
   1446       const char *fname = bfd_get_filename (abfd);
   1447       for (dirlen = strlen (fname); dirlen > 0; dirlen--)
   1448 	if (IS_DIR_SEPARATOR (fname[dirlen - 1]))
   1449 	  break;
   1450 
   1451       dir = (char *) bfd_malloc (dirlen + 1);
   1452       if (dir == NULL)
   1453 	{
   1454 	  free (base);
   1455 	  return NULL;
   1456 	}
   1457       memcpy (dir, fname, dirlen);
   1458       dir[dirlen] = '\0';
   1459     }
   1460   else
   1461     {
   1462       dir = (char *) bfd_malloc (1);
   1463       * dir = 0;
   1464       dirlen = 0;
   1465     }
   1466 
   1467   /* Compute the canonical name of the bfd object with all symbolic links
   1468      resolved, for use in the global debugfile directory.  */
   1469   canon_dir = lrealpath (bfd_get_filename (abfd));
   1470   for (canon_dirlen = strlen (canon_dir); canon_dirlen > 0; canon_dirlen--)
   1471     if (IS_DIR_SEPARATOR (canon_dir[canon_dirlen - 1]))
   1472       break;
   1473   canon_dir[canon_dirlen] = '\0';
   1474 
   1475 #ifndef EXTRA_DEBUG_ROOT1
   1476 #define EXTRA_DEBUG_ROOT1 "/usr/lib/debug"
   1477 #endif
   1478 #ifndef EXTRA_DEBUG_ROOT2
   1479 #define EXTRA_DEBUG_ROOT2 "/usr/lib/debug/usr"
   1480 #endif
   1481 
   1482   debugfile = (char *)
   1483       bfd_malloc (strlen (debug_file_directory) + 1
   1484 		  + (canon_dirlen > dirlen ? canon_dirlen : dirlen)
   1485 		  + strlen (".debug/")
   1486 #ifdef EXTRA_DEBUG_ROOT1
   1487 		  + strlen (EXTRA_DEBUG_ROOT1)
   1488 #endif
   1489 #ifdef EXTRA_DEBUG_ROOT2
   1490 		  + strlen (EXTRA_DEBUG_ROOT2)
   1491 #endif
   1492 		  + strlen (base)
   1493 		  + 1);
   1494   if (debugfile == NULL)
   1495     goto found; /* Actually this returns NULL.  */
   1496 
   1497   /* First try in the same directory as the original file.
   1498 
   1499      FIXME: Strictly speaking if we are using the build-id method,
   1500      (ie include_dirs == FALSE) then we should only check absolute
   1501      paths, not relative ones like this one (and the next one).
   1502      The check is left in however as this allows the binutils
   1503      testsuite to exercise this feature without having to install
   1504      a file into the root filesystem.  (See binutils/testsuite/
   1505      binutils-all/objdump.exp for the test).  */
   1506   sprintf (debugfile, "%s%s", dir, base);
   1507   if (check_func (debugfile, func_data))
   1508     goto found;
   1509 
   1510   /* Then try in a subdirectory called .debug.  */
   1511   sprintf (debugfile, "%s.debug/%s", dir, base);
   1512   if (check_func (debugfile, func_data))
   1513     goto found;
   1514 
   1515 #ifdef EXTRA_DEBUG_ROOT1
   1516   /* Try the first extra debug file root.  */
   1517   sprintf (debugfile, "%s%s%s", EXTRA_DEBUG_ROOT1,
   1518 	   include_dirs ? canon_dir : "/", base);
   1519   if (check_func (debugfile, func_data))
   1520     goto found;
   1521 #endif
   1522 
   1523 #ifdef EXTRA_DEBUG_ROOT2
   1524   /* Try the second extra debug file root.  */
   1525   sprintf (debugfile, "%s%s%s", EXTRA_DEBUG_ROOT2,
   1526 	   include_dirs ? canon_dir : "/", base);
   1527   if (check_func (debugfile, func_data))
   1528     goto found;
   1529 #endif
   1530 
   1531   /* Then try in the global debugfile directory.  */
   1532   strcpy (debugfile, debug_file_directory);
   1533   dirlen = strlen (debug_file_directory) - 1;
   1534   if (include_dirs)
   1535     {
   1536       if (dirlen > 0
   1537 	  && debug_file_directory[dirlen] != '/'
   1538 	  && canon_dir[0] != '/')
   1539 	strcat (debugfile, "/");
   1540       strcat (debugfile, canon_dir);
   1541     }
   1542   else
   1543     {
   1544       if (dirlen > 0 && debug_file_directory[dirlen] != '/')
   1545 	strcat (debugfile, "/");
   1546     }
   1547   strcat (debugfile, base);
   1548 
   1549   if (check_func (debugfile, func_data))
   1550     goto found;
   1551 
   1552   /* Failed to find the file.  */
   1553   free (debugfile);
   1554   debugfile = NULL;
   1555 
   1556  found:
   1557   free (base);
   1558   free (dir);
   1559   free (canon_dir);
   1560   return debugfile;
   1561 }
   1562 
   1563 /*
   1564 FUNCTION
   1565 	bfd_follow_gnu_debuglink
   1566 
   1567 SYNOPSIS
   1568 	char *bfd_follow_gnu_debuglink (bfd *abfd, const char *dir);
   1569 
   1570 DESCRIPTION
   1571 	Takes a BFD and searches it for a .gnu_debuglink section.  If this
   1572 	section is found, it examines the section for the name and checksum
   1573 	of a '.debug' file containing auxiliary debugging information.  It
   1574 	then searches the filesystem for this .debug file in some standard
   1575 	locations, including the directory tree rooted at @var{dir}, and if
   1576 	found returns the full filename.
   1577 
   1578 	If @var{dir} is NULL, the search will take place starting at
   1579 	the current directory.
   1580 
   1581 	Returns <<NULL>> on any errors or failure to locate the .debug
   1582 	file, otherwise a pointer to a heap-allocated string
   1583 	containing the filename.  The caller is responsible for
   1584 	freeing this string.
   1585 */
   1586 
   1587 char *
   1588 bfd_follow_gnu_debuglink (bfd *abfd, const char *dir)
   1589 {
   1590   uint32_t crc32;
   1591 
   1592   return find_separate_debug_file (abfd, dir, true,
   1593 				   bfd_get_debug_link_info_1,
   1594 				   separate_debug_file_exists, &crc32);
   1595 }
   1596 
   1597 /* Helper for bfd_follow_gnu_debugaltlink.  It just returns the name
   1598    of the separate debug file.  */
   1599 
   1600 static char *
   1601 get_alt_debug_link_info_shim (bfd * abfd, void *unused ATTRIBUTE_UNUSED)
   1602 {
   1603   bfd_size_type len;
   1604   bfd_byte *buildid = NULL;
   1605   char *result = bfd_get_alt_debug_link_info (abfd, &len, &buildid);
   1606 
   1607   free (buildid);
   1608 
   1609   return result;
   1610 }
   1611 
   1612 /*
   1613 FUNCTION
   1614 	bfd_follow_gnu_debugaltlink
   1615 
   1616 SYNOPSIS
   1617 	char *bfd_follow_gnu_debugaltlink (bfd *abfd, const char *dir);
   1618 
   1619 DESCRIPTION
   1620 	Takes a BFD and searches it for a .gnu_debugaltlink section.  If this
   1621 	section is found, it examines the section for the name of a file
   1622 	containing auxiliary debugging information.  It then searches the
   1623 	filesystem for this file in a set of standard locations, including
   1624 	the directory tree rooted at @var{dir}, and if found returns the
   1625 	full filename.
   1626 
   1627 	If @var{dir} is NULL, the search will take place starting at
   1628 	the current directory.
   1629 
   1630 	Returns <<NULL>> on any errors or failure to locate the debug
   1631 	file, otherwise a pointer to a heap-allocated string
   1632 	containing the filename.  The caller is responsible for
   1633 	freeing this string.
   1634 */
   1635 
   1636 char *
   1637 bfd_follow_gnu_debugaltlink (bfd *abfd, const char *dir)
   1638 {
   1639   return find_separate_debug_file (abfd, dir, true,
   1640 				   get_alt_debug_link_info_shim,
   1641 				   separate_alt_debug_file_exists,
   1642 				   NULL);
   1643 }
   1644 
   1645 /*
   1646 FUNCTION
   1647 	bfd_create_gnu_debuglink_section
   1648 
   1649 SYNOPSIS
   1650 	struct bfd_section *bfd_create_gnu_debuglink_section
   1651 	  (bfd *abfd, const char *filename);
   1652 
   1653 DESCRIPTION
   1654 	Takes a @var{BFD} and adds a .gnu_debuglink section to it.  The
   1655 	section is sized to be big enough to contain a link to the specified
   1656 	@var{filename}.
   1657 
   1658 	A pointer to the new section is returned if all is ok.  Otherwise
   1659 	<<NULL>> is returned and bfd_error is set.
   1660 */
   1661 
   1662 asection *
   1663 bfd_create_gnu_debuglink_section (bfd *abfd, const char *filename)
   1664 {
   1665   asection *sect;
   1666   bfd_size_type debuglink_size;
   1667   flagword flags;
   1668 
   1669   if (abfd == NULL || filename == NULL)
   1670     {
   1671       bfd_set_error (bfd_error_invalid_operation);
   1672       return NULL;
   1673     }
   1674 
   1675   /* Strip off any path components in filename.  */
   1676   filename = lbasename (filename);
   1677 
   1678   sect = bfd_get_section_by_name (abfd, GNU_DEBUGLINK);
   1679   if (sect)
   1680     {
   1681       /* Section already exists.  */
   1682       bfd_set_error (bfd_error_invalid_operation);
   1683       return NULL;
   1684     }
   1685 
   1686   flags = SEC_HAS_CONTENTS | SEC_READONLY | SEC_DEBUGGING;
   1687   sect = bfd_make_section_with_flags (abfd, GNU_DEBUGLINK, flags);
   1688   if (sect == NULL)
   1689     return NULL;
   1690 
   1691   /* Compute the size of the section.  Allow for the CRC after the filename,
   1692      and padding so that it will start on a 4-byte boundary.  */
   1693   debuglink_size = strlen (filename) + 1;
   1694   debuglink_size += 3;
   1695   debuglink_size &= ~3;
   1696   debuglink_size += 4;
   1697 
   1698   if (!bfd_set_section_size (sect, debuglink_size))
   1699     /* XXX Should we delete the section from the bfd ?  */
   1700     return NULL;
   1701 
   1702   /* PR 21193: Ensure that the section has 4-byte alignment for the CRC.
   1703      Note - despite the name of the function being called, we are
   1704      setting an alignment power, not a byte alignment value.  */
   1705   bfd_set_section_alignment (sect, 2);
   1706 
   1707   return sect;
   1708 }
   1709 
   1710 
   1711 /*
   1712 FUNCTION
   1713 	bfd_fill_in_gnu_debuglink_section
   1714 
   1715 SYNOPSIS
   1716 	bool bfd_fill_in_gnu_debuglink_section
   1717 	  (bfd *abfd, struct bfd_section *sect, const char *filename);
   1718 
   1719 DESCRIPTION
   1720 	Takes a @var{BFD} and containing a .gnu_debuglink section @var{SECT}
   1721 	and fills in the contents of the section to contain a link to the
   1722 	specified @var{filename}.  The filename should be absolute or
   1723 	relative to the current directory.
   1724 
   1725 	<<TRUE>> is returned if all is ok.  Otherwise <<FALSE>> is returned
   1726 	and bfd_error is set.
   1727 */
   1728 
   1729 bool
   1730 bfd_fill_in_gnu_debuglink_section (bfd *abfd,
   1731 				   struct bfd_section *sect,
   1732 				   const char *filename)
   1733 {
   1734   bfd_size_type debuglink_size;
   1735   uint32_t crc32;
   1736   char * contents;
   1737   bfd_size_type crc_offset;
   1738   FILE * handle;
   1739   unsigned char buffer[8 * 1024];
   1740   size_t count;
   1741   size_t filelen;
   1742 
   1743   if (abfd == NULL || sect == NULL || filename == NULL)
   1744     {
   1745       bfd_set_error (bfd_error_invalid_operation);
   1746       return false;
   1747     }
   1748 
   1749   /* Open the linked file so that we can compute a CRC.  */
   1750   handle = _bfd_real_fopen (filename, FOPEN_RB);
   1751   if (handle == NULL)
   1752     {
   1753       bfd_set_error (bfd_error_system_call);
   1754       return false;
   1755     }
   1756 
   1757   crc32 = 0;
   1758   while ((count = fread (buffer, 1, sizeof buffer, handle)) > 0)
   1759     crc32 = bfd_calc_gnu_debuglink_crc32 (crc32, buffer, count);
   1760   fclose (handle);
   1761 
   1762   /* Strip off any path components in filename,
   1763      now that we no longer need them.  */
   1764   filename = lbasename (filename);
   1765 
   1766   filelen = strlen (filename);
   1767   debuglink_size = filelen + 1;
   1768   debuglink_size += 3;
   1769   debuglink_size &= ~3;
   1770   debuglink_size += 4;
   1771 
   1772   contents = (char *) bfd_malloc (debuglink_size);
   1773   if (contents == NULL)
   1774     {
   1775       /* XXX Should we delete the section from the bfd ?  */
   1776       return false;
   1777     }
   1778 
   1779   crc_offset = debuglink_size - 4;
   1780   memcpy (contents, filename, filelen);
   1781   memset (contents + filelen, 0, crc_offset - filelen);
   1782 
   1783   bfd_put_32 (abfd, crc32, contents + crc_offset);
   1784 
   1785   if (! bfd_set_section_contents (abfd, sect, contents, 0, debuglink_size))
   1786     {
   1787       /* XXX Should we delete the section from the bfd ?  */
   1788       free (contents);
   1789       return false;
   1790     }
   1791 
   1792   return true;
   1793 }
   1794 
   1795 /* Finds the build-id associated with @var{abfd}.  If the build-id is
   1796    extracted from the note section then a build-id structure is built
   1797    for it, using memory allocated to @var{abfd}, and this is then
   1798    attached to the @var{abfd}.
   1799 
   1800    Returns a pointer to the build-id structure if a build-id could be
   1801    found.  If no build-id is found NULL is returned and error code is
   1802    set.  */
   1803 
   1804 static struct bfd_build_id *
   1805 get_build_id (bfd *abfd)
   1806 {
   1807   struct bfd_build_id *build_id;
   1808   Elf_Internal_Note inote;
   1809   Elf_External_Note *enote;
   1810   bfd_byte *contents;
   1811   asection *sect;
   1812   bfd_size_type size;
   1813 
   1814   BFD_ASSERT (abfd);
   1815 
   1816   if (abfd->build_id && abfd->build_id->size > 0)
   1817     /* Save some time by using the already computed build-id.  */
   1818     return (struct bfd_build_id *) abfd->build_id;
   1819 
   1820   sect = bfd_get_section_by_name (abfd, ".note.gnu.build-id");
   1821   if (sect == NULL
   1822       || (sect->flags & SEC_HAS_CONTENTS) == 0)
   1823     {
   1824       bfd_set_error (bfd_error_no_debug_section);
   1825       return NULL;
   1826     }
   1827 
   1828   size = bfd_section_size (sect);
   1829   /* FIXME: Should we support smaller build-id notes ?  */
   1830   if (size < 0x24)
   1831     {
   1832       bfd_set_error (bfd_error_invalid_operation);
   1833       return NULL;
   1834     }
   1835 
   1836   if (!bfd_malloc_and_get_section (abfd, sect, & contents))
   1837     return NULL;
   1838 
   1839   /* FIXME: Paranoia - allow for compressed build-id sections.
   1840      Maybe we should complain if this size is different from
   1841      the one obtained above...  */
   1842   size = bfd_section_size (sect);
   1843   if (size < sizeof (Elf_External_Note))
   1844     {
   1845       bfd_set_error (bfd_error_invalid_operation);
   1846       free (contents);
   1847       return NULL;
   1848     }
   1849 
   1850   enote = (Elf_External_Note *) contents;
   1851   inote.type = H_GET_32 (abfd, enote->type);
   1852   inote.namesz = H_GET_32 (abfd, enote->namesz);
   1853   inote.namedata = enote->name;
   1854   inote.descsz = H_GET_32 (abfd, enote->descsz);
   1855   inote.descdata = inote.namedata + BFD_ALIGN (inote.namesz, 4);
   1856   /* FIXME: Should we check for extra notes in this section ?  */
   1857 
   1858   if (inote.descsz <= 0
   1859       || inote.type != NT_GNU_BUILD_ID
   1860       || inote.namesz != 4 /* sizeof "GNU"  */
   1861       || !startswith (inote.namedata, "GNU")
   1862       || inote.descsz > 0x7ffffffe
   1863       || size < (12 + BFD_ALIGN (inote.namesz, 4) + inote.descsz))
   1864     {
   1865       free (contents);
   1866       bfd_set_error (bfd_error_invalid_operation);
   1867       return NULL;
   1868     }
   1869 
   1870   build_id = bfd_alloc (abfd, sizeof (struct bfd_build_id) + inote.descsz);
   1871   if (build_id == NULL)
   1872     {
   1873       free (contents);
   1874       return NULL;
   1875     }
   1876 
   1877   build_id->size = inote.descsz;
   1878   memcpy (build_id->data, inote.descdata, inote.descsz);
   1879   abfd->build_id = build_id;
   1880   free (contents);
   1881 
   1882   return build_id;
   1883 }
   1884 
   1885 /* Searches @var{abfd} for a build-id, and then constructs a pathname
   1886    from it.  The path is computed as .build-id/NN/NN+NN.debug where
   1887    NNNN+NN is the build-id value as a hexadecimal string.
   1888 
   1889    Returns the constructed filename or NULL upon error.  It is the
   1890    caller's responsibility to free the memory used to hold the
   1891    filename.  If a filename is returned then the @var{build_id_out_p}
   1892    parameter (which points to a @code{struct bfd_build_id} pointer) is
   1893    set to a pointer to the build_id structure.  */
   1894 
   1895 static char *
   1896 get_build_id_name (bfd *abfd, void *build_id_out_p)
   1897 {
   1898   struct bfd_build_id **build_id_out = build_id_out_p;
   1899   struct bfd_build_id *build_id;
   1900   char *name;
   1901   char *n;
   1902   bfd_size_type s;
   1903   bfd_byte *d;
   1904 
   1905   if (abfd == NULL || bfd_get_filename (abfd) == NULL || build_id_out == NULL)
   1906     {
   1907       bfd_set_error (bfd_error_invalid_operation);
   1908       return NULL;
   1909     }
   1910 
   1911   build_id = get_build_id (abfd);
   1912   if (build_id == NULL)
   1913     return NULL;
   1914 
   1915   /* Compute the debug pathname corresponding to the build-id.  */
   1916   name = bfd_malloc (strlen (".build-id/") + build_id->size * 2 + 2 + strlen (".debug"));
   1917   if (name == NULL)
   1918     {
   1919       bfd_set_error (bfd_error_no_memory);
   1920       return NULL;
   1921     }
   1922   n = name;
   1923   d = build_id->data;
   1924   s = build_id->size;
   1925 
   1926   n += sprintf (n, ".build-id/");
   1927   n += sprintf (n, "%02x", (unsigned) *d++); s--;
   1928   n += sprintf (n, "/");
   1929   while (s--)
   1930     n += sprintf (n, "%02x", (unsigned) *d++);
   1931   n += sprintf (n, ".debug");
   1932 
   1933   *build_id_out = build_id;
   1934   return name;
   1935 }
   1936 
   1937 /* Checks to see if @var{name} is a readable file and if its build-id
   1938    matches @var{buildid}.
   1939 
   1940    Returns TRUE if the file exists, is readable, and contains a
   1941    build-id which matches the build-id pointed at by @var{build_id_p}
   1942    (which is really a @code{struct bfd_build_id **}).  */
   1943 
   1944 static bool
   1945 check_build_id_file (const char *name, void *buildid_p)
   1946 {
   1947   struct bfd_build_id *orig_build_id;
   1948   struct bfd_build_id *build_id;
   1949   bfd * file;
   1950   bool result;
   1951 
   1952   BFD_ASSERT (name);
   1953   BFD_ASSERT (buildid_p);
   1954 
   1955   file = bfd_openr (name, NULL);
   1956   if (file == NULL)
   1957     return false;
   1958 
   1959   /* If the file is an archive, process all of its elements.  */
   1960   if (! bfd_check_format (file, bfd_object))
   1961     {
   1962       bfd_close (file);
   1963       return false;
   1964     }
   1965 
   1966   build_id = get_build_id (file);
   1967   if (build_id == NULL)
   1968     {
   1969       bfd_close (file);
   1970       return false;
   1971     }
   1972 
   1973   orig_build_id = *(struct bfd_build_id **) buildid_p;
   1974 
   1975   result = build_id->size == orig_build_id->size
   1976     && memcmp (build_id->data, orig_build_id->data, build_id->size) == 0;
   1977 
   1978   (void) bfd_close (file);
   1979 
   1980   return result;
   1981 }
   1982 
   1983 /*
   1984 FUNCTION
   1985 	bfd_follow_build_id_debuglink
   1986 
   1987 SYNOPSIS
   1988 	char *bfd_follow_build_id_debuglink (bfd *abfd, const char *dir);
   1989 
   1990 DESCRIPTION
   1991 	Takes @var{abfd} and searches it for a .note.gnu.build-id section.
   1992 	If this section is found, it extracts the value of the NT_GNU_BUILD_ID
   1993 	note, which should be a hexadecimal value @var{NNNN+NN} (for
   1994 	32+ hex digits).  It then searches the filesystem for a file named
   1995 	@var{.build-id/NN/NN+NN.debug} in a set of standard locations,
   1996 	including the directory tree rooted at @var{dir}.  The filename
   1997 	of the first matching file to be found is returned.  A matching
   1998 	file should contain a .note.gnu.build-id section with the same
   1999 	@var{NNNN+NN} note as @var{abfd}, although this check is currently
   2000 	not implemented.
   2001 
   2002 	If @var{dir} is NULL, the search will take place starting at
   2003 	the current directory.
   2004 
   2005 	Returns <<NULL>> on any errors or failure to locate the debug
   2006 	file, otherwise a pointer to a heap-allocated string
   2007 	containing the filename.  The caller is responsible for
   2008 	freeing this string.
   2009 */
   2010 
   2011 char *
   2012 bfd_follow_build_id_debuglink (bfd *abfd, const char *dir)
   2013 {
   2014   struct bfd_build_id *build_id;
   2015 
   2016   return find_separate_debug_file (abfd, dir, false,
   2017 				   get_build_id_name,
   2018 				   check_build_id_file, &build_id);
   2019 }
   2020 
   2021 /*
   2022 FUNCTION
   2023 	bfd_set_filename
   2024 
   2025 SYNOPSIS
   2026 	const char *bfd_set_filename (bfd *abfd, const char *filename);
   2027 
   2028 DESCRIPTION
   2029 	Set the filename of @var{abfd}, copying the FILENAME parameter to
   2030 	bfd_alloc'd memory owned by @var{abfd}.  Returns a pointer the
   2031 	newly allocated name, or NULL if the allocation failed.
   2032 */
   2033 
   2034 const char *
   2035 bfd_set_filename (bfd *abfd, const char *filename)
   2036 {
   2037   size_t len = strlen (filename) + 1;
   2038   char *n = bfd_alloc (abfd, len);
   2039 
   2040   if (n == NULL)
   2041     return NULL;
   2042 
   2043   if (abfd->filename != NULL)
   2044     {
   2045       /* PR 29389.  If we attempt to rename a file that has been closed due
   2046 	 to caching, then we will not be able to reopen it later on.  */
   2047       if (abfd->iostream == NULL && (abfd->flags & BFD_CLOSED_BY_CACHE))
   2048 	{
   2049 	  bfd_set_error (bfd_error_invalid_operation);
   2050 	  return NULL;
   2051 	}
   2052 
   2053       /* Similarly if we attempt to close a renamed file because the
   2054 	 cache is now full, we will not be able to reopen it later on.  */
   2055       if (abfd->iostream != NULL)
   2056 	abfd->cacheable = 0;
   2057     }
   2058 
   2059   memcpy (n, filename, len);
   2060   abfd->filename = n;
   2061 
   2062   return n;
   2063 }
   2064