Tidy bfdio to consistenly use containing archive
[external/binutils.git] / bfd / bfdio.c
1 /* Low-level I/O routines for BFDs.
2
3    Copyright (C) 1990-2018 Free Software Foundation, Inc.
4
5    Written by Cygnus Support.
6
7    This file is part of BFD, the Binary File Descriptor library.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22    MA 02110-1301, USA.  */
23
24 #include "sysdep.h"
25 #include <limits.h>
26 #include "bfd.h"
27 #include "libbfd.h"
28
29 #ifndef S_IXUSR
30 #define S_IXUSR 0100    /* Execute by owner.  */
31 #endif
32 #ifndef S_IXGRP
33 #define S_IXGRP 0010    /* Execute by group.  */
34 #endif
35 #ifndef S_IXOTH
36 #define S_IXOTH 0001    /* Execute by others.  */
37 #endif
38
39 #ifndef FD_CLOEXEC
40 #define FD_CLOEXEC 1
41 #endif
42
43 file_ptr
44 _bfd_real_ftell (FILE *file)
45 {
46 #if defined (HAVE_FTELLO64)
47   return ftello64 (file);
48 #elif defined (HAVE_FTELLO)
49   return ftello (file);
50 #else
51   return ftell (file);
52 #endif
53 }
54
55 int
56 _bfd_real_fseek (FILE *file, file_ptr offset, int whence)
57 {
58 #if defined (HAVE_FSEEKO64)
59   return fseeko64 (file, offset, whence);
60 #elif defined (HAVE_FSEEKO)
61   return fseeko (file, offset, whence);
62 #else
63   return fseek (file, offset, whence);
64 #endif
65 }
66
67 /* Mark FILE as close-on-exec.  Return FILE.  FILE may be NULL, in
68    which case nothing is done.  */
69 static FILE *
70 close_on_exec (FILE *file)
71 {
72 #if defined (HAVE_FILENO) && defined (F_GETFD)
73   if (file)
74     {
75       int fd = fileno (file);
76       int old = fcntl (fd, F_GETFD, 0);
77       if (old >= 0)
78         fcntl (fd, F_SETFD, old | FD_CLOEXEC);
79     }
80 #endif
81   return file;
82 }
83
84 FILE *
85 _bfd_real_fopen (const char *filename, const char *modes)
86 {
87 #ifdef VMS
88   char *vms_attr;
89
90   /* On VMS, fopen allows file attributes as optional arguments.
91      We need to use them but we'd better to use the common prototype.
92      In fopen-vms.h, they are separated from the mode with a comma.
93      Split here.  */
94   vms_attr = strchr (modes, ',');
95   if (vms_attr == NULL)
96     {
97       /* No attributes.  */
98       return close_on_exec (fopen (filename, modes));
99     }
100   else
101     {
102       /* Attributes found.  Split.  */
103       size_t modes_len = strlen (modes) + 1;
104       char attrs[modes_len + 1];
105       char *at[3];
106       int i;
107
108       memcpy (attrs, modes, modes_len);
109       at[0] = attrs;
110       for (i = 0; i < 2; i++)
111         {
112           at[i + 1] = strchr (at[i], ',');
113           BFD_ASSERT (at[i + 1] != NULL);
114           *(at[i + 1]++) = 0; /* Replace ',' with a nul, and skip it.  */
115         }
116       return close_on_exec (fopen (filename, at[0], at[1], at[2]));
117     }
118 #else /* !VMS */
119 #if defined (HAVE_FOPEN64)
120   return close_on_exec (fopen64 (filename, modes));
121 #else
122   return close_on_exec (fopen (filename, modes));
123 #endif
124 #endif /* !VMS */
125 }
126
127 /*
128 INTERNAL_DEFINITION
129         struct bfd_iovec
130
131 DESCRIPTION
132
133         The <<struct bfd_iovec>> contains the internal file I/O class.
134         Each <<BFD>> has an instance of this class and all file I/O is
135         routed through it (it is assumed that the instance implements
136         all methods listed below).
137
138 .struct bfd_iovec
139 .{
140 .  {* To avoid problems with macros, a "b" rather than "f"
141 .     prefix is prepended to each method name.  *}
142 .  {* Attempt to read/write NBYTES on ABFD's IOSTREAM storing/fetching
143 .     bytes starting at PTR.  Return the number of bytes actually
144 .     transfered (a read past end-of-file returns less than NBYTES),
145 .     or -1 (setting <<bfd_error>>) if an error occurs.  *}
146 .  file_ptr (*bread) (struct bfd *abfd, void *ptr, file_ptr nbytes);
147 .  file_ptr (*bwrite) (struct bfd *abfd, const void *ptr,
148 .                      file_ptr nbytes);
149 .  {* Return the current IOSTREAM file offset, or -1 (setting <<bfd_error>>
150 .     if an error occurs.  *}
151 .  file_ptr (*btell) (struct bfd *abfd);
152 .  {* For the following, on successful completion a value of 0 is returned.
153 .     Otherwise, a value of -1 is returned (and <<bfd_error>> is set).  *}
154 .  int (*bseek) (struct bfd *abfd, file_ptr offset, int whence);
155 .  int (*bclose) (struct bfd *abfd);
156 .  int (*bflush) (struct bfd *abfd);
157 .  int (*bstat) (struct bfd *abfd, struct stat *sb);
158 .  {* Mmap a part of the files. ADDR, LEN, PROT, FLAGS and OFFSET are the usual
159 .     mmap parameter, except that LEN and OFFSET do not need to be page
160 .     aligned.  Returns (void *)-1 on failure, mmapped address on success.
161 .     Also write in MAP_ADDR the address of the page aligned buffer and in
162 .     MAP_LEN the size mapped (a page multiple).  Use unmap with MAP_ADDR and
163 .     MAP_LEN to unmap.  *}
164 .  void *(*bmmap) (struct bfd *abfd, void *addr, bfd_size_type len,
165 .                  int prot, int flags, file_ptr offset,
166 .                  void **map_addr, bfd_size_type *map_len);
167 .};
168
169 .extern const struct bfd_iovec _bfd_memory_iovec;
170
171 */
172
173
174 /* Return value is amount read.  */
175
176 bfd_size_type
177 bfd_bread (void *ptr, bfd_size_type size, bfd *abfd)
178 {
179   file_ptr nread;
180   bfd *element_bfd = abfd;
181   ufile_ptr offset = 0;
182
183   while (abfd->my_archive != NULL
184          && !bfd_is_thin_archive (abfd->my_archive))
185     {
186       offset += abfd->origin;
187       abfd = abfd->my_archive;
188     }
189
190   /* If this is an archive element, don't read past the end of
191      this element.  */
192   if (element_bfd->arelt_data != NULL)
193     {
194       bfd_size_type maxbytes = arelt_size (element_bfd);
195
196       if (abfd->where < offset || abfd->where - offset >= maxbytes)
197         {
198           bfd_set_error (bfd_error_invalid_operation);
199           return -1;
200         }
201       if (abfd->where - offset + size > maxbytes)
202         size = maxbytes - (abfd->where - offset);
203     }
204
205   if (abfd->iovec == NULL)
206     {
207       bfd_set_error (bfd_error_invalid_operation);
208       return -1;
209     }
210
211   nread = abfd->iovec->bread (abfd, ptr, size);
212   if (nread != -1)
213     abfd->where += nread;
214
215   return nread;
216 }
217
218 bfd_size_type
219 bfd_bwrite (const void *ptr, bfd_size_type size, bfd *abfd)
220 {
221   file_ptr nwrote;
222
223   while (abfd->my_archive != NULL
224          && !bfd_is_thin_archive (abfd->my_archive))
225     abfd = abfd->my_archive;
226
227   if (abfd->iovec == NULL)
228     {
229       bfd_set_error (bfd_error_invalid_operation);
230       return -1;
231     }
232
233   nwrote = abfd->iovec->bwrite (abfd, ptr, size);
234   if (nwrote != -1)
235     abfd->where += nwrote;
236   if ((bfd_size_type) nwrote != size)
237     {
238 #ifdef ENOSPC
239       errno = ENOSPC;
240 #endif
241       bfd_set_error (bfd_error_system_call);
242     }
243   return nwrote;
244 }
245
246 file_ptr
247 bfd_tell (bfd *abfd)
248 {
249   ufile_ptr offset = 0;
250   file_ptr ptr;
251
252   while (abfd->my_archive != NULL
253          && !bfd_is_thin_archive (abfd->my_archive))
254     {
255       offset += abfd->origin;
256       abfd = abfd->my_archive;
257     }
258
259   if (abfd->iovec == NULL)
260     return 0;
261
262   ptr = abfd->iovec->btell (abfd);
263   abfd->where = ptr;
264   return ptr - offset;
265 }
266
267 int
268 bfd_flush (bfd *abfd)
269 {
270   while (abfd->my_archive != NULL
271          && !bfd_is_thin_archive (abfd->my_archive))
272     abfd = abfd->my_archive;
273
274   if (abfd->iovec == NULL)
275     return 0;
276
277   return abfd->iovec->bflush (abfd);
278 }
279
280 /* Returns 0 for success, negative value for failure (in which case
281    bfd_get_error can retrieve the error code).  */
282 int
283 bfd_stat (bfd *abfd, struct stat *statbuf)
284 {
285   int result;
286
287   while (abfd->my_archive != NULL
288          && !bfd_is_thin_archive (abfd->my_archive))
289     abfd = abfd->my_archive;
290
291   if (abfd->iovec == NULL)
292     {
293       bfd_set_error (bfd_error_invalid_operation);
294       return -1;
295     }
296
297   result = abfd->iovec->bstat (abfd, statbuf);
298   if (result < 0)
299     bfd_set_error (bfd_error_system_call);
300   return result;
301 }
302
303 /* Returns 0 for success, nonzero for failure (in which case bfd_get_error
304    can retrieve the error code).  */
305
306 int
307 bfd_seek (bfd *abfd, file_ptr position, int direction)
308 {
309   int result;
310   ufile_ptr offset = 0;
311
312   while (abfd->my_archive != NULL
313          && !bfd_is_thin_archive (abfd->my_archive))
314     {
315       offset += abfd->origin;
316       abfd = abfd->my_archive;
317     }
318
319   if (abfd->iovec == NULL)
320     {
321       bfd_set_error (bfd_error_invalid_operation);
322       return -1;
323     }
324
325   /* For the time being, a BFD may not seek to it's end.  The problem
326      is that we don't easily have a way to recognize the end of an
327      element in an archive.  */
328   BFD_ASSERT (direction == SEEK_SET || direction == SEEK_CUR);
329
330   if (direction != SEEK_CUR)
331     position += offset;
332
333   result = abfd->iovec->bseek (abfd, position, direction);
334   if (result != 0)
335     {
336       /* An EINVAL error probably means that the file offset was
337          absurd.  */
338       if (errno == EINVAL)
339         bfd_set_error (bfd_error_file_truncated);
340       else
341         bfd_set_error (bfd_error_system_call);
342     }
343   else
344     {
345       /* Adjust `where' field.  */
346       if (direction == SEEK_CUR)
347         abfd->where += position;
348       else
349         abfd->where = position;
350     }
351
352   return result;
353 }
354
355 /*
356 FUNCTION
357         bfd_get_mtime
358
359 SYNOPSIS
360         long bfd_get_mtime (bfd *abfd);
361
362 DESCRIPTION
363         Return the file modification time (as read from the file system, or
364         from the archive header for archive members).
365
366 */
367
368 long
369 bfd_get_mtime (bfd *abfd)
370 {
371   struct stat buf;
372
373   if (abfd->mtime_set)
374     return abfd->mtime;
375
376   if (bfd_stat (abfd, &buf) != 0)
377     return 0;
378
379   abfd->mtime = buf.st_mtime;           /* Save value in case anyone wants it */
380   return buf.st_mtime;
381 }
382
383 /*
384 FUNCTION
385         bfd_get_size
386
387 SYNOPSIS
388         ufile_ptr bfd_get_size (bfd *abfd);
389
390 DESCRIPTION
391         Return the file size (as read from file system) for the file
392         associated with BFD @var{abfd}.
393
394         The initial motivation for, and use of, this routine is not
395         so we can get the exact size of the object the BFD applies to, since
396         that might not be generally possible (archive members for example).
397         It would be ideal if someone could eventually modify
398         it so that such results were guaranteed.
399
400         Instead, we want to ask questions like "is this NNN byte sized
401         object I'm about to try read from file offset YYY reasonable?"
402         As as example of where we might do this, some object formats
403         use string tables for which the first <<sizeof (long)>> bytes of the
404         table contain the size of the table itself, including the size bytes.
405         If an application tries to read what it thinks is one of these
406         string tables, without some way to validate the size, and for
407         some reason the size is wrong (byte swapping error, wrong location
408         for the string table, etc.), the only clue is likely to be a read
409         error when it tries to read the table, or a "virtual memory
410         exhausted" error when it tries to allocate 15 bazillon bytes
411         of space for the 15 bazillon byte table it is about to read.
412         This function at least allows us to answer the question, "is the
413         size reasonable?".
414 */
415
416 ufile_ptr
417 bfd_get_size (bfd *abfd)
418 {
419   struct stat buf;
420
421   if (bfd_stat (abfd, &buf) != 0)
422     return 0;
423
424   return buf.st_size;
425 }
426
427 /*
428 FUNCTION
429         bfd_get_file_size
430
431 SYNOPSIS
432         ufile_ptr bfd_get_file_size (bfd *abfd);
433
434 DESCRIPTION
435         Return the file size (as read from file system) for the file
436         associated with BFD @var{abfd}.  It supports both normal files
437         and archive elements.
438
439 */
440
441 ufile_ptr
442 bfd_get_file_size (bfd *abfd)
443 {
444   if (abfd->my_archive != NULL
445       && !bfd_is_thin_archive (abfd->my_archive))
446     return arelt_size (abfd);
447
448   return bfd_get_size (abfd);
449 }
450
451 /*
452 FUNCTION
453         bfd_mmap
454
455 SYNOPSIS
456         void *bfd_mmap (bfd *abfd, void *addr, bfd_size_type len,
457                         int prot, int flags, file_ptr offset,
458                         void **map_addr, bfd_size_type *map_len);
459
460 DESCRIPTION
461         Return mmap()ed region of the file, if possible and implemented.
462         LEN and OFFSET do not need to be page aligned.  The page aligned
463         address and length are written to MAP_ADDR and MAP_LEN.
464
465 */
466
467 void *
468 bfd_mmap (bfd *abfd, void *addr, bfd_size_type len,
469           int prot, int flags, file_ptr offset,
470           void **map_addr, bfd_size_type *map_len)
471 {
472   while (abfd->my_archive != NULL
473          && !bfd_is_thin_archive (abfd->my_archive))
474     {
475       offset += abfd->origin;
476       abfd = abfd->my_archive;
477     }
478
479   if (abfd->iovec == NULL)
480     {
481       bfd_set_error (bfd_error_invalid_operation);
482       return (void *) -1;
483     }
484
485   return abfd->iovec->bmmap (abfd, addr, len, prot, flags, offset,
486                              map_addr, map_len);
487 }
488
489 /* Memory file I/O operations.  */
490
491 static file_ptr
492 memory_bread (bfd *abfd, void *ptr, file_ptr size)
493 {
494   struct bfd_in_memory *bim;
495   bfd_size_type get;
496
497   bim = (struct bfd_in_memory *) abfd->iostream;
498   get = size;
499   if (abfd->where + get > bim->size)
500     {
501       if (bim->size < (bfd_size_type) abfd->where)
502         get = 0;
503       else
504         get = bim->size - abfd->where;
505       bfd_set_error (bfd_error_file_truncated);
506     }
507   memcpy (ptr, bim->buffer + abfd->where, (size_t) get);
508   return get;
509 }
510
511 static file_ptr
512 memory_bwrite (bfd *abfd, const void *ptr, file_ptr size)
513 {
514   struct bfd_in_memory *bim = (struct bfd_in_memory *) abfd->iostream;
515
516   if (abfd->where + size > bim->size)
517     {
518       bfd_size_type newsize, oldsize;
519
520       oldsize = (bim->size + 127) & ~(bfd_size_type) 127;
521       bim->size = abfd->where + size;
522       /* Round up to cut down on memory fragmentation */
523       newsize = (bim->size + 127) & ~(bfd_size_type) 127;
524       if (newsize > oldsize)
525         {
526           bim->buffer = (bfd_byte *) bfd_realloc_or_free (bim->buffer, newsize);
527           if (bim->buffer == NULL)
528             {
529               bim->size = 0;
530               return 0;
531             }
532           if (newsize > bim->size)
533             memset (bim->buffer + bim->size, 0, newsize - bim->size);
534         }
535     }
536   memcpy (bim->buffer + abfd->where, ptr, (size_t) size);
537   return size;
538 }
539
540 static file_ptr
541 memory_btell (bfd *abfd)
542 {
543   return abfd->where;
544 }
545
546 static int
547 memory_bseek (bfd *abfd, file_ptr position, int direction)
548 {
549   file_ptr nwhere;
550   struct bfd_in_memory *bim;
551
552   bim = (struct bfd_in_memory *) abfd->iostream;
553
554   if (direction == SEEK_SET)
555     nwhere = position;
556   else
557     nwhere = abfd->where + position;
558
559   if (nwhere < 0)
560     {
561       abfd->where = 0;
562       errno = EINVAL;
563       return -1;
564     }
565
566   if ((bfd_size_type)nwhere > bim->size)
567     {
568       if (abfd->direction == write_direction
569           || abfd->direction == both_direction)
570         {
571           bfd_size_type newsize, oldsize;
572
573           oldsize = (bim->size + 127) & ~(bfd_size_type) 127;
574           bim->size = nwhere;
575           /* Round up to cut down on memory fragmentation */
576           newsize = (bim->size + 127) & ~(bfd_size_type) 127;
577           if (newsize > oldsize)
578             {
579               bim->buffer = (bfd_byte *) bfd_realloc_or_free (bim->buffer, newsize);
580               if (bim->buffer == NULL)
581                 {
582                   errno = EINVAL;
583                   bim->size = 0;
584                   return -1;
585                 }
586               memset (bim->buffer + oldsize, 0, newsize - oldsize);
587             }
588         }
589       else
590         {
591           abfd->where = bim->size;
592           errno = EINVAL;
593           bfd_set_error (bfd_error_file_truncated);
594           return -1;
595         }
596     }
597   return 0;
598 }
599
600 static int
601 memory_bclose (struct bfd *abfd)
602 {
603   struct bfd_in_memory *bim = (struct bfd_in_memory *) abfd->iostream;
604
605   if (bim->buffer != NULL)
606     free (bim->buffer);
607   free (bim);
608   abfd->iostream = NULL;
609
610   return 0;
611 }
612
613 static int
614 memory_bflush (bfd *abfd ATTRIBUTE_UNUSED)
615 {
616   return 0;
617 }
618
619 static int
620 memory_bstat (bfd *abfd, struct stat *statbuf)
621 {
622   struct bfd_in_memory *bim = (struct bfd_in_memory *) abfd->iostream;
623
624   memset (statbuf, 0, sizeof (*statbuf));
625   statbuf->st_size = bim->size;
626
627   return 0;
628 }
629
630 static void *
631 memory_bmmap (bfd *abfd ATTRIBUTE_UNUSED, void *addr ATTRIBUTE_UNUSED,
632               bfd_size_type len ATTRIBUTE_UNUSED, int prot ATTRIBUTE_UNUSED,
633               int flags ATTRIBUTE_UNUSED, file_ptr offset ATTRIBUTE_UNUSED,
634               void **map_addr ATTRIBUTE_UNUSED,
635               bfd_size_type *map_len ATTRIBUTE_UNUSED)
636 {
637   return (void *)-1;
638 }
639
640 const struct bfd_iovec _bfd_memory_iovec =
641 {
642   &memory_bread, &memory_bwrite, &memory_btell, &memory_bseek,
643   &memory_bclose, &memory_bflush, &memory_bstat, &memory_bmmap
644 };