Merge branch 'vendor/BZIP'
[dragonfly.git] / contrib / binutils-2.17 / bfd / cache.c
1 /* BFD library -- caching of file descriptors.
2
3    Copyright 1990, 1991, 1992, 1993, 1994, 1996, 2000, 2001, 2002,
4    2003, 2004, 2005 Free Software Foundation, Inc.
5
6    Hacked by Steve Chamberlain of Cygnus Support (steve@cygnus.com).
7
8 This file is part of BFD, the Binary File Descriptor library.
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
23
24 /*
25 SECTION
26         File caching
27
28         The file caching mechanism is embedded within BFD and allows
29         the application to open as many BFDs as it wants without
30         regard to the underlying operating system's file descriptor
31         limit (often as low as 20 open files).  The module in
32         <<cache.c>> maintains a least recently used list of
33         <<BFD_CACHE_MAX_OPEN>> files, and exports the name
34         <<bfd_cache_lookup>>, which runs around and makes sure that
35         the required BFD is open. If not, then it chooses a file to
36         close, closes it and opens the one wanted, returning its file
37         handle.
38
39 SUBSECTION
40         Caching functions
41 */
42
43 #include "bfd.h"
44 #include "sysdep.h"
45 #include "libbfd.h"
46 #include "libiberty.h"
47
48 /* In some cases we can optimize cache operation when reopening files.
49    For instance, a flush is entirely unnecessary if the file is already
50    closed, so a flush would use CACHE_NO_OPEN.  Similarly, a seek using
51    SEEK_SET or SEEK_END need not first seek to the current position.
52    For stat we ignore seek errors, just in case the file has changed
53    while we weren't looking.  If it has, then it's possible that the
54    file is shorter and we don't want a seek error to prevent us doing
55    the stat.  */
56 enum cache_flag {
57   CACHE_NORMAL = 0,
58   CACHE_NO_OPEN = 1,
59   CACHE_NO_SEEK = 2,
60   CACHE_NO_SEEK_ERROR = 4
61 };
62
63 /* The maximum number of files which the cache will keep open at
64    one time.  */
65
66 #define BFD_CACHE_MAX_OPEN 10
67
68 /* The number of BFD files we have open.  */
69
70 static int open_files;
71
72 /* Zero, or a pointer to the topmost BFD on the chain.  This is
73    used by the <<bfd_cache_lookup>> macro in @file{libbfd.h} to
74    determine when it can avoid a function call.  */
75
76 static bfd *bfd_last_cache = NULL;
77
78 /* Insert a BFD into the cache.  */
79
80 static void
81 insert (bfd *abfd)
82 {
83   if (bfd_last_cache == NULL)
84     {
85       abfd->lru_next = abfd;
86       abfd->lru_prev = abfd;
87     }
88   else
89     {
90       abfd->lru_next = bfd_last_cache;
91       abfd->lru_prev = bfd_last_cache->lru_prev;
92       abfd->lru_prev->lru_next = abfd;
93       abfd->lru_next->lru_prev = abfd;
94     }
95   bfd_last_cache = abfd;
96 }
97
98 /* Remove a BFD from the cache.  */
99
100 static void
101 snip (bfd *abfd)
102 {
103   abfd->lru_prev->lru_next = abfd->lru_next;
104   abfd->lru_next->lru_prev = abfd->lru_prev;
105   if (abfd == bfd_last_cache)
106     {
107       bfd_last_cache = abfd->lru_next;
108       if (abfd == bfd_last_cache)
109         bfd_last_cache = NULL;
110     }
111 }
112
113 /* Close a BFD and remove it from the cache.  */
114
115 static bfd_boolean
116 bfd_cache_delete (bfd *abfd)
117 {
118   bfd_boolean ret;
119
120   if (fclose ((FILE *) abfd->iostream) == 0)
121     ret = TRUE;
122   else
123     {
124       ret = FALSE;
125       bfd_set_error (bfd_error_system_call);
126     }
127
128   snip (abfd);
129
130   abfd->iostream = NULL;
131   --open_files;
132
133   return ret;
134 }
135
136 /* We need to open a new file, and the cache is full.  Find the least
137    recently used cacheable BFD and close it.  */
138
139 static bfd_boolean
140 close_one (void)
141 {
142   register bfd *kill;
143
144   if (bfd_last_cache == NULL)
145     kill = NULL;
146   else
147     {
148       for (kill = bfd_last_cache->lru_prev;
149            ! kill->cacheable;
150            kill = kill->lru_prev)
151         {
152           if (kill == bfd_last_cache)
153             {
154               kill = NULL;
155               break;
156             }
157         }
158     }
159
160   if (kill == NULL)
161     {
162       /* There are no open cacheable BFD's.  */
163       return TRUE;
164     }
165
166   kill->where = real_ftell ((FILE *) kill->iostream);
167
168   /* Save the file st_mtime.  This is a hack so that gdb can detect when
169      an executable has been deleted and recreated.  The only thing that
170      makes this reasonable is that st_mtime doesn't change when a file
171      is unlinked, so saving st_mtime makes BFD's file cache operation
172      a little more transparent for this particular usage pattern.  If we
173      hadn't closed the file then we would not have lost the original
174      contents, st_mtime etc.  Of course, if something is writing to an
175      existing file, then this is the wrong thing to do.
176      FIXME: gdb should save these times itself on first opening a file,
177      and this hack be removed.  */
178   if (kill->direction == no_direction || kill->direction == read_direction)
179     {
180       bfd_get_mtime (kill);
181       kill->mtime_set = TRUE;
182     }
183
184   return bfd_cache_delete (kill);
185 }
186
187 /* Check to see if the required BFD is the same as the last one
188    looked up. If so, then it can use the stream in the BFD with
189    impunity, since it can't have changed since the last lookup;
190    otherwise, it has to perform the complicated lookup function.  */
191
192 #define bfd_cache_lookup(x, flag) \
193   ((x) == bfd_last_cache                        \
194    ? (FILE *) (bfd_last_cache->iostream)        \
195    : bfd_cache_lookup_worker (x, flag))
196
197 /* Called when the macro <<bfd_cache_lookup>> fails to find a
198    quick answer.  Find a file descriptor for @var{abfd}.  If
199    necessary, it open it.  If there are already more than
200    <<BFD_CACHE_MAX_OPEN>> files open, it tries to close one first, to
201    avoid running out of file descriptors.  It will return NULL
202    if it is unable to (re)open the @var{abfd}.  */
203
204 static FILE *
205 bfd_cache_lookup_worker (bfd *abfd, enum cache_flag flag)
206 {
207   bfd *orig_bfd = abfd;
208   if ((abfd->flags & BFD_IN_MEMORY) != 0)
209     abort ();
210
211   if (abfd->my_archive)
212     abfd = abfd->my_archive;
213
214   if (abfd->iostream != NULL)
215     {
216       /* Move the file to the start of the cache.  */
217       if (abfd != bfd_last_cache)
218         {
219           snip (abfd);
220           insert (abfd);
221         }
222       return (FILE *) abfd->iostream;
223     }
224
225   if (flag & CACHE_NO_OPEN)
226     return NULL;
227
228   if (bfd_open_file (abfd) == NULL)
229     ;
230   else if (!(flag & CACHE_NO_SEEK)
231            && real_fseek ((FILE *) abfd->iostream, abfd->where, SEEK_SET) != 0
232            && !(flag & CACHE_NO_SEEK_ERROR))
233     bfd_set_error (bfd_error_system_call);
234   else
235     return (FILE *) abfd->iostream;
236
237   (*_bfd_error_handler) (_("reopening %B: %s\n"),
238                          orig_bfd, bfd_errmsg (bfd_get_error ()));
239   return NULL;
240 }
241
242 static file_ptr
243 cache_btell (struct bfd *abfd)
244 {
245   FILE *f = bfd_cache_lookup (abfd, CACHE_NO_OPEN);
246   if (f == NULL)
247     return abfd->where;
248   return real_ftell (f);
249 }
250
251 static int
252 cache_bseek (struct bfd *abfd, file_ptr offset, int whence)
253 {
254   FILE *f = bfd_cache_lookup (abfd, whence != SEEK_CUR ? CACHE_NO_SEEK : 0);
255   if (f == NULL)
256     return -1;
257   return real_fseek (f, offset, whence);
258 }
259
260 /* Note that archive entries don't have streams; they share their parent's.
261    This allows someone to play with the iostream behind BFD's back.
262
263    Also, note that the origin pointer points to the beginning of a file's
264    contents (0 for non-archive elements).  For archive entries this is the
265    first octet in the file, NOT the beginning of the archive header.  */
266
267 static file_ptr
268 cache_bread (struct bfd *abfd, void *buf, file_ptr nbytes)
269 {
270   FILE *f;
271   file_ptr nread;
272   /* FIXME - this looks like an optimization, but it's really to cover
273      up for a feature of some OSs (not solaris - sigh) that
274      ld/pe-dll.c takes advantage of (apparently) when it creates BFDs
275      internally and tries to link against them.  BFD seems to be smart
276      enough to realize there are no symbol records in the "file" that
277      doesn't exist but attempts to read them anyway.  On Solaris,
278      attempting to read zero bytes from a NULL file results in a core
279      dump, but on other platforms it just returns zero bytes read.
280      This makes it to something reasonable. - DJ */
281   if (nbytes == 0)
282     return 0;
283
284   f = bfd_cache_lookup (abfd, 0);
285   if (f == NULL)
286     return 0;
287
288 #if defined (__VAX) && defined (VMS)
289   /* Apparently fread on Vax VMS does not keep the record length
290      information.  */
291   nread = read (fileno (f), buf, nbytes);
292   /* Set bfd_error if we did not read as much data as we expected.  If
293      the read failed due to an error set the bfd_error_system_call,
294      else set bfd_error_file_truncated.  */
295   if (nread == (file_ptr)-1)
296     {
297       bfd_set_error (bfd_error_system_call);
298       return -1;
299     }
300 #else
301   nread = fread (buf, 1, nbytes, f);
302   /* Set bfd_error if we did not read as much data as we expected.  If
303      the read failed due to an error set the bfd_error_system_call,
304      else set bfd_error_file_truncated.  */
305   if (nread < nbytes && ferror (f))
306     {
307       bfd_set_error (bfd_error_system_call);
308       return -1;
309     }
310 #endif
311   return nread;
312 }
313
314 static file_ptr
315 cache_bwrite (struct bfd *abfd, const void *where, file_ptr nbytes)
316 {
317   file_ptr nwrite;
318   FILE *f = bfd_cache_lookup (abfd, 0);
319   if (f == NULL)
320     return 0;
321   nwrite = fwrite (where, 1, nbytes, f);
322   if (nwrite < nbytes && ferror (f))
323     {
324       bfd_set_error (bfd_error_system_call);
325       return -1;
326     }
327   return nwrite;
328 }
329
330 static int
331 cache_bclose (struct bfd *abfd)
332 {
333   return bfd_cache_close (abfd);
334 }
335
336 static int
337 cache_bflush (struct bfd *abfd)
338 {
339   int sts;
340   FILE *f = bfd_cache_lookup (abfd, CACHE_NO_OPEN);
341   if (f == NULL)
342     return 0;
343   sts = fflush (f);
344   if (sts < 0)
345     bfd_set_error (bfd_error_system_call);
346   return sts;
347 }
348
349 static int
350 cache_bstat (struct bfd *abfd, struct stat *sb)
351 {
352   int sts;
353   FILE *f = bfd_cache_lookup (abfd, CACHE_NO_SEEK_ERROR);
354   if (f == NULL)
355     return -1;
356   sts = fstat (fileno (f), sb);
357   if (sts < 0)
358     bfd_set_error (bfd_error_system_call);
359   return sts;
360 }
361
362 static const struct bfd_iovec cache_iovec = {
363   &cache_bread, &cache_bwrite, &cache_btell, &cache_bseek,
364   &cache_bclose, &cache_bflush, &cache_bstat
365 };
366
367 /*
368 INTERNAL_FUNCTION
369         bfd_cache_init
370
371 SYNOPSIS
372         bfd_boolean bfd_cache_init (bfd *abfd);
373
374 DESCRIPTION
375         Add a newly opened BFD to the cache.
376 */
377
378 bfd_boolean
379 bfd_cache_init (bfd *abfd)
380 {
381   BFD_ASSERT (abfd->iostream != NULL);
382   if (open_files >= BFD_CACHE_MAX_OPEN)
383     {
384       if (! close_one ())
385         return FALSE;
386     }
387   abfd->iovec = &cache_iovec;
388   insert (abfd);
389   ++open_files;
390   return TRUE;
391 }
392
393 /*
394 INTERNAL_FUNCTION
395         bfd_cache_close
396
397 SYNOPSIS
398         bfd_boolean bfd_cache_close (bfd *abfd);
399
400 DESCRIPTION
401         Remove the BFD @var{abfd} from the cache. If the attached file is open,
402         then close it too.
403
404 RETURNS
405         <<FALSE>> is returned if closing the file fails, <<TRUE>> is
406         returned if all is well.
407 */
408
409 bfd_boolean
410 bfd_cache_close (bfd *abfd)
411 {
412   if (abfd->iovec != &cache_iovec)
413     return TRUE;
414
415   if (abfd->iostream == NULL)
416     /* Previously closed.  */
417     return TRUE;
418
419   return bfd_cache_delete (abfd);
420 }
421
422 /*
423 FUNCTION
424         bfd_cache_close_all
425
426 SYNOPSIS
427         bfd_boolean bfd_cache_close_all (void);
428
429 DESCRIPTION
430         Remove all BFDs from the cache. If the attached file is open,
431         then close it too.
432
433 RETURNS
434         <<FALSE>> is returned if closing one of the file fails, <<TRUE>> is
435         returned if all is well.
436 */
437
438 bfd_boolean
439 bfd_cache_close_all ()
440 {
441   bfd_boolean ret = TRUE;
442
443   while (bfd_last_cache != NULL)
444     ret &= bfd_cache_close (bfd_last_cache);
445
446   return ret;
447 }
448
449 /*
450 INTERNAL_FUNCTION
451         bfd_open_file
452
453 SYNOPSIS
454         FILE* bfd_open_file (bfd *abfd);
455
456 DESCRIPTION
457         Call the OS to open a file for @var{abfd}.  Return the <<FILE *>>
458         (possibly <<NULL>>) that results from this operation.  Set up the
459         BFD so that future accesses know the file is open. If the <<FILE *>>
460         returned is <<NULL>>, then it won't have been put in the
461         cache, so it won't have to be removed from it.
462 */
463
464 FILE *
465 bfd_open_file (bfd *abfd)
466 {
467   abfd->cacheable = TRUE;       /* Allow it to be closed later.  */
468
469   if (open_files >= BFD_CACHE_MAX_OPEN)
470     {
471       if (! close_one ())
472         return NULL;
473     }
474
475   switch (abfd->direction)
476     {
477     case read_direction:
478     case no_direction:
479       abfd->iostream = (PTR) real_fopen (abfd->filename, FOPEN_RB);
480       break;
481     case both_direction:
482     case write_direction:
483       if (abfd->opened_once)
484         {
485           abfd->iostream = (PTR) real_fopen (abfd->filename, FOPEN_RUB);
486           if (abfd->iostream == NULL)
487             abfd->iostream = (PTR) real_fopen (abfd->filename, FOPEN_WUB);
488         }
489       else
490         {
491           /* Create the file.
492
493              Some operating systems won't let us overwrite a running
494              binary.  For them, we want to unlink the file first.
495
496              However, gcc 2.95 will create temporary files using
497              O_EXCL and tight permissions to prevent other users from
498              substituting other .o files during the compilation.  gcc
499              will then tell the assembler to use the newly created
500              file as an output file.  If we unlink the file here, we
501              open a brief window when another user could still
502              substitute a file.
503
504              So we unlink the output file if and only if it has
505              non-zero size.  */
506 #ifndef __MSDOS__
507           /* Don't do this for MSDOS: it doesn't care about overwriting
508              a running binary, but if this file is already open by
509              another BFD, we will be in deep trouble if we delete an
510              open file.  In fact, objdump does just that if invoked with
511              the --info option.  */
512           struct stat s;
513
514           if (stat (abfd->filename, &s) == 0 && s.st_size != 0)
515             unlink_if_ordinary (abfd->filename);
516 #endif
517           abfd->iostream = (PTR) real_fopen (abfd->filename, FOPEN_WUB);
518           abfd->opened_once = TRUE;
519         }
520       break;
521     }
522
523   if (abfd->iostream == NULL)
524     bfd_set_error (bfd_error_system_call);
525   else
526     {
527       if (! bfd_cache_init (abfd))
528         return NULL;
529     }
530
531   return (FILE *) abfd->iostream;
532 }