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