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