Subversion Repositories Kolibri OS

Rev

Rev 5197 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5197 serge 1
/* Support for the generic parts of PE/PEI; the common executable parts.
6324 serge 2
   Copyright (C) 1995-2015 Free Software Foundation, Inc.
5197 serge 3
   Written by Cygnus Solutions.
4
 
5
   This file is part of BFD, the Binary File Descriptor library.
6
 
7
   This program is free software; you can redistribute it and/or modify
8
   it under the terms of the GNU General Public License as published by
9
   the Free Software Foundation; either version 3 of the License, or
10
   (at your option) any later version.
11
 
12
   This program is distributed in the hope that it will be useful,
13
   but WITHOUT ANY WARRANTY; without even the implied warranty of
14
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
   GNU General Public License for more details.
16
 
17
   You should have received a copy of the GNU General Public License
18
   along with this program; if not, write to the Free Software
19
   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20
   MA 02110-1301, USA.  */
21
 
22
 
23
/* Most of this hacked by Steve Chamberlain .
24
 
25
   PE/PEI rearrangement (and code added): Donn Terry
26
					  Softway Systems, Inc.  */
27
 
28
/* Hey look, some documentation [and in a place you expect to find it]!
29
 
30
   The main reference for the pei format is "Microsoft Portable Executable
31
   and Common Object File Format Specification 4.1".  Get it if you need to
32
   do some serious hacking on this code.
33
 
34
   Another reference:
35
   "Peering Inside the PE: A Tour of the Win32 Portable Executable
36
   File Format", MSJ 1994, Volume 9.
37
 
38
   The *sole* difference between the pe format and the pei format is that the
39
   latter has an MSDOS 2.0 .exe header on the front that prints the message
40
   "This app must be run under Windows." (or some such).
41
   (FIXME: Whether that statement is *really* true or not is unknown.
42
   Are there more subtle differences between pe and pei formats?
43
   For now assume there aren't.  If you find one, then for God sakes
44
   document it here!)
45
 
46
   The Microsoft docs use the word "image" instead of "executable" because
47
   the former can also refer to a DLL (shared library).  Confusion can arise
48
   because the `i' in `pei' also refers to "image".  The `pe' format can
49
   also create images (i.e. executables), it's just that to run on a win32
50
   system you need to use the pei format.
51
 
52
   FIXME: Please add more docs here so the next poor fool that has to hack
53
   on this code has a chance of getting something accomplished without
54
   wasting too much time.  */
55
 
56
/* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64
57
   depending on whether we're compiling for straight PE or PE+.  */
58
#define COFF_WITH_pe
59
 
60
#include "sysdep.h"
61
#include "bfd.h"
62
#include "libbfd.h"
63
#include "coff/internal.h"
64
#include "bfdver.h"
65
 
66
/* NOTE: it's strange to be including an architecture specific header
67
   in what's supposed to be general (to PE/PEI) code.  However, that's
68
   where the definitions are, and they don't vary per architecture
69
   within PE/PEI, so we get them from there.  FIXME: The lack of
70
   variance is an assumption which may prove to be incorrect if new
71
   PE/PEI targets are created.  */
72
#if defined COFF_WITH_pex64
73
# include "coff/x86_64.h"
74
#elif defined COFF_WITH_pep
75
# include "coff/ia64.h"
76
#else
77
# include "coff/i386.h"
78
#endif
79
 
80
#include "coff/pe.h"
81
#include "libcoff.h"
82
#include "libpei.h"
6324 serge 83
#include "safe-ctype.h"
5197 serge 84
 
85
#if defined COFF_WITH_pep || defined COFF_WITH_pex64
86
# undef AOUTSZ
87
# define AOUTSZ		PEPAOUTSZ
88
# define PEAOUTHDR	PEPAOUTHDR
89
#endif
90
 
6324 serge 91
#define HighBitSet(val)      ((val) & 0x80000000)
92
#define SetHighBit(val)      ((val) | 0x80000000)
93
#define WithoutHighBit(val)  ((val) & 0x7fffffff)
94
 
5197 serge 95
/* FIXME: This file has various tests of POWERPC_LE_PE.  Those tests
96
   worked when the code was in peicode.h, but no longer work now that
97
   the code is in peigen.c.  PowerPC NT is said to be dead.  If
98
   anybody wants to revive the code, you will have to figure out how
99
   to handle those issues.  */
100
 
101
void
102
_bfd_pei_swap_sym_in (bfd * abfd, void * ext1, void * in1)
103
{
104
  SYMENT *ext = (SYMENT *) ext1;
105
  struct internal_syment *in = (struct internal_syment *) in1;
106
 
107
  if (ext->e.e_name[0] == 0)
108
    {
109
      in->_n._n_n._n_zeroes = 0;
110
      in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
111
    }
112
  else
113
    memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
114
 
115
  in->n_value = H_GET_32 (abfd, ext->e_value);
116
  in->n_scnum = H_GET_16 (abfd, ext->e_scnum);
117
 
118
  if (sizeof (ext->e_type) == 2)
119
    in->n_type = H_GET_16 (abfd, ext->e_type);
120
  else
121
    in->n_type = H_GET_32 (abfd, ext->e_type);
122
 
123
  in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
124
  in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
125
 
126
#ifndef STRICT_PE_FORMAT
127
  /* This is for Gnu-created DLLs.  */
128
 
129
  /* The section symbols for the .idata$ sections have class 0x68
130
     (C_SECTION), which MS documentation indicates is a section
131
     symbol.  Unfortunately, the value field in the symbol is simply a
132
     copy of the .idata section's flags rather than something useful.
133
     When these symbols are encountered, change the value to 0 so that
134
     they will be handled somewhat correctly in the bfd code.  */
135
  if (in->n_sclass == C_SECTION)
136
    {
137
      char namebuf[SYMNMLEN + 1];
138
      const char *name = NULL;
139
 
140
      in->n_value = 0x0;
141
 
142
      /* Create synthetic empty sections as needed.  DJ */
143
      if (in->n_scnum == 0)
144
	{
145
	  asection *sec;
146
 
147
	  name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
148
	  if (name == NULL)
6324 serge 149
	    {
150
	      _bfd_error_handler (_("%B: unable to find name for empty section"),
151
				  abfd);
152
	      bfd_set_error (bfd_error_invalid_target);
153
	      return;
154
	    }
155
 
5197 serge 156
	  sec = bfd_get_section_by_name (abfd, name);
157
	  if (sec != NULL)
158
	    in->n_scnum = sec->target_index;
159
	}
160
 
161
      if (in->n_scnum == 0)
162
	{
163
	  int unused_section_number = 0;
164
	  asection *sec;
165
	  flagword flags;
166
 
167
	  for (sec = abfd->sections; sec; sec = sec->next)
168
	    if (unused_section_number <= sec->target_index)
169
	      unused_section_number = sec->target_index + 1;
170
 
171
	  if (name == namebuf)
172
	    {
173
	      name = (const char *) bfd_alloc (abfd, strlen (namebuf) + 1);
174
	      if (name == NULL)
6324 serge 175
		{
176
		  _bfd_error_handler (_("%B: out of memory creating name for empty section"),
177
				      abfd);
178
		  return;
179
		}
5197 serge 180
	      strcpy ((char *) name, namebuf);
181
	    }
6324 serge 182
 
5197 serge 183
	  flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
184
	  sec = bfd_make_section_anyway_with_flags (abfd, name, flags);
185
	  if (sec == NULL)
6324 serge 186
	    {
187
	      _bfd_error_handler (_("%B: unable to create fake empty section"),
188
				  abfd);
189
	      return;
190
	    }
5197 serge 191
 
192
	  sec->vma = 0;
193
	  sec->lma = 0;
194
	  sec->size = 0;
195
	  sec->filepos = 0;
196
	  sec->rel_filepos = 0;
197
	  sec->reloc_count = 0;
198
	  sec->line_filepos = 0;
199
	  sec->lineno_count = 0;
200
	  sec->userdata = NULL;
201
	  sec->next = NULL;
202
	  sec->alignment_power = 2;
203
 
204
	  sec->target_index = unused_section_number;
205
 
206
	  in->n_scnum = unused_section_number;
207
	}
208
      in->n_sclass = C_STAT;
209
    }
210
#endif
211
 
212
#ifdef coff_swap_sym_in_hook
213
  /* This won't work in peigen.c, but since it's for PPC PE, it's not
214
     worth fixing.  */
215
  coff_swap_sym_in_hook (abfd, ext1, in1);
216
#endif
217
}
218
 
6324 serge 219
static bfd_boolean
220
abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
221
{
222
  bfd_vma abs_val = * (bfd_vma *) data;
223
 
224
  return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
225
}
226
 
5197 serge 227
unsigned int
228
_bfd_pei_swap_sym_out (bfd * abfd, void * inp, void * extp)
229
{
230
  struct internal_syment *in = (struct internal_syment *) inp;
231
  SYMENT *ext = (SYMENT *) extp;
232
 
233
  if (in->_n._n_name[0] == 0)
234
    {
235
      H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
236
      H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
237
    }
238
  else
239
    memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
240
 
6324 serge 241
  /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a
242
     symbol.  This is a problem on 64-bit targets where we can generate
243
     absolute symbols with values >= 1^32.  We try to work around this
244
     problem by finding a section whose base address is sufficient to
245
     reduce the absolute value to < 1^32, and then transforming the
246
     symbol into a section relative symbol.  This of course is a hack.  */
247
  if (sizeof (in->n_value) > 4
248
      /* The strange computation of the shift amount is here in order to
249
	 avoid a compile time warning about the comparison always being
250
	 false.  It does not matter if this test fails to work as expected
251
	 as the worst that can happen is that some absolute symbols are
252
	 needlessly converted into section relative symbols.  */
253
      && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1)
254
      && in->n_scnum == -1)
255
    {
256
      asection * sec;
257
 
258
      sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
259
      if (sec)
260
	{
261
	  in->n_value -= sec->vma;
262
	  in->n_scnum = sec->target_index;
263
	}
264
      /* else: FIXME: The value is outside the range of any section.  This
265
	 happens for __image_base__ and __ImageBase and maybe some other
266
	 symbols as well.  We should find a way to handle these values.  */
267
    }
268
 
5197 serge 269
  H_PUT_32 (abfd, in->n_value, ext->e_value);
270
  H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
271
 
272
  if (sizeof (ext->e_type) == 2)
273
    H_PUT_16 (abfd, in->n_type, ext->e_type);
274
  else
275
    H_PUT_32 (abfd, in->n_type, ext->e_type);
276
 
277
  H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
278
  H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
279
 
280
  return SYMESZ;
281
}
282
 
283
void
284
_bfd_pei_swap_aux_in (bfd *	abfd,
285
		      void *	ext1,
286
		      int       type,
287
		      int       in_class,
288
		      int	indx ATTRIBUTE_UNUSED,
289
		      int	numaux ATTRIBUTE_UNUSED,
290
		      void * 	in1)
291
{
292
  AUXENT *ext = (AUXENT *) ext1;
293
  union internal_auxent *in = (union internal_auxent *) in1;
294
 
6324 serge 295
  /* PR 17521: Make sure that all fields in the aux structure
296
     are initialised.  */
297
  memset (in, 0, sizeof * in);
5197 serge 298
  switch (in_class)
299
    {
300
    case C_FILE:
301
      if (ext->x_file.x_fname[0] == 0)
302
	{
303
	  in->x_file.x_n.x_zeroes = 0;
304
	  in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
305
	}
306
      else
307
	memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
308
      return;
309
 
310
    case C_STAT:
311
    case C_LEAFSTAT:
312
    case C_HIDDEN:
313
      if (type == T_NULL)
314
	{
315
	  in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
316
	  in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
317
	  in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
318
	  in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
319
	  in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
320
	  in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
321
	  return;
322
	}
323
      break;
324
    }
325
 
326
  in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
327
  in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
328
 
329
  if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
330
      || ISTAG (in_class))
331
    {
332
      in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
333
      in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
334
    }
335
  else
336
    {
337
      in->x_sym.x_fcnary.x_ary.x_dimen[0] =
338
	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
339
      in->x_sym.x_fcnary.x_ary.x_dimen[1] =
340
	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
341
      in->x_sym.x_fcnary.x_ary.x_dimen[2] =
342
	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
343
      in->x_sym.x_fcnary.x_ary.x_dimen[3] =
344
	H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
345
    }
346
 
347
  if (ISFCN (type))
348
    {
349
      in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
350
    }
351
  else
352
    {
353
      in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
354
      in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
355
    }
356
}
357
 
358
unsigned int
359
_bfd_pei_swap_aux_out (bfd *  abfd,
360
		       void * inp,
361
		       int    type,
362
		       int    in_class,
363
		       int    indx ATTRIBUTE_UNUSED,
364
		       int    numaux ATTRIBUTE_UNUSED,
365
		       void * extp)
366
{
367
  union internal_auxent *in = (union internal_auxent *) inp;
368
  AUXENT *ext = (AUXENT *) extp;
369
 
370
  memset (ext, 0, AUXESZ);
371
 
372
  switch (in_class)
373
    {
374
    case C_FILE:
375
      if (in->x_file.x_fname[0] == 0)
376
	{
377
	  H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
378
	  H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
379
	}
380
      else
381
	memcpy (ext->x_file.x_fname, in->x_file.x_fname, FILNMLEN);
382
 
383
      return AUXESZ;
384
 
385
    case C_STAT:
386
    case C_LEAFSTAT:
387
    case C_HIDDEN:
388
      if (type == T_NULL)
389
	{
390
	  PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
391
	  PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
392
	  PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
393
	  H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
394
	  H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
395
	  H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
396
	  return AUXESZ;
397
	}
398
      break;
399
    }
400
 
401
  H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
402
  H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
403
 
404
  if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
405
      || ISTAG (in_class))
406
    {
407
      PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr,  ext);
408
      PUT_FCN_ENDNDX  (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
409
    }
410
  else
411
    {
412
      H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
413
		ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
414
      H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
415
		ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
416
      H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
417
		ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
418
      H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
419
		ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
420
    }
421
 
422
  if (ISFCN (type))
423
    H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
424
  else
425
    {
426
      PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
427
      PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
428
    }
429
 
430
  return AUXESZ;
431
}
432
 
433
void
434
_bfd_pei_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
435
{
436
  LINENO *ext = (LINENO *) ext1;
437
  struct internal_lineno *in = (struct internal_lineno *) in1;
438
 
439
  in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
440
  in->l_lnno = GET_LINENO_LNNO (abfd, ext);
441
}
442
 
443
unsigned int
444
_bfd_pei_swap_lineno_out (bfd * abfd, void * inp, void * outp)
445
{
446
  struct internal_lineno *in = (struct internal_lineno *) inp;
447
  struct external_lineno *ext = (struct external_lineno *) outp;
448
  H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
449
 
450
  PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
451
  return LINESZ;
452
}
453
 
454
void
455
_bfd_pei_swap_aouthdr_in (bfd * abfd,
456
			  void * aouthdr_ext1,
457
			  void * aouthdr_int1)
458
{
459
  PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
460
  AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
461
  struct internal_aouthdr *aouthdr_int
462
    = (struct internal_aouthdr *) aouthdr_int1;
463
  struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
464
 
465
  aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
466
  aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
467
  aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
468
  aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
469
  aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
470
  aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
471
  aouthdr_int->text_start =
472
    GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
6324 serge 473
 
5197 serge 474
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
475
  /* PE32+ does not have data_start member!  */
476
  aouthdr_int->data_start =
477
    GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
478
  a->BaseOfData = aouthdr_int->data_start;
479
#endif
480
 
481
  a->Magic = aouthdr_int->magic;
482
  a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
483
  a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
484
  a->SizeOfCode = aouthdr_int->tsize ;
485
  a->SizeOfInitializedData = aouthdr_int->dsize ;
486
  a->SizeOfUninitializedData = aouthdr_int->bsize ;
487
  a->AddressOfEntryPoint = aouthdr_int->entry;
488
  a->BaseOfCode = aouthdr_int->text_start;
489
  a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
490
  a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
491
  a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
492
  a->MajorOperatingSystemVersion =
493
    H_GET_16 (abfd, src->MajorOperatingSystemVersion);
494
  a->MinorOperatingSystemVersion =
495
    H_GET_16 (abfd, src->MinorOperatingSystemVersion);
496
  a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
497
  a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
498
  a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
499
  a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
500
  a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
501
  a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
502
  a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
503
  a->CheckSum = H_GET_32 (abfd, src->CheckSum);
504
  a->Subsystem = H_GET_16 (abfd, src->Subsystem);
505
  a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
506
  a->SizeOfStackReserve =
507
    GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
508
  a->SizeOfStackCommit =
509
    GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
510
  a->SizeOfHeapReserve =
511
    GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
512
  a->SizeOfHeapCommit =
513
    GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
514
  a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
515
  a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
516
 
517
  {
518
    int idx;
519
 
6324 serge 520
    /* PR 17512: Corrupt PE binaries can cause seg-faults.  */
521
    if (a->NumberOfRvaAndSizes > IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
522
      {
523
	(*_bfd_error_handler)
524
	  (_("%B: aout header specifies an invalid number of data-directory entries: %d"),
525
	   abfd, a->NumberOfRvaAndSizes);
526
	bfd_set_error (bfd_error_bad_value);
527
 
528
	/* Paranoia: If the number is corrupt, then assume that the
529
	   actual entries themselves might be corrupt as well.  */
530
	a->NumberOfRvaAndSizes = 0;
531
      }
532
 
5197 serge 533
    for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++)
534
      {
535
        /* If data directory is empty, rva also should be 0.  */
536
	int size =
537
	  H_GET_32 (abfd, src->DataDirectory[idx][1]);
538
 
539
	a->DataDirectory[idx].Size = size;
540
 
541
	if (size)
542
	  a->DataDirectory[idx].VirtualAddress =
543
	    H_GET_32 (abfd, src->DataDirectory[idx][0]);
544
	else
545
	  a->DataDirectory[idx].VirtualAddress = 0;
546
      }
6324 serge 547
 
548
    while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
549
      {
550
	a->DataDirectory[idx].Size = 0;
551
	a->DataDirectory[idx].VirtualAddress = 0;
552
	idx ++;
553
      }
5197 serge 554
  }
555
 
556
  if (aouthdr_int->entry)
557
    {
558
      aouthdr_int->entry += a->ImageBase;
559
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
560
      aouthdr_int->entry &= 0xffffffff;
561
#endif
562
    }
563
 
564
  if (aouthdr_int->tsize)
565
    {
566
      aouthdr_int->text_start += a->ImageBase;
567
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
568
      aouthdr_int->text_start &= 0xffffffff;
569
#endif
570
    }
571
 
572
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
573
  /* PE32+ does not have data_start member!  */
574
  if (aouthdr_int->dsize)
575
    {
576
      aouthdr_int->data_start += a->ImageBase;
577
      aouthdr_int->data_start &= 0xffffffff;
578
    }
579
#endif
580
 
581
#ifdef POWERPC_LE_PE
582
  /* These three fields are normally set up by ppc_relocate_section.
583
     In the case of reading a file in, we can pick them up from the
584
     DataDirectory.  */
585
  first_thunk_address = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress;
586
  thunk_size = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size;
587
  import_table_size = a->DataDirectory[PE_IMPORT_TABLE].Size;
588
#endif
589
}
590
 
591
/* A support function for below.  */
592
 
593
static void
594
add_data_entry (bfd * abfd,
595
		struct internal_extra_pe_aouthdr *aout,
596
		int idx,
597
		char *name,
598
		bfd_vma base)
599
{
600
  asection *sec = bfd_get_section_by_name (abfd, name);
601
 
602
  /* Add import directory information if it exists.  */
603
  if ((sec != NULL)
604
      && (coff_section_data (abfd, sec) != NULL)
605
      && (pei_section_data (abfd, sec) != NULL))
606
    {
607
      /* If data directory is empty, rva also should be 0.  */
608
      int size = pei_section_data (abfd, sec)->virt_size;
609
      aout->DataDirectory[idx].Size = size;
610
 
611
      if (size)
612
	{
613
	  aout->DataDirectory[idx].VirtualAddress =
614
	    (sec->vma - base) & 0xffffffff;
615
	  sec->flags |= SEC_DATA;
616
	}
617
    }
618
}
619
 
620
unsigned int
621
_bfd_pei_swap_aouthdr_out (bfd * abfd, void * in, void * out)
622
{
623
  struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
624
  pe_data_type *pe = pe_data (abfd);
625
  struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
626
  PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
627
  bfd_vma sa, fa, ib;
628
  IMAGE_DATA_DIRECTORY idata2, idata5, tls;
629
 
630
  sa = extra->SectionAlignment;
631
  fa = extra->FileAlignment;
632
  ib = extra->ImageBase;
633
 
634
  idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
635
  idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
636
  tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
637
 
638
  if (aouthdr_in->tsize)
639
    {
640
      aouthdr_in->text_start -= ib;
641
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
642
      aouthdr_in->text_start &= 0xffffffff;
643
#endif
644
    }
645
 
646
  if (aouthdr_in->dsize)
647
    {
648
      aouthdr_in->data_start -= ib;
649
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
650
      aouthdr_in->data_start &= 0xffffffff;
651
#endif
652
    }
653
 
654
  if (aouthdr_in->entry)
655
    {
656
      aouthdr_in->entry -= ib;
657
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
658
      aouthdr_in->entry &= 0xffffffff;
659
#endif
660
    }
661
 
662
#define FA(x) (((x) + fa -1 ) & (- fa))
663
#define SA(x) (((x) + sa -1 ) & (- sa))
664
 
665
  /* We like to have the sizes aligned.  */
666
  aouthdr_in->bsize = FA (aouthdr_in->bsize);
667
 
668
  extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
669
 
670
  add_data_entry (abfd, extra, 0, ".edata", ib);
671
  add_data_entry (abfd, extra, 2, ".rsrc", ib);
672
  add_data_entry (abfd, extra, 3, ".pdata", ib);
673
 
674
  /* In theory we do not need to call add_data_entry for .idata$2 or
675
     .idata$5.  It will be done in bfd_coff_final_link where all the
676
     required information is available.  If however, we are not going
677
     to perform a final link, eg because we have been invoked by objcopy
678
     or strip, then we need to make sure that these Data Directory
679
     entries are initialised properly.
680
 
681
     So - we copy the input values into the output values, and then, if
682
     a final link is going to be performed, it can overwrite them.  */
683
  extra->DataDirectory[PE_IMPORT_TABLE]  = idata2;
684
  extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
685
  extra->DataDirectory[PE_TLS_TABLE] = tls;
686
 
687
  if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
688
    /* Until other .idata fixes are made (pending patch), the entry for
689
       .idata is needed for backwards compatibility.  FIXME.  */
690
    add_data_entry (abfd, extra, 1, ".idata", ib);
691
 
692
  /* For some reason, the virtual size (which is what's set by
693
     add_data_entry) for .reloc is not the same as the size recorded
694
     in this slot by MSVC; it doesn't seem to cause problems (so far),
695
     but since it's the best we've got, use it.  It does do the right
696
     thing for .pdata.  */
697
  if (pe->has_reloc_section)
698
    add_data_entry (abfd, extra, 5, ".reloc", ib);
699
 
700
  {
701
    asection *sec;
702
    bfd_vma hsize = 0;
703
    bfd_vma dsize = 0;
704
    bfd_vma isize = 0;
705
    bfd_vma tsize = 0;
706
 
707
    for (sec = abfd->sections; sec; sec = sec->next)
708
      {
709
	int rounded = FA (sec->size);
710
 
711
	/* The first non-zero section filepos is the header size.
712
	   Sections without contents will have a filepos of 0.  */
713
	if (hsize == 0)
714
	  hsize = sec->filepos;
715
	if (sec->flags & SEC_DATA)
716
	  dsize += rounded;
717
	if (sec->flags & SEC_CODE)
718
	  tsize += rounded;
719
	/* The image size is the total VIRTUAL size (which is what is
720
	   in the virt_size field).  Files have been seen (from MSVC
721
	   5.0 link.exe) where the file size of the .data segment is
722
	   quite small compared to the virtual size.  Without this
723
	   fix, strip munges the file.
724
 
725
	   FIXME: We need to handle holes between sections, which may
726
	   happpen when we covert from another format.  We just use
727
	   the virtual address and virtual size of the last section
728
	   for the image size.  */
729
	if (coff_section_data (abfd, sec) != NULL
730
	    && pei_section_data (abfd, sec) != NULL)
731
	  isize = (sec->vma - extra->ImageBase
732
		   + SA (FA (pei_section_data (abfd, sec)->virt_size)));
733
      }
734
 
735
    aouthdr_in->dsize = dsize;
736
    aouthdr_in->tsize = tsize;
737
    extra->SizeOfHeaders = hsize;
738
    extra->SizeOfImage = isize;
739
  }
740
 
741
  H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
742
 
743
/* e.g. 219510000 is linker version 2.19  */
744
#define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
745
 
746
  /* This piece of magic sets the "linker version" field to
747
     LINKER_VERSION.  */
748
  H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
749
	    aouthdr_out->standard.vstamp);
750
 
751
  PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
752
  PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
753
  PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
754
  PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
755
  PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
756
			  aouthdr_out->standard.text_start);
757
 
758
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
759
  /* PE32+ does not have data_start member!  */
760
  PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
761
			  aouthdr_out->standard.data_start);
762
#endif
763
 
764
  PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
765
  H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
766
  H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
767
  H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
768
	    aouthdr_out->MajorOperatingSystemVersion);
769
  H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
770
	    aouthdr_out->MinorOperatingSystemVersion);
771
  H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
772
  H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
773
  H_PUT_16 (abfd, extra->MajorSubsystemVersion,
774
	    aouthdr_out->MajorSubsystemVersion);
775
  H_PUT_16 (abfd, extra->MinorSubsystemVersion,
776
	    aouthdr_out->MinorSubsystemVersion);
777
  H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
778
  H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
779
  H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
780
  H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
781
  H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
782
  H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
783
  PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
784
				    aouthdr_out->SizeOfStackReserve);
785
  PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
786
				   aouthdr_out->SizeOfStackCommit);
787
  PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
788
				   aouthdr_out->SizeOfHeapReserve);
789
  PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
790
				  aouthdr_out->SizeOfHeapCommit);
791
  H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
792
  H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
793
	    aouthdr_out->NumberOfRvaAndSizes);
794
  {
795
    int idx;
796
 
6324 serge 797
    for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
5197 serge 798
      {
799
	H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
800
		  aouthdr_out->DataDirectory[idx][0]);
801
	H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
802
		  aouthdr_out->DataDirectory[idx][1]);
803
      }
804
  }
805
 
806
  return AOUTSZ;
807
}
808
 
809
unsigned int
810
_bfd_pei_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
811
{
812
  int idx;
813
  struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
814
  struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
815
 
816
  if (pe_data (abfd)->has_reloc_section
817
      || pe_data (abfd)->dont_strip_reloc)
818
    filehdr_in->f_flags &= ~F_RELFLG;
819
 
820
  if (pe_data (abfd)->dll)
821
    filehdr_in->f_flags |= F_DLL;
822
 
823
  filehdr_in->pe.e_magic    = DOSMAGIC;
824
  filehdr_in->pe.e_cblp     = 0x90;
825
  filehdr_in->pe.e_cp       = 0x3;
826
  filehdr_in->pe.e_crlc     = 0x0;
827
  filehdr_in->pe.e_cparhdr  = 0x4;
828
  filehdr_in->pe.e_minalloc = 0x0;
829
  filehdr_in->pe.e_maxalloc = 0xffff;
830
  filehdr_in->pe.e_ss       = 0x0;
831
  filehdr_in->pe.e_sp       = 0xb8;
832
  filehdr_in->pe.e_csum     = 0x0;
833
  filehdr_in->pe.e_ip       = 0x0;
834
  filehdr_in->pe.e_cs       = 0x0;
835
  filehdr_in->pe.e_lfarlc   = 0x40;
836
  filehdr_in->pe.e_ovno     = 0x0;
837
 
838
  for (idx = 0; idx < 4; idx++)
839
    filehdr_in->pe.e_res[idx] = 0x0;
840
 
841
  filehdr_in->pe.e_oemid   = 0x0;
842
  filehdr_in->pe.e_oeminfo = 0x0;
843
 
844
  for (idx = 0; idx < 10; idx++)
845
    filehdr_in->pe.e_res2[idx] = 0x0;
846
 
847
  filehdr_in->pe.e_lfanew = 0x80;
848
 
849
  /* This next collection of data are mostly just characters.  It
850
     appears to be constant within the headers put on NT exes.  */
851
  filehdr_in->pe.dos_message[0]  = 0x0eba1f0e;
852
  filehdr_in->pe.dos_message[1]  = 0xcd09b400;
853
  filehdr_in->pe.dos_message[2]  = 0x4c01b821;
854
  filehdr_in->pe.dos_message[3]  = 0x685421cd;
855
  filehdr_in->pe.dos_message[4]  = 0x70207369;
856
  filehdr_in->pe.dos_message[5]  = 0x72676f72;
857
  filehdr_in->pe.dos_message[6]  = 0x63206d61;
858
  filehdr_in->pe.dos_message[7]  = 0x6f6e6e61;
859
  filehdr_in->pe.dos_message[8]  = 0x65622074;
860
  filehdr_in->pe.dos_message[9]  = 0x6e757220;
861
  filehdr_in->pe.dos_message[10] = 0x206e6920;
862
  filehdr_in->pe.dos_message[11] = 0x20534f44;
863
  filehdr_in->pe.dos_message[12] = 0x65646f6d;
864
  filehdr_in->pe.dos_message[13] = 0x0a0d0d2e;
865
  filehdr_in->pe.dos_message[14] = 0x24;
866
  filehdr_in->pe.dos_message[15] = 0x0;
867
  filehdr_in->pe.nt_signature = NT_SIGNATURE;
868
 
869
  H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
870
  H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
871
 
872
  /* Only use a real timestamp if the option was chosen.  */
873
  if ((pe_data (abfd)->insert_timestamp))
6324 serge 874
    H_PUT_32 (abfd, time (0), filehdr_out->f_timdat);
5197 serge 875
 
876
  PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
877
		      filehdr_out->f_symptr);
878
  H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
879
  H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
880
  H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
881
 
882
  /* Put in extra dos header stuff.  This data remains essentially
883
     constant, it just has to be tacked on to the beginning of all exes
884
     for NT.  */
885
  H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
886
  H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
887
  H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
888
  H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
889
  H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
890
  H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
891
  H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
892
  H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
893
  H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
894
  H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
895
  H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
896
  H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
897
  H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
898
  H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
899
 
900
  for (idx = 0; idx < 4; idx++)
901
    H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
902
 
903
  H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
904
  H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
905
 
906
  for (idx = 0; idx < 10; idx++)
907
    H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
908
 
909
  H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
910
 
911
  for (idx = 0; idx < 16; idx++)
912
    H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx],
913
	      filehdr_out->dos_message[idx]);
914
 
915
  /* Also put in the NT signature.  */
916
  H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
917
 
918
  return FILHSZ;
919
}
920
 
921
unsigned int
922
_bfd_pe_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
923
{
924
  struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
925
  FILHDR *filehdr_out = (FILHDR *) out;
926
 
927
  H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
928
  H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
929
  H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
930
  PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
931
  H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
932
  H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
933
  H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
934
 
935
  return FILHSZ;
936
}
937
 
938
unsigned int
939
_bfd_pei_swap_scnhdr_out (bfd * abfd, void * in, void * out)
940
{
941
  struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
942
  SCNHDR *scnhdr_ext = (SCNHDR *) out;
943
  unsigned int ret = SCNHSZ;
944
  bfd_vma ps;
945
  bfd_vma ss;
946
 
947
  memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
948
 
949
  PUT_SCNHDR_VADDR (abfd,
950
		    ((scnhdr_int->s_vaddr
951
		      - pe_data (abfd)->pe_opthdr.ImageBase)
952
		     & 0xffffffff),
953
		    scnhdr_ext->s_vaddr);
954
 
955
  /* NT wants the size data to be rounded up to the next
956
     NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
957
     sometimes).  */
958
  if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
959
    {
960
      if (bfd_pei_p (abfd))
961
	{
962
	  ps = scnhdr_int->s_size;
963
	  ss = 0;
964
	}
965
      else
966
       {
967
         ps = 0;
968
         ss = scnhdr_int->s_size;
969
       }
970
    }
971
  else
972
    {
973
      if (bfd_pei_p (abfd))
974
	ps = scnhdr_int->s_paddr;
975
      else
976
	ps = 0;
977
 
978
      ss = scnhdr_int->s_size;
979
    }
980
 
981
  PUT_SCNHDR_SIZE (abfd, ss,
982
		   scnhdr_ext->s_size);
983
 
984
  /* s_paddr in PE is really the virtual size.  */
985
  PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
986
 
987
  PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
988
		     scnhdr_ext->s_scnptr);
989
  PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
990
		     scnhdr_ext->s_relptr);
991
  PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
992
		      scnhdr_ext->s_lnnoptr);
993
 
994
  {
995
    /* Extra flags must be set when dealing with PE.  All sections should also
996
       have the IMAGE_SCN_MEM_READ (0x40000000) flag set.  In addition, the
997
       .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
998
       sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
999
       (this is especially important when dealing with the .idata section since
1000
       the addresses for routines from .dlls must be overwritten).  If .reloc
1001
       section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
1002
       (0x02000000).  Also, the resource data should also be read and
1003
       writable.  */
1004
 
1005
    /* FIXME: Alignment is also encoded in this field, at least on PPC and
1006
       ARM-WINCE.  Although - how do we get the original alignment field
1007
       back ?  */
1008
 
1009
    typedef struct
1010
    {
1011
      const char * 	section_name;
1012
      unsigned long	must_have;
1013
    }
1014
    pe_required_section_flags;
1015
 
1016
    pe_required_section_flags known_sections [] =
1017
      {
1018
	{ ".arch",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
1019
	{ ".bss",   IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1020
	{ ".data",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1021
	{ ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1022
	{ ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1023
	{ ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1024
	{ ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1025
	{ ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1026
	{ ".rsrc",  IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1027
	{ ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1028
	{ ".tls",   IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1029
	{ ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1030
	{ NULL, 0}
1031
      };
1032
 
1033
    pe_required_section_flags * p;
1034
 
1035
    /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1036
       we know exactly what this specific section wants so we remove it
1037
       and then allow the must_have field to add it back in if necessary.
1038
       However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1039
       default WP_TEXT file flag has been cleared.  WP_TEXT may be cleared
1040
       by ld --enable-auto-import (if auto-import is actually needed),
1041
       by ld --omagic, or by obcopy --writable-text.  */
1042
 
1043
    for (p = known_sections; p->section_name; p++)
1044
      if (strcmp (scnhdr_int->s_name, p->section_name) == 0)
1045
	{
1046
	  if (strcmp (scnhdr_int->s_name, ".text")
1047
	      || (bfd_get_file_flags (abfd) & WP_TEXT))
1048
	    scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1049
	  scnhdr_int->s_flags |= p->must_have;
1050
	  break;
1051
	}
1052
 
1053
    H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1054
  }
1055
 
1056
  if (coff_data (abfd)->link_info
6324 serge 1057
      && ! bfd_link_relocatable (coff_data (abfd)->link_info)
1058
      && ! bfd_link_pic (coff_data (abfd)->link_info)
5197 serge 1059
      && strcmp (scnhdr_int->s_name, ".text") == 0)
1060
    {
1061
      /* By inference from looking at MS output, the 32 bit field
1062
	 which is the combination of the number_of_relocs and
1063
	 number_of_linenos is used for the line number count in
1064
	 executables.  A 16-bit field won't do for cc1.  The MS
1065
	 document says that the number of relocs is zero for
1066
	 executables, but the 17-th bit has been observed to be there.
1067
	 Overflow is not an issue: a 4G-line program will overflow a
1068
	 bunch of other fields long before this!  */
1069
      H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1070
      H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1071
    }
1072
  else
1073
    {
1074
      if (scnhdr_int->s_nlnno <= 0xffff)
1075
	H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1076
      else
1077
	{
1078
	  (*_bfd_error_handler) (_("%s: line number overflow: 0x%lx > 0xffff"),
1079
				 bfd_get_filename (abfd),
1080
				 scnhdr_int->s_nlnno);
1081
	  bfd_set_error (bfd_error_file_truncated);
1082
	  H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1083
	  ret = 0;
1084
	}
1085
 
1086
      /* Although we could encode 0xffff relocs here, we do not, to be
1087
         consistent with other parts of bfd. Also it lets us warn, as
1088
         we should never see 0xffff here w/o having the overflow flag
1089
         set.  */
1090
      if (scnhdr_int->s_nreloc < 0xffff)
1091
	H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1092
      else
1093
	{
1094
	  /* PE can deal with large #s of relocs, but not here.  */
1095
	  H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1096
	  scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1097
	  H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1098
	}
1099
    }
1100
  return ret;
1101
}
1102
 
6324 serge 1103
void
1104
_bfd_pei_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1105
{
1106
  struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1107
  struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1108
 
1109
  in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1110
  in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1111
  in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1112
  in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1113
  in->Type = H_GET_32(abfd, ext->Type);
1114
  in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1115
  in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1116
  in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1117
}
1118
 
1119
unsigned int
1120
_bfd_pei_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1121
{
1122
  struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1123
  struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1124
 
1125
  H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1126
  H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1127
  H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1128
  H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1129
  H_PUT_32(abfd, in->Type, ext->Type);
1130
  H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1131
  H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1132
  H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1133
 
1134
  return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1135
}
1136
 
1137
CODEVIEW_INFO *
1138
_bfd_pei_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo)
1139
{
1140
  char buffer[256+1];
1141
 
1142
  if (bfd_seek (abfd, where, SEEK_SET) != 0)
1143
    return NULL;
1144
 
1145
  if (bfd_bread (buffer, 256, abfd) < 4)
1146
    return NULL;
1147
 
1148
  /* Ensure null termination of filename.  */
1149
  buffer[256] = '\0';
1150
 
1151
  cvinfo->CVSignature = H_GET_32 (abfd, buffer);
1152
  cvinfo->Age = 0;
1153
 
1154
  if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1155
      && (length > sizeof (CV_INFO_PDB70)))
1156
    {
1157
      CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1158
 
1159
      cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1160
 
1161
      /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1162
         by 8 single bytes.  Byte swap them so we can conveniently treat the GUID
1163
         as 16 bytes in big-endian order.  */
1164
      bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1165
      bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1166
      bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1167
      memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1168
 
1169
      cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1170
      // cvinfo->PdbFileName = cvinfo70->PdbFileName;
1171
 
1172
      return cvinfo;
1173
    }
1174
  else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1175
           && (length > sizeof (CV_INFO_PDB20)))
1176
    {
1177
      CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1178
      cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1179
      memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1180
      cvinfo->SignatureLength = 4;
1181
      // cvinfo->PdbFileName = cvinfo20->PdbFileName;
1182
 
1183
      return cvinfo;
1184
    }
1185
 
1186
  return NULL;
1187
}
1188
 
1189
unsigned int
1190
_bfd_pei_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo)
1191
{
1192
  unsigned int size = sizeof (CV_INFO_PDB70) + 1;
1193
  CV_INFO_PDB70 *cvinfo70;
1194
  char buffer[size];
1195
 
1196
  if (bfd_seek (abfd, where, SEEK_SET) != 0)
1197
    return 0;
1198
 
1199
  cvinfo70 = (CV_INFO_PDB70 *) buffer;
1200
  H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1201
 
1202
  /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1203
     in little-endian order, followed by 8 single bytes.  */
1204
  bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1205
  bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1206
  bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1207
  memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1208
 
1209
  H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1210
  cvinfo70->PdbFileName[0] = '\0';
1211
 
1212
  if (bfd_bwrite (buffer, size, abfd) != size)
1213
    return 0;
1214
 
1215
  return size;
1216
}
1217
 
5197 serge 1218
static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1219
{
1220
  N_("Export Directory [.edata (or where ever we found it)]"),
1221
  N_("Import Directory [parts of .idata]"),
1222
  N_("Resource Directory [.rsrc]"),
1223
  N_("Exception Directory [.pdata]"),
1224
  N_("Security Directory"),
1225
  N_("Base Relocation Directory [.reloc]"),
1226
  N_("Debug Directory"),
1227
  N_("Description Directory"),
1228
  N_("Special Directory"),
1229
  N_("Thread Storage Directory [.tls]"),
1230
  N_("Load Configuration Directory"),
1231
  N_("Bound Import Directory"),
1232
  N_("Import Address Table Directory"),
1233
  N_("Delay Import Directory"),
1234
  N_("CLR Runtime Header"),
1235
  N_("Reserved")
1236
};
1237
 
1238
#ifdef POWERPC_LE_PE
1239
/* The code for the PPC really falls in the "architecture dependent"
1240
   category.  However, it's not clear that anyone will ever care, so
1241
   we're ignoring the issue for now; if/when PPC matters, some of this
1242
   may need to go into peicode.h, or arguments passed to enable the
1243
   PPC- specific code.  */
1244
#endif
1245
 
1246
static bfd_boolean
1247
pe_print_idata (bfd * abfd, void * vfile)
1248
{
1249
  FILE *file = (FILE *) vfile;
1250
  bfd_byte *data;
1251
  asection *section;
1252
  bfd_signed_vma adj;
1253
 
1254
#ifdef POWERPC_LE_PE
1255
  asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
1256
#endif
1257
 
1258
  bfd_size_type datasize = 0;
1259
  bfd_size_type dataoff;
1260
  bfd_size_type i;
1261
  int onaline = 20;
1262
 
1263
  pe_data_type *pe = pe_data (abfd);
1264
  struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1265
 
1266
  bfd_vma addr;
1267
 
1268
  addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1269
 
1270
  if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1271
    {
1272
      /* Maybe the extra header isn't there.  Look for the section.  */
1273
      section = bfd_get_section_by_name (abfd, ".idata");
1274
      if (section == NULL)
1275
	return TRUE;
1276
 
1277
      addr = section->vma;
1278
      datasize = section->size;
1279
      if (datasize == 0)
1280
	return TRUE;
1281
    }
1282
  else
1283
    {
1284
      addr += extra->ImageBase;
1285
      for (section = abfd->sections; section != NULL; section = section->next)
1286
	{
1287
	  datasize = section->size;
1288
	  if (addr >= section->vma && addr < section->vma + datasize)
1289
	    break;
1290
	}
1291
 
1292
      if (section == NULL)
1293
	{
1294
	  fprintf (file,
1295
		   _("\nThere is an import table, but the section containing it could not be found\n"));
1296
	  return TRUE;
1297
	}
6324 serge 1298
      else if (!(section->flags & SEC_HAS_CONTENTS))
1299
        {
1300
	  fprintf (file,
1301
		   _("\nThere is an import table in %s, but that section has no contents\n"),
1302
		   section->name);
1303
	  return TRUE;
1304
        }
5197 serge 1305
    }
1306
 
1307
  fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1308
	   section->name, (unsigned long) addr);
1309
 
1310
  dataoff = addr - section->vma;
1311
 
1312
#ifdef POWERPC_LE_PE
1313
  if (rel_section != 0 && rel_section->size != 0)
1314
    {
1315
      /* The toc address can be found by taking the starting address,
1316
	 which on the PPC locates a function descriptor. The
1317
	 descriptor consists of the function code starting address
1318
	 followed by the address of the toc. The starting address we
1319
	 get from the bfd, and the descriptor is supposed to be in the
1320
	 .reldata section.  */
1321
 
1322
      bfd_vma loadable_toc_address;
1323
      bfd_vma toc_address;
1324
      bfd_vma start_address;
1325
      bfd_byte *data;
1326
      bfd_vma offset;
1327
 
1328
      if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
1329
	{
1330
	  if (data != NULL)
1331
	    free (data);
1332
	  return FALSE;
1333
	}
1334
 
1335
      offset = abfd->start_address - rel_section->vma;
1336
 
1337
      if (offset >= rel_section->size || offset + 8 > rel_section->size)
1338
        {
1339
          if (data != NULL)
1340
            free (data);
1341
          return FALSE;
1342
        }
1343
 
1344
      start_address = bfd_get_32 (abfd, data + offset);
1345
      loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
1346
      toc_address = loadable_toc_address - 32768;
1347
 
1348
      fprintf (file,
1349
	       _("\nFunction descriptor located at the start address: %04lx\n"),
1350
	       (unsigned long int) (abfd->start_address));
1351
      fprintf (file,
1352
	       _("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
1353
	       start_address, loadable_toc_address, toc_address);
1354
      if (data != NULL)
1355
	free (data);
1356
    }
1357
  else
1358
    {
1359
      fprintf (file,
1360
	       _("\nNo reldata section! Function descriptor not decoded.\n"));
1361
    }
1362
#endif
1363
 
1364
  fprintf (file,
1365
	   _("\nThe Import Tables (interpreted %s section contents)\n"),
1366
	   section->name);
1367
  fprintf (file,
1368
	   _("\
1369
 vma:            Hint    Time      Forward  DLL       First\n\
1370
                 Table   Stamp     Chain    Name      Thunk\n"));
1371
 
1372
  /* Read the whole section.  Some of the fields might be before dataoff.  */
1373
  if (!bfd_malloc_and_get_section (abfd, section, &data))
1374
    {
1375
      if (data != NULL)
1376
	free (data);
1377
      return FALSE;
1378
    }
1379
 
1380
  adj = section->vma - extra->ImageBase;
1381
 
1382
  /* Print all image import descriptors.  */
1383
  for (i = dataoff; i + onaline <= datasize; i += onaline)
1384
    {
1385
      bfd_vma hint_addr;
1386
      bfd_vma time_stamp;
1387
      bfd_vma forward_chain;
1388
      bfd_vma dll_name;
1389
      bfd_vma first_thunk;
1390
      int idx = 0;
1391
      bfd_size_type j;
1392
      char *dll;
1393
 
1394
      /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress).  */
1395
      fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1396
      hint_addr = bfd_get_32 (abfd, data + i);
1397
      time_stamp = bfd_get_32 (abfd, data + i + 4);
1398
      forward_chain = bfd_get_32 (abfd, data + i + 8);
1399
      dll_name = bfd_get_32 (abfd, data + i + 12);
1400
      first_thunk = bfd_get_32 (abfd, data + i + 16);
1401
 
1402
      fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1403
	       (unsigned long) hint_addr,
1404
	       (unsigned long) time_stamp,
1405
	       (unsigned long) forward_chain,
1406
	       (unsigned long) dll_name,
1407
	       (unsigned long) first_thunk);
1408
 
1409
      if (hint_addr == 0 && first_thunk == 0)
1410
	break;
1411
 
1412
      if (dll_name - adj >= section->size)
1413
        break;
1414
 
1415
      dll = (char *) data + dll_name - adj;
6324 serge 1416
      /* PR 17512 file: 078-12277-0.004.  */
1417
      bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1418
      fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
5197 serge 1419
 
1420
      if (hint_addr != 0)
1421
	{
1422
	  bfd_byte *ft_data;
1423
	  asection *ft_section;
1424
	  bfd_vma ft_addr;
1425
	  bfd_size_type ft_datasize;
1426
	  int ft_idx;
1427
	  int ft_allocated;
1428
 
1429
	  fprintf (file, _("\tvma:  Hint/Ord Member-Name Bound-To\n"));
1430
 
1431
	  idx = hint_addr - adj;
1432
 
1433
	  ft_addr = first_thunk + extra->ImageBase;
1434
	  ft_idx = first_thunk - adj;
1435
	  ft_data = data + ft_idx;
1436
	  ft_datasize = datasize - ft_idx;
1437
	  ft_allocated = 0;
1438
 
1439
	  if (first_thunk != hint_addr)
1440
	    {
1441
	      /* Find the section which contains the first thunk.  */
1442
	      for (ft_section = abfd->sections;
1443
		   ft_section != NULL;
1444
		   ft_section = ft_section->next)
1445
		{
1446
		  if (ft_addr >= ft_section->vma
1447
		      && ft_addr < ft_section->vma + ft_section->size)
1448
		    break;
1449
		}
1450
 
1451
	      if (ft_section == NULL)
1452
		{
1453
		  fprintf (file,
1454
		       _("\nThere is a first thunk, but the section containing it could not be found\n"));
1455
		  continue;
1456
		}
1457
 
1458
	      /* Now check to see if this section is the same as our current
1459
		 section.  If it is not then we will have to load its data in.  */
1460
	      if (ft_section != section)
1461
		{
1462
		  ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1463
		  ft_datasize = ft_section->size - ft_idx;
1464
		  ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1465
		  if (ft_data == NULL)
1466
		    continue;
1467
 
1468
		  /* Read ft_datasize bytes starting at offset ft_idx.  */
1469
		  if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1470
						 (bfd_vma) ft_idx, ft_datasize))
1471
		    {
1472
		      free (ft_data);
1473
		      continue;
1474
		    }
1475
		  ft_allocated = 1;
1476
		}
1477
	    }
1478
 
1479
	  /* Print HintName vector entries.  */
1480
#ifdef COFF_WITH_pex64
1481
	  for (j = 0; idx + j + 8 <= datasize; j += 8)
1482
	    {
6324 serge 1483
	      bfd_size_type amt;
5197 serge 1484
	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
1485
	      unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1486
 
1487
	      if (!member && !member_high)
1488
		break;
1489
 
6324 serge 1490
	      amt = member - adj;
1491
 
1492
	      if (HighBitSet (member_high))
5197 serge 1493
		fprintf (file, "\t%lx%08lx\t %4lx%08lx  ",
6324 serge 1494
			 member_high, member,
1495
			 WithoutHighBit (member_high), member);
1496
	      /* PR binutils/17512: Handle corrupt PE data.  */
1497
	      else if (amt + 2 >= datasize)
1498
		fprintf (file, _("\t"), member);
5197 serge 1499
	      else
1500
		{
1501
		  int ordinal;
1502
		  char *member_name;
1503
 
6324 serge 1504
		  ordinal = bfd_get_16 (abfd, data + amt);
1505
		  member_name = (char *) data + amt + 2;
1506
		  fprintf (file, "\t%04lx\t %4d  %.*s",member, ordinal,
1507
			   (int) (datasize - (amt + 2)), member_name);
5197 serge 1508
		}
1509
 
1510
	      /* If the time stamp is not zero, the import address
1511
		 table holds actual addresses.  */
1512
	      if (time_stamp != 0
1513
		  && first_thunk != 0
1514
		  && first_thunk != hint_addr
1515
		  && j + 4 <= ft_datasize)
1516
		fprintf (file, "\t%04lx",
1517
			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1518
	      fprintf (file, "\n");
1519
	    }
1520
#else
1521
	  for (j = 0; idx + j + 4 <= datasize; j += 4)
1522
	    {
6324 serge 1523
	      bfd_size_type amt;
5197 serge 1524
	      unsigned long member = bfd_get_32 (abfd, data + idx + j);
1525
 
1526
	      /* Print single IMAGE_IMPORT_BY_NAME vector.  */
1527
	      if (member == 0)
1528
		break;
1529
 
6324 serge 1530
	      amt = member - adj;
1531
	      if (HighBitSet (member))
5197 serge 1532
		fprintf (file, "\t%04lx\t %4lu  ",
6324 serge 1533
			 member, WithoutHighBit (member));
1534
	      /* PR binutils/17512: Handle corrupt PE data.  */
1535
	      else if (amt + 2 >= datasize)
1536
		fprintf (file, _("\t"), member);
5197 serge 1537
	      else
1538
		{
1539
		  int ordinal;
1540
		  char *member_name;
1541
 
6324 serge 1542
		  ordinal = bfd_get_16 (abfd, data + amt);
1543
		  member_name = (char *) data + amt + 2;
1544
		  fprintf (file, "\t%04lx\t %4d  %.*s",
1545
			   member, ordinal,
1546
			   (int) (datasize - (amt + 2)), member_name);
5197 serge 1547
		}
1548
 
1549
	      /* If the time stamp is not zero, the import address
1550
		 table holds actual addresses.  */
1551
	      if (time_stamp != 0
1552
		  && first_thunk != 0
1553
		  && first_thunk != hint_addr
1554
		  && j + 4 <= ft_datasize)
1555
		fprintf (file, "\t%04lx",
1556
			 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1557
 
1558
	      fprintf (file, "\n");
1559
	    }
1560
#endif
1561
	  if (ft_allocated)
1562
	    free (ft_data);
1563
	}
1564
 
1565
      fprintf (file, "\n");
1566
    }
1567
 
1568
  free (data);
1569
 
1570
  return TRUE;
1571
}
1572
 
1573
static bfd_boolean
1574
pe_print_edata (bfd * abfd, void * vfile)
1575
{
1576
  FILE *file = (FILE *) vfile;
1577
  bfd_byte *data;
1578
  asection *section;
1579
  bfd_size_type datasize = 0;
1580
  bfd_size_type dataoff;
1581
  bfd_size_type i;
6324 serge 1582
  bfd_vma       adj;
5197 serge 1583
  struct EDT_type
1584
  {
1585
    long export_flags;          /* Reserved - should be zero.  */
1586
    long time_stamp;
1587
    short major_ver;
1588
    short minor_ver;
1589
    bfd_vma name;               /* RVA - relative to image base.  */
1590
    long base;                  /* Ordinal base.  */
1591
    unsigned long num_functions;/* Number in the export address table.  */
1592
    unsigned long num_names;    /* Number in the name pointer table.  */
1593
    bfd_vma eat_addr;		/* RVA to the export address table.  */
1594
    bfd_vma npt_addr;		/* RVA to the Export Name Pointer Table.  */
1595
    bfd_vma ot_addr;		/* RVA to the Ordinal Table.  */
1596
  } edt;
1597
 
1598
  pe_data_type *pe = pe_data (abfd);
1599
  struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1600
 
1601
  bfd_vma addr;
1602
 
1603
  addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1604
 
1605
  if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1606
    {
1607
      /* Maybe the extra header isn't there.  Look for the section.  */
1608
      section = bfd_get_section_by_name (abfd, ".edata");
1609
      if (section == NULL)
1610
	return TRUE;
1611
 
1612
      addr = section->vma;
1613
      dataoff = 0;
1614
      datasize = section->size;
1615
      if (datasize == 0)
1616
	return TRUE;
1617
    }
1618
  else
1619
    {
1620
      addr += extra->ImageBase;
1621
 
1622
      for (section = abfd->sections; section != NULL; section = section->next)
1623
	if (addr >= section->vma && addr < section->vma + section->size)
1624
	  break;
1625
 
1626
      if (section == NULL)
1627
	{
1628
	  fprintf (file,
1629
		   _("\nThere is an export table, but the section containing it could not be found\n"));
1630
	  return TRUE;
1631
	}
6324 serge 1632
      else if (!(section->flags & SEC_HAS_CONTENTS))
1633
        {
1634
	  fprintf (file,
1635
		   _("\nThere is an export table in %s, but that section has no contents\n"),
1636
		   section->name);
1637
	  return TRUE;
1638
        }
5197 serge 1639
 
1640
      dataoff = addr - section->vma;
1641
      datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1642
      if (datasize > section->size - dataoff)
1643
	{
1644
	  fprintf (file,
1645
		   _("\nThere is an export table in %s, but it does not fit into that section\n"),
1646
		   section->name);
1647
	  return TRUE;
1648
	}
1649
    }
1650
 
6324 serge 1651
  /* PR 17512: Handle corrupt PE binaries.  */
1652
  if (datasize < 36)
1653
    {
1654
      fprintf (file,
1655
	       _("\nThere is an export table in %s, but it is too small (%d)\n"),
1656
	       section->name, (int) datasize);
1657
      return TRUE;
1658
    }
1659
 
5197 serge 1660
  fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1661
	   section->name, (unsigned long) addr);
1662
 
1663
  data = (bfd_byte *) bfd_malloc (datasize);
1664
  if (data == NULL)
1665
    return FALSE;
1666
 
1667
  if (! bfd_get_section_contents (abfd, section, data,
1668
				  (file_ptr) dataoff, datasize))
1669
    return FALSE;
1670
 
1671
  /* Go get Export Directory Table.  */
1672
  edt.export_flags   = bfd_get_32 (abfd, data +  0);
1673
  edt.time_stamp     = bfd_get_32 (abfd, data +  4);
1674
  edt.major_ver      = bfd_get_16 (abfd, data +  8);
1675
  edt.minor_ver      = bfd_get_16 (abfd, data + 10);
1676
  edt.name           = bfd_get_32 (abfd, data + 12);
1677
  edt.base           = bfd_get_32 (abfd, data + 16);
1678
  edt.num_functions  = bfd_get_32 (abfd, data + 20);
1679
  edt.num_names      = bfd_get_32 (abfd, data + 24);
1680
  edt.eat_addr       = bfd_get_32 (abfd, data + 28);
1681
  edt.npt_addr       = bfd_get_32 (abfd, data + 32);
1682
  edt.ot_addr        = bfd_get_32 (abfd, data + 36);
1683
 
1684
  adj = section->vma - extra->ImageBase + dataoff;
1685
 
1686
  /* Dump the EDT first.  */
1687
  fprintf (file,
1688
	   _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1689
	   section->name);
1690
 
1691
  fprintf (file,
1692
	   _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1693
 
1694
  fprintf (file,
1695
	   _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1696
 
1697
  fprintf (file,
1698
	   _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1699
 
1700
  fprintf (file,
1701
	   _("Name \t\t\t\t"));
1702
  bfd_fprintf_vma (abfd, file, edt.name);
1703
 
6324 serge 1704
  if ((edt.name >= adj) && (edt.name < adj + datasize))
1705
    fprintf (file, " %.*s\n",
1706
	     (int) (datasize - (edt.name - adj)),
1707
	     data + edt.name - adj);
1708
  else
1709
    fprintf (file, "(outside .edata section)\n");
1710
 
5197 serge 1711
  fprintf (file,
1712
	   _("Ordinal Base \t\t\t%ld\n"), edt.base);
1713
 
1714
  fprintf (file,
1715
	   _("Number in:\n"));
1716
 
1717
  fprintf (file,
1718
	   _("\tExport Address Table \t\t%08lx\n"),
1719
	   edt.num_functions);
1720
 
1721
  fprintf (file,
1722
	   _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1723
 
1724
  fprintf (file,
1725
	   _("Table Addresses\n"));
1726
 
1727
  fprintf (file,
1728
	   _("\tExport Address Table \t\t"));
1729
  bfd_fprintf_vma (abfd, file, edt.eat_addr);
1730
  fprintf (file, "\n");
1731
 
1732
  fprintf (file,
1733
	   _("\tName Pointer Table \t\t"));
1734
  bfd_fprintf_vma (abfd, file, edt.npt_addr);
1735
  fprintf (file, "\n");
1736
 
1737
  fprintf (file,
1738
	   _("\tOrdinal Table \t\t\t"));
1739
  bfd_fprintf_vma (abfd, file, edt.ot_addr);
1740
  fprintf (file, "\n");
1741
 
1742
  /* The next table to find is the Export Address Table. It's basically
1743
     a list of pointers that either locate a function in this dll, or
1744
     forward the call to another dll. Something like:
1745
      typedef union
1746
      {
1747
        long export_rva;
1748
        long forwarder_rva;
1749
      } export_address_table_entry;  */
1750
 
1751
  fprintf (file,
1752
	  _("\nExport Address Table -- Ordinal Base %ld\n"),
1753
	  edt.base);
1754
 
6324 serge 1755
  /* PR 17512: Handle corrupt PE binaries.  */
1756
  if (edt.eat_addr + (edt.num_functions * 4) - adj >= datasize
1757
      /* PR 17512: file: 092b1829 */
1758
      || (edt.num_functions * 4) < edt.num_functions
1759
      /* PR 17512 file: 140-165018-0.004.  */
1760
      || data + edt.eat_addr - adj < data)
1761
    fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1762
	     (long) edt.eat_addr,
1763
	     (long) edt.num_functions);
1764
  else for (i = 0; i < edt.num_functions; ++i)
5197 serge 1765
    {
1766
      bfd_vma eat_member = bfd_get_32 (abfd,
1767
				       data + edt.eat_addr + (i * 4) - adj);
1768
      if (eat_member == 0)
1769
	continue;
1770
 
1771
      if (eat_member - adj <= datasize)
1772
	{
1773
	  /* This rva is to a name (forwarding function) in our section.  */
1774
	  /* Should locate a function descriptor.  */
1775
	  fprintf (file,
6324 serge 1776
		   "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
5197 serge 1777
		   (long) i,
1778
		   (long) (i + edt.base),
1779
		   (unsigned long) eat_member,
1780
		   _("Forwarder RVA"),
6324 serge 1781
		   (int)(datasize - (eat_member - adj)),
5197 serge 1782
		   data + eat_member - adj);
1783
	}
1784
      else
1785
	{
1786
	  /* Should locate a function descriptor in the reldata section.  */
1787
	  fprintf (file,
1788
		   "\t[%4ld] +base[%4ld] %04lx %s\n",
1789
		   (long) i,
1790
		   (long) (i + edt.base),
1791
		   (unsigned long) eat_member,
1792
		   _("Export RVA"));
1793
	}
1794
    }
1795
 
1796
  /* The Export Name Pointer Table is paired with the Export Ordinal Table.  */
1797
  /* Dump them in parallel for clarity.  */
1798
  fprintf (file,
1799
	   _("\n[Ordinal/Name Pointer] Table\n"));
1800
 
6324 serge 1801
  /* PR 17512: Handle corrupt PE binaries.  */
1802
  if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1803
      /* PR 17512: file: bb68816e.  */
1804
      || edt.num_names * 4 < edt.num_names
1805
      || (data + edt.npt_addr - adj) < data)
1806
    fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1807
	     (long) edt.npt_addr,
1808
	     (long) edt.num_names);
1809
  /* PR 17512: file: 140-147171-0.004.  */
1810
  else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1811
	   || data + edt.ot_addr - adj < data)
1812
    fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1813
	     (long) edt.ot_addr,
1814
	     (long) edt.num_names);
1815
  else for (i = 0; i < edt.num_names; ++i)
5197 serge 1816
    {
6324 serge 1817
      bfd_vma  name_ptr;
1818
      bfd_vma  ord;
5197 serge 1819
 
6324 serge 1820
      ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1821
      name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
5197 serge 1822
 
6324 serge 1823
      if ((name_ptr - adj) >= datasize)
1824
	{
1825
	  fprintf (file, _("\t[%4ld] \n"),
1826
		   (long) ord, (long) name_ptr);
1827
	}
1828
      else
1829
    {
1830
	  char * name = (char *) data + name_ptr - adj;
1831
 
1832
	  fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
1833
		   (int)((char *)(data + datasize) - name), name);
1834
	}
5197 serge 1835
    }
1836
 
1837
  free (data);
1838
 
1839
  return TRUE;
1840
}
1841
 
1842
/* This really is architecture dependent.  On IA-64, a .pdata entry
1843
   consists of three dwords containing relative virtual addresses that
1844
   specify the start and end address of the code range the entry
1845
   covers and the address of the corresponding unwind info data.
1846
 
1847
   On ARM and SH-4, a compressed PDATA structure is used :
1848
   _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1849
   _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1850
   See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1851
 
1852
   This is the version for uncompressed data.  */
1853
 
1854
static bfd_boolean
1855
pe_print_pdata (bfd * abfd, void * vfile)
1856
{
1857
#if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1858
# define PDATA_ROW_SIZE	(3 * 8)
1859
#else
1860
# define PDATA_ROW_SIZE	(5 * 4)
1861
#endif
1862
  FILE *file = (FILE *) vfile;
1863
  bfd_byte *data = 0;
1864
  asection *section = bfd_get_section_by_name (abfd, ".pdata");
1865
  bfd_size_type datasize = 0;
1866
  bfd_size_type i;
1867
  bfd_size_type start, stop;
1868
  int onaline = PDATA_ROW_SIZE;
1869
 
1870
  if (section == NULL
1871
      || coff_section_data (abfd, section) == NULL
1872
      || pei_section_data (abfd, section) == NULL)
1873
    return TRUE;
1874
 
1875
  stop = pei_section_data (abfd, section)->virt_size;
1876
  if ((stop % onaline) != 0)
1877
    fprintf (file,
1878
	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
1879
	     (long) stop, onaline);
1880
 
1881
  fprintf (file,
1882
	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
1883
#if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1884
  fprintf (file,
1885
	   _(" vma:\t\t\tBegin Address    End Address      Unwind Info\n"));
1886
#else
1887
  fprintf (file, _("\
1888
 vma:\t\tBegin    End      EH       EH       PrologEnd  Exception\n\
1889
     \t\tAddress  Address  Handler  Data     Address    Mask\n"));
1890
#endif
1891
 
1892
  datasize = section->size;
1893
  if (datasize == 0)
1894
    return TRUE;
1895
 
6324 serge 1896
  /* PR 17512: file: 002-193900-0.004.  */
1897
  if (datasize < stop)
1898
    {
1899
      fprintf (file, _("Virtual size of .pdata section (%ld) larger than real size (%ld)\n"),
1900
	       (long) stop, (long) datasize);
1901
      return FALSE;
1902
    }
1903
 
5197 serge 1904
  if (! bfd_malloc_and_get_section (abfd, section, &data))
1905
    {
1906
      if (data != NULL)
1907
	free (data);
1908
      return FALSE;
1909
    }
1910
 
1911
  start = 0;
1912
 
1913
  for (i = start; i < stop; i += onaline)
1914
    {
1915
      bfd_vma begin_addr;
1916
      bfd_vma end_addr;
1917
      bfd_vma eh_handler;
1918
      bfd_vma eh_data;
1919
      bfd_vma prolog_end_addr;
1920
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1921
      int em_data;
1922
#endif
1923
 
1924
      if (i + PDATA_ROW_SIZE > stop)
1925
	break;
1926
 
1927
      begin_addr      = GET_PDATA_ENTRY (abfd, data + i     );
1928
      end_addr        = GET_PDATA_ENTRY (abfd, data + i +  4);
1929
      eh_handler      = GET_PDATA_ENTRY (abfd, data + i +  8);
1930
      eh_data         = GET_PDATA_ENTRY (abfd, data + i + 12);
1931
      prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1932
 
1933
      if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1934
	  && eh_data == 0 && prolog_end_addr == 0)
1935
	/* We are probably into the padding of the section now.  */
1936
	break;
1937
 
1938
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1939
      em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1940
#endif
1941
      eh_handler &= ~(bfd_vma) 0x3;
1942
      prolog_end_addr &= ~(bfd_vma) 0x3;
1943
 
1944
      fputc (' ', file);
1945
      bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1946
      bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1947
      bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1948
      bfd_fprintf_vma (abfd, file, eh_handler);
1949
#if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1950
      fputc (' ', file);
1951
      bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1952
      bfd_fprintf_vma (abfd, file, prolog_end_addr);
1953
      fprintf (file, "   %x", em_data);
1954
#endif
1955
 
1956
#ifdef POWERPC_LE_PE
1957
      if (eh_handler == 0 && eh_data != 0)
1958
	{
1959
	  /* Special bits here, although the meaning may be a little
1960
	     mysterious. The only one I know for sure is 0x03
1961
	     Code Significance
1962
	     0x00 None
1963
	     0x01 Register Save Millicode
1964
	     0x02 Register Restore Millicode
1965
	     0x03 Glue Code Sequence.  */
1966
	  switch (eh_data)
1967
	    {
1968
	    case 0x01:
1969
	      fprintf (file, _(" Register save millicode"));
1970
	      break;
1971
	    case 0x02:
1972
	      fprintf (file, _(" Register restore millicode"));
1973
	      break;
1974
	    case 0x03:
1975
	      fprintf (file, _(" Glue code sequence"));
1976
	      break;
1977
	    default:
1978
	      break;
1979
	    }
1980
	}
1981
#endif
1982
      fprintf (file, "\n");
1983
    }
1984
 
1985
  free (data);
1986
 
1987
  return TRUE;
1988
#undef PDATA_ROW_SIZE
1989
}
1990
 
1991
typedef struct sym_cache
1992
{
1993
  int        symcount;
1994
  asymbol ** syms;
1995
} sym_cache;
1996
 
1997
static asymbol **
1998
slurp_symtab (bfd *abfd, sym_cache *psc)
1999
{
2000
  asymbol ** sy = NULL;
2001
  long storage;
2002
 
2003
  if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
2004
    {
2005
      psc->symcount = 0;
2006
      return NULL;
2007
    }
2008
 
2009
  storage = bfd_get_symtab_upper_bound (abfd);
2010
  if (storage < 0)
2011
    return NULL;
2012
  if (storage)
6324 serge 2013
    {
5197 serge 2014
    sy = (asymbol **) bfd_malloc (storage);
6324 serge 2015
      if (sy == NULL)
2016
	return NULL;
2017
    }
5197 serge 2018
 
2019
  psc->symcount = bfd_canonicalize_symtab (abfd, sy);
2020
  if (psc->symcount < 0)
2021
    return NULL;
2022
  return sy;
2023
}
2024
 
2025
static const char *
2026
my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
2027
{
2028
  int i;
2029
 
2030
  if (psc->syms == 0)
2031
    psc->syms = slurp_symtab (abfd, psc);
2032
 
2033
  for (i = 0; i < psc->symcount; i++)
2034
    {
2035
      if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
2036
	return psc->syms[i]->name;
2037
    }
2038
 
2039
  return NULL;
2040
}
2041
 
2042
static void
2043
cleanup_syms (sym_cache *psc)
2044
{
2045
  psc->symcount = 0;
2046
  free (psc->syms);
2047
  psc->syms = NULL;
2048
}
2049
 
2050
/* This is the version for "compressed" pdata.  */
2051
 
2052
bfd_boolean
2053
_bfd_pe_print_ce_compressed_pdata (bfd * abfd, void * vfile)
2054
{
2055
# define PDATA_ROW_SIZE	(2 * 4)
2056
  FILE *file = (FILE *) vfile;
2057
  bfd_byte *data = NULL;
2058
  asection *section = bfd_get_section_by_name (abfd, ".pdata");
2059
  bfd_size_type datasize = 0;
2060
  bfd_size_type i;
2061
  bfd_size_type start, stop;
2062
  int onaline = PDATA_ROW_SIZE;
2063
  struct sym_cache cache = {0, 0} ;
2064
 
2065
  if (section == NULL
2066
      || coff_section_data (abfd, section) == NULL
2067
      || pei_section_data (abfd, section) == NULL)
2068
    return TRUE;
2069
 
2070
  stop = pei_section_data (abfd, section)->virt_size;
2071
  if ((stop % onaline) != 0)
2072
    fprintf (file,
2073
	     _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
2074
	     (long) stop, onaline);
2075
 
2076
  fprintf (file,
2077
	   _("\nThe Function Table (interpreted .pdata section contents)\n"));
2078
 
2079
  fprintf (file, _("\
2080
 vma:\t\tBegin    Prolog   Function Flags    Exception EH\n\
2081
     \t\tAddress  Length   Length   32b exc  Handler   Data\n"));
2082
 
2083
  datasize = section->size;
2084
  if (datasize == 0)
2085
    return TRUE;
2086
 
2087
  if (! bfd_malloc_and_get_section (abfd, section, &data))
2088
    {
2089
      if (data != NULL)
2090
	free (data);
2091
      return FALSE;
2092
    }
2093
 
2094
  start = 0;
2095
 
2096
  for (i = start; i < stop; i += onaline)
2097
    {
2098
      bfd_vma begin_addr;
2099
      bfd_vma other_data;
2100
      bfd_vma prolog_length, function_length;
2101
      int flag32bit, exception_flag;
2102
      asection *tsection;
2103
 
2104
      if (i + PDATA_ROW_SIZE > stop)
2105
	break;
2106
 
2107
      begin_addr = GET_PDATA_ENTRY (abfd, data + i     );
2108
      other_data = GET_PDATA_ENTRY (abfd, data + i +  4);
2109
 
2110
      if (begin_addr == 0 && other_data == 0)
2111
	/* We are probably into the padding of the section now.  */
2112
	break;
2113
 
2114
      prolog_length = (other_data & 0x000000FF);
2115
      function_length = (other_data & 0x3FFFFF00) >> 8;
2116
      flag32bit = (int)((other_data & 0x40000000) >> 30);
2117
      exception_flag = (int)((other_data & 0x80000000) >> 31);
2118
 
2119
      fputc (' ', file);
2120
      bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2121
      bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2122
      bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2123
      bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2124
      fprintf (file, "%2d  %2d   ", flag32bit, exception_flag);
2125
 
2126
      /* Get the exception handler's address and the data passed from the
2127
         .text section. This is really the data that belongs with the .pdata
2128
         but got "compressed" out for the ARM and SH4 architectures.  */
2129
      tsection = bfd_get_section_by_name (abfd, ".text");
2130
      if (tsection && coff_section_data (abfd, tsection)
2131
	  && pei_section_data (abfd, tsection))
2132
	{
2133
	  bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2134
	  bfd_byte *tdata;
2135
 
2136
	  tdata = (bfd_byte *) bfd_malloc (8);
2137
	  if (tdata)
2138
	    {
2139
	      if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2140
		{
2141
		  bfd_vma eh, eh_data;
2142
 
2143
		  eh = bfd_get_32 (abfd, tdata);
2144
		  eh_data = bfd_get_32 (abfd, tdata + 4);
2145
		  fprintf (file, "%08x  ", (unsigned int) eh);
2146
		  fprintf (file, "%08x", (unsigned int) eh_data);
2147
		  if (eh != 0)
2148
		    {
2149
		      const char *s = my_symbol_for_address (abfd, eh, &cache);
2150
 
2151
		      if (s)
2152
			fprintf (file, " (%s) ", s);
2153
		    }
2154
		}
2155
	      free (tdata);
2156
	    }
2157
	}
2158
 
2159
      fprintf (file, "\n");
2160
    }
2161
 
2162
  free (data);
2163
 
2164
  cleanup_syms (& cache);
2165
 
2166
  return TRUE;
2167
#undef PDATA_ROW_SIZE
2168
}
2169
 
2170
 
2171
#define IMAGE_REL_BASED_HIGHADJ 4
2172
static const char * const tbl[] =
2173
{
2174
  "ABSOLUTE",
2175
  "HIGH",
2176
  "LOW",
2177
  "HIGHLOW",
2178
  "HIGHADJ",
2179
  "MIPS_JMPADDR",
2180
  "SECTION",
2181
  "REL32",
2182
  "RESERVED1",
2183
  "MIPS_JMPADDR16",
2184
  "DIR64",
2185
  "HIGH3ADJ",
2186
  "UNKNOWN",   /* MUST be last.  */
2187
};
2188
 
2189
static bfd_boolean
2190
pe_print_reloc (bfd * abfd, void * vfile)
2191
{
2192
  FILE *file = (FILE *) vfile;
2193
  bfd_byte *data = 0;
2194
  asection *section = bfd_get_section_by_name (abfd, ".reloc");
6324 serge 2195
  bfd_byte *p, *end;
5197 serge 2196
 
6324 serge 2197
  if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS))
5197 serge 2198
    return TRUE;
2199
 
2200
  fprintf (file,
2201
	   _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2202
 
2203
  if (! bfd_malloc_and_get_section (abfd, section, &data))
2204
    {
2205
      if (data != NULL)
2206
	free (data);
2207
      return FALSE;
2208
    }
2209
 
6324 serge 2210
  p = data;
2211
  end = data + section->size;
2212
  while (p + 8 <= end)
5197 serge 2213
    {
2214
      int j;
2215
      bfd_vma virtual_address;
6324 serge 2216
      unsigned long number, size;
2217
      bfd_byte *chunk_end;
5197 serge 2218
 
2219
      /* The .reloc section is a sequence of blocks, with a header consisting
2220
	 of two 32 bit quantities, followed by a number of 16 bit entries.  */
6324 serge 2221
      virtual_address = bfd_get_32 (abfd, p);
2222
      size = bfd_get_32 (abfd, p + 4);
2223
      p += 8;
5197 serge 2224
      number = (size - 8) / 2;
2225
 
2226
      if (size == 0)
2227
	break;
2228
 
2229
      fprintf (file,
2230
	       _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
6324 serge 2231
	       (unsigned long) virtual_address, size, size, number);
5197 serge 2232
 
6324 serge 2233
      chunk_end = p + size;
2234
      if (chunk_end > end)
2235
	chunk_end = end;
2236
      j = 0;
2237
      while (p + 2 <= chunk_end)
5197 serge 2238
	{
6324 serge 2239
	  unsigned short e = bfd_get_16 (abfd, p);
5197 serge 2240
	  unsigned int t = (e & 0xF000) >> 12;
2241
	  int off = e & 0x0FFF;
2242
 
2243
	  if (t >= sizeof (tbl) / sizeof (tbl[0]))
2244
	    t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2245
 
2246
	  fprintf (file,
2247
		   _("\treloc %4d offset %4x [%4lx] %s"),
2248
		   j, off, (unsigned long) (off + virtual_address), tbl[t]);
2249
 
6324 serge 2250
	  p += 2;
2251
	  j++;
2252
 
5197 serge 2253
	  /* HIGHADJ takes an argument, - the next record *is* the
2254
	     low 16 bits of addend.  */
6324 serge 2255
	  if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
5197 serge 2256
	    {
6324 serge 2257
	      fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2258
	      p += 2;
5197 serge 2259
	      j++;
2260
	    }
2261
 
2262
	  fprintf (file, "\n");
2263
	}
6324 serge 2264
    }
5197 serge 2265
 
6324 serge 2266
  free (data);
2267
 
2268
  return TRUE;
2269
}
2270
 
2271
/* A data structure describing the regions of a .rsrc section.
2272
   Some fields are filled in as the section is parsed.  */
2273
 
2274
typedef struct rsrc_regions
2275
{
2276
  bfd_byte * section_start;
2277
  bfd_byte * section_end;
2278
  bfd_byte * strings_start;
2279
  bfd_byte * resource_start;
2280
} rsrc_regions;
2281
 
2282
static bfd_byte *
2283
rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2284
			       rsrc_regions *, bfd_vma);
2285
 
2286
/* Print the resource entry at DATA, with the text indented by INDENT.
2287
   Recusively calls rsrc_print_resource_directory to print the contents
2288
   of directory entries.
2289
   Returns the address of the end of the data associated with the entry
2290
   or section_end + 1 upon failure.  */
2291
 
2292
static bfd_byte *
2293
rsrc_print_resource_entries (FILE *         file,
2294
			     bfd *          abfd,
2295
			     unsigned int   indent,
2296
			     bfd_boolean    is_name,
2297
			     bfd_byte *     data,
2298
			     rsrc_regions * regions,
2299
			     bfd_vma        rva_bias)
2300
{
2301
  unsigned long entry, addr, size;
2302
  bfd_byte * leaf;
2303
 
2304
  if (data + 8 >= regions->section_end)
2305
    return regions->section_end + 1;
2306
 
2307
  fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2308
 
2309
  entry = (unsigned long) bfd_get_32 (abfd, data);
2310
  if (is_name)
2311
    {
2312
      bfd_byte * name;
2313
 
2314
      /* Note - the documentation says that this field is an RVA value
2315
	 but windres appears to produce a section relative offset with
2316
	 the top bit set.  Support both styles for now.  */
2317
      if (HighBitSet (entry))
2318
	name = regions->section_start + WithoutHighBit (entry);
2319
      else
2320
	name = regions->section_start + entry - rva_bias;
2321
 
2322
      if (name + 2 < regions->section_end && name > regions->section_start)
2323
	{
2324
	  unsigned int len;
2325
 
2326
	  if (regions->strings_start == NULL)
2327
	    regions->strings_start = name;
2328
 
2329
	  len = bfd_get_16 (abfd, name);
2330
 
2331
	  fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2332
 
2333
	  if (name + 2 + len * 2 < regions->section_end)
2334
	    {
2335
	      /* This strange loop is to cope with multibyte characters.  */
2336
	      while (len --)
2337
		{
2338
		  char c;
2339
 
2340
		  name += 2;
2341
		  c = * name;
2342
		  /* Avoid printing control characters.  */
2343
		  if (c > 0 && c < 32)
2344
		    fprintf (file, "^%c", c + 64);
2345
		  else
2346
		    fprintf (file, "%.1s", name);
2347
		}
2348
	    }
2349
	  else
2350
	    {
2351
	      fprintf (file, _("\n"), len);
2352
	      /* PR binutils/17512: Do not try to continue decoding a
2353
		 corrupted resource section.  It is likely to end up with
2354
		 reams of extraneous output.  FIXME: We could probably
2355
		 continue if we disable the printing of strings...  */
2356
	      return regions->section_end + 1;
2357
	    }
2358
	}
2359
      else
2360
	{
2361
	  fprintf (file, _("\n"), entry);
2362
	  return regions->section_end + 1;
2363
	}
5197 serge 2364
    }
6324 serge 2365
  else
2366
    fprintf (file, _("ID: %#08lx"), entry);
5197 serge 2367
 
6324 serge 2368
  entry = (long) bfd_get_32 (abfd, data + 4);
2369
  fprintf (file, _(", Value: %#08lx\n"), entry);
2370
 
2371
  if (HighBitSet  (entry))
2372
    {
2373
      data = regions->section_start + WithoutHighBit (entry);
2374
      if (data <= regions->section_start || data > regions->section_end)
2375
	return regions->section_end + 1;
2376
 
2377
      /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2378
	 in the resource table.  We need some way to detect this.  */
2379
      return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2380
					    regions, rva_bias);
2381
    }
2382
 
2383
  leaf = regions->section_start + entry;
2384
 
2385
  if (leaf + 16 >= regions->section_end
2386
      /* PR 17512: file: 055dff7e.  */
2387
      || leaf < regions->section_start)
2388
    return regions->section_end + 1;
2389
 
2390
  fprintf (file, _("%03x %*.s  Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2391
	   (int) (entry), indent, " ",
2392
	   addr = (long) bfd_get_32 (abfd, leaf),
2393
	   size = (long) bfd_get_32 (abfd, leaf + 4),
2394
	   (int) bfd_get_32 (abfd, leaf + 8));
2395
 
2396
  /* Check that the reserved entry is 0.  */
2397
  if (bfd_get_32 (abfd, leaf + 12) != 0
2398
      /* And that the data address/size is valid too.  */
2399
      || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2400
    return regions->section_end + 1;
2401
 
2402
  if (regions->resource_start == NULL)
2403
    regions->resource_start = regions->section_start + (addr - rva_bias);
2404
 
2405
  return regions->section_start + (addr - rva_bias) + size;
2406
}
2407
 
2408
#define max(a,b) ((a) > (b) ? (a) : (b))
2409
#define min(a,b) ((a) < (b) ? (a) : (b))
2410
 
2411
static bfd_byte *
2412
rsrc_print_resource_directory (FILE *         file,
2413
			       bfd *          abfd,
2414
			       unsigned int   indent,
2415
			       bfd_byte *     data,
2416
			       rsrc_regions * regions,
2417
			       bfd_vma        rva_bias)
2418
{
2419
  unsigned int num_names, num_ids;
2420
  bfd_byte * highest_data = data;
2421
 
2422
  if (data + 16 >= regions->section_end)
2423
    return regions->section_end + 1;
2424
 
2425
  fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2426
  switch (indent)
2427
    {
2428
    case 0: fprintf (file, "Type"); break;
2429
    case 2: fprintf (file, "Name"); break;
2430
    case 4: fprintf (file, "Language"); break;
2431
    default:
2432
      fprintf (file, _("\n"), indent);
2433
      /* FIXME: For now we end the printing here.  If in the
2434
	 future more directory types are added to the RSRC spec
2435
	 then we will need to change this.  */
2436
      return regions->section_end + 1;
2437
    }
2438
 
2439
  fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2440
	   (int) bfd_get_32 (abfd, data),
2441
	   (long) bfd_get_32 (abfd, data + 4),
2442
	   (int)  bfd_get_16 (abfd, data + 8),
2443
	   (int)  bfd_get_16 (abfd, data + 10),
2444
	   num_names = (int) bfd_get_16 (abfd, data + 12),
2445
	   num_ids =   (int) bfd_get_16 (abfd, data + 14));
2446
  data += 16;
2447
 
2448
  while (num_names --)
2449
    {
2450
      bfd_byte * entry_end;
2451
 
2452
      entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, TRUE,
2453
					       data, regions, rva_bias);
2454
      data += 8;
2455
      highest_data = max (highest_data, entry_end);
2456
      if (entry_end >= regions->section_end)
2457
	return entry_end;
2458
    }
2459
 
2460
  while (num_ids --)
2461
    {
2462
      bfd_byte * entry_end;
2463
 
2464
      entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, FALSE,
2465
					       data, regions, rva_bias);
2466
      data += 8;
2467
      highest_data = max (highest_data, entry_end);
2468
      if (entry_end >= regions->section_end)
2469
	return entry_end;
2470
    }
2471
 
2472
  return max (highest_data, data);
2473
}
2474
 
2475
/* Display the contents of a .rsrc section.  We do not try to
2476
   reproduce the resources, windres does that.  Instead we dump
2477
   the tables in a human readable format.  */
2478
 
2479
static bfd_boolean
2480
rsrc_print_section (bfd * abfd, void * vfile)
2481
{
2482
  bfd_vma rva_bias;
2483
  pe_data_type * pe;
2484
  FILE * file = (FILE *) vfile;
2485
  bfd_size_type datasize;
2486
  asection * section;
2487
  bfd_byte * data;
2488
  rsrc_regions regions;
2489
 
2490
  pe = pe_data (abfd);
2491
  if (pe == NULL)
2492
    return TRUE;
2493
 
2494
  section = bfd_get_section_by_name (abfd, ".rsrc");
2495
  if (section == NULL)
2496
    return TRUE;
2497
  if (!(section->flags & SEC_HAS_CONTENTS))
2498
    return TRUE;
2499
 
2500
  datasize = section->size;
2501
  if (datasize == 0)
2502
    return TRUE;
2503
 
2504
  rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2505
 
2506
  if (! bfd_malloc_and_get_section (abfd, section, & data))
2507
    {
2508
      if (data != NULL)
2509
	free (data);
2510
      return FALSE;
2511
    }
2512
 
2513
  regions.section_start = data;
2514
  regions.section_end = data + datasize;
2515
  regions.strings_start = NULL;
2516
  regions.resource_start = NULL;
2517
 
2518
  fflush (file);
2519
  fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2520
 
2521
  while (data < regions.section_end)
2522
    {
2523
      bfd_byte * p = data;
2524
 
2525
      data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2526
 
2527
      if (data == regions.section_end + 1)
2528
	fprintf (file, _("Corrupt .rsrc section detected!\n"));
2529
      else
2530
	{
2531
	  /* Align data before continuing.  */
2532
	  int align = (1 << section->alignment_power) - 1;
2533
 
2534
	  data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2535
	  rva_bias += data - p;
2536
 
2537
	  /* For reasons that are unclear .rsrc sections are sometimes created
2538
	     aligned to a 1^3 boundary even when their alignment is set at
2539
	     1^2.  Catch that case here before we issue a spurious warning
2540
	     message.  */
2541
	  if (data == (regions.section_end - 4))
2542
	    data = regions.section_end;
2543
	  else if (data < regions.section_end)
2544
	    {
2545
	      /* If the extra data is all zeros then do not complain.
2546
		 This is just padding so that the section meets the
2547
		 page size requirements.  */
2548
	      while (++ data < regions.section_end)
2549
		if (*data != 0)
2550
		  break;
2551
	      if (data < regions.section_end)
2552
		fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2553
	    }
2554
	}
2555
    }
2556
 
2557
  if (regions.strings_start != NULL)
2558
    fprintf (file, " String table starts at offset: %#03x\n",
2559
	     (int) (regions.strings_start - regions.section_start));
2560
  if (regions.resource_start != NULL)
2561
    fprintf (file, " Resources start at offset: %#03x\n",
2562
	     (int) (regions.resource_start - regions.section_start));
2563
 
2564
  free (regions.section_start);
2565
  return TRUE;
2566
}
2567
 
2568
#define IMAGE_NUMBEROF_DEBUG_TYPES 12
2569
 
2570
static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2571
{
2572
  "Unknown",
2573
  "COFF",
2574
  "CodeView",
2575
  "FPO",
2576
  "Misc",
2577
  "Exception",
2578
  "Fixup",
2579
  "OMAP-to-SRC",
2580
  "OMAP-from-SRC",
2581
  "Borland",
2582
  "Reserved",
2583
  "CLSID",
2584
};
2585
 
2586
static bfd_boolean
2587
pe_print_debugdata (bfd * abfd, void * vfile)
2588
{
2589
  FILE *file = (FILE *) vfile;
2590
  pe_data_type *pe = pe_data (abfd);
2591
  struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2592
  asection *section;
2593
  bfd_byte *data = 0;
2594
  bfd_size_type dataoff;
2595
  unsigned int i;
2596
 
2597
  bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2598
  bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2599
 
2600
  if (size == 0)
2601
    return TRUE;
2602
 
2603
  addr += extra->ImageBase;
2604
  for (section = abfd->sections; section != NULL; section = section->next)
2605
    {
2606
      if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2607
        break;
2608
    }
2609
 
2610
  if (section == NULL)
2611
    {
2612
      fprintf (file,
2613
               _("\nThere is a debug directory, but the section containing it could not be found\n"));
2614
      return TRUE;
2615
    }
2616
  else if (!(section->flags & SEC_HAS_CONTENTS))
2617
    {
2618
      fprintf (file,
2619
               _("\nThere is a debug directory in %s, but that section has no contents\n"),
2620
               section->name);
2621
      return TRUE;
2622
    }
2623
  else if (section->size < size)
2624
    {
2625
      fprintf (file,
2626
               _("\nError: section %s contains the debug data starting address but it is too small\n"),
2627
               section->name);
2628
      return FALSE;
2629
    }
2630
 
2631
  fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2632
	   section->name, (unsigned long) addr);
2633
 
2634
  dataoff = addr - section->vma;
2635
 
2636
  if (size > (section->size - dataoff))
2637
    {
2638
      fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2639
      return FALSE;
2640
    }
2641
 
2642
  fprintf (file,
2643
	   _("Type                Size     Rva      Offset\n"));
2644
 
2645
  /* Read the whole section.  */
2646
  if (!bfd_malloc_and_get_section (abfd, section, &data))
2647
    {
2648
      if (data != NULL)
5197 serge 2649
  free (data);
6324 serge 2650
      return FALSE;
2651
    }
5197 serge 2652
 
6324 serge 2653
  for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2654
    {
2655
      const char *type_name;
2656
      struct external_IMAGE_DEBUG_DIRECTORY *ext
2657
	= &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2658
      struct internal_IMAGE_DEBUG_DIRECTORY idd;
2659
 
2660
      _bfd_pei_swap_debugdir_in (abfd, ext, &idd);
2661
 
2662
      if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2663
        type_name = debug_type_names[0];
2664
      else
2665
        type_name = debug_type_names[idd.Type];
2666
 
2667
      fprintf (file, " %2ld  %14s %08lx %08lx %08lx\n",
2668
	       idd.Type, type_name, idd.SizeOfData,
2669
	       idd.AddressOfRawData, idd.PointerToRawData);
2670
 
2671
      if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2672
        {
2673
          char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2674
	  /* PR 17512: file: 065-29434-0.001:0.1
2675
	     We need to use a 32-bit aligned buffer
2676
	     to safely read in a codeview record.  */
2677
          char buffer[256 + 1] ATTRIBUTE_ALIGNED_ALIGNOF (CODEVIEW_INFO);
2678
 
2679
          CODEVIEW_INFO *cvinfo = (CODEVIEW_INFO *) buffer;
2680
 
2681
          /* The debug entry doesn't have to have to be in a section,
2682
	     in which case AddressOfRawData is 0, so always use PointerToRawData.  */
2683
          if (!_bfd_pei_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2684
					       idd.SizeOfData, cvinfo))
2685
            continue;
2686
 
2687
          for (i = 0; i < cvinfo->SignatureLength; i++)
2688
            sprintf (&signature[i*2], "%02x", cvinfo->Signature[i] & 0xff);
2689
 
2690
          fprintf (file, "(format %c%c%c%c signature %s age %ld)\n",
2691
		   buffer[0], buffer[1], buffer[2], buffer[3],
2692
		   signature, cvinfo->Age);
2693
        }
2694
    }
2695
 
2696
  if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2697
    fprintf (file,
2698
            _("The debug directory size is not a multiple of the debug directory entry size\n"));
2699
 
5197 serge 2700
  return TRUE;
2701
}
2702
 
2703
/* Print out the program headers.  */
2704
 
2705
bfd_boolean
2706
_bfd_pe_print_private_bfd_data_common (bfd * abfd, void * vfile)
2707
{
2708
  FILE *file = (FILE *) vfile;
2709
  int j;
2710
  pe_data_type *pe = pe_data (abfd);
2711
  struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2712
  const char *subsystem_name = NULL;
2713
  const char *name;
2714
 
2715
  /* The MS dumpbin program reportedly ands with 0xff0f before
2716
     printing the characteristics field.  Not sure why.  No reason to
2717
     emulate it here.  */
2718
  fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2719
#undef PF
2720
#define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2721
  PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2722
  PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2723
  PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2724
  PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2725
  PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2726
  PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2727
  PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2728
  PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2729
  PF (IMAGE_FILE_SYSTEM, "system file");
2730
  PF (IMAGE_FILE_DLL, "DLL");
2731
  PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2732
#undef PF
2733
 
2734
  /* ctime implies '\n'.  */
2735
  {
2736
    time_t t = pe->coff.timestamp;
2737
    fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2738
  }
2739
 
2740
#ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2741
# define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2742
#endif
2743
#ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2744
# define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2745
#endif
2746
#ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2747
# define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2748
#endif
2749
 
2750
  switch (i->Magic)
2751
    {
2752
    case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2753
      name = "PE32";
2754
      break;
2755
    case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2756
      name = "PE32+";
2757
      break;
2758
    case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2759
      name = "ROM";
2760
      break;
2761
    default:
2762
      name = NULL;
2763
      break;
2764
    }
2765
  fprintf (file, "Magic\t\t\t%04x", i->Magic);
2766
  if (name)
2767
    fprintf (file, "\t(%s)",name);
2768
  fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2769
  fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2770
  fprintf (file, "SizeOfCode\t\t%08lx\n", (unsigned long) i->SizeOfCode);
2771
  fprintf (file, "SizeOfInitializedData\t%08lx\n",
2772
	   (unsigned long) i->SizeOfInitializedData);
2773
  fprintf (file, "SizeOfUninitializedData\t%08lx\n",
2774
	   (unsigned long) i->SizeOfUninitializedData);
2775
  fprintf (file, "AddressOfEntryPoint\t");
2776
  bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2777
  fprintf (file, "\nBaseOfCode\t\t");
2778
  bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2779
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
2780
  /* PE32+ does not have BaseOfData member!  */
2781
  fprintf (file, "\nBaseOfData\t\t");
2782
  bfd_fprintf_vma (abfd, file, i->BaseOfData);
2783
#endif
2784
 
2785
  fprintf (file, "\nImageBase\t\t");
2786
  bfd_fprintf_vma (abfd, file, i->ImageBase);
2787
  fprintf (file, "\nSectionAlignment\t");
2788
  bfd_fprintf_vma (abfd, file, i->SectionAlignment);
2789
  fprintf (file, "\nFileAlignment\t\t");
2790
  bfd_fprintf_vma (abfd, file, i->FileAlignment);
2791
  fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2792
  fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2793
  fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2794
  fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2795
  fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2796
  fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2797
  fprintf (file, "Win32Version\t\t%08lx\n", (unsigned long) i->Reserved1);
2798
  fprintf (file, "SizeOfImage\t\t%08lx\n", (unsigned long) i->SizeOfImage);
2799
  fprintf (file, "SizeOfHeaders\t\t%08lx\n", (unsigned long) i->SizeOfHeaders);
2800
  fprintf (file, "CheckSum\t\t%08lx\n", (unsigned long) i->CheckSum);
2801
 
2802
  switch (i->Subsystem)
2803
    {
2804
    case IMAGE_SUBSYSTEM_UNKNOWN:
2805
      subsystem_name = "unspecified";
2806
      break;
2807
    case IMAGE_SUBSYSTEM_NATIVE:
2808
      subsystem_name = "NT native";
2809
      break;
2810
    case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2811
      subsystem_name = "Windows GUI";
2812
      break;
2813
    case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2814
      subsystem_name = "Windows CUI";
2815
      break;
2816
    case IMAGE_SUBSYSTEM_POSIX_CUI:
2817
      subsystem_name = "POSIX CUI";
2818
      break;
2819
    case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2820
      subsystem_name = "Wince CUI";
2821
      break;
2822
    // These are from UEFI Platform Initialization Specification 1.1.
2823
    case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2824
      subsystem_name = "EFI application";
2825
      break;
2826
    case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2827
      subsystem_name = "EFI boot service driver";
2828
      break;
2829
    case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2830
      subsystem_name = "EFI runtime driver";
2831
      break;
2832
    case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2833
      subsystem_name = "SAL runtime driver";
2834
      break;
2835
    // This is from revision 8.0 of the MS PE/COFF spec
2836
    case IMAGE_SUBSYSTEM_XBOX:
2837
      subsystem_name = "XBOX";
2838
      break;
2839
    // Added default case for clarity - subsystem_name is NULL anyway.
2840
    default:
2841
      subsystem_name = NULL;
2842
    }
2843
 
2844
  fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2845
  if (subsystem_name)
2846
    fprintf (file, "\t(%s)", subsystem_name);
2847
  fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2848
  fprintf (file, "SizeOfStackReserve\t");
2849
  bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2850
  fprintf (file, "\nSizeOfStackCommit\t");
2851
  bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2852
  fprintf (file, "\nSizeOfHeapReserve\t");
2853
  bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2854
  fprintf (file, "\nSizeOfHeapCommit\t");
2855
  bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2856
  fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2857
  fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2858
	   (unsigned long) i->NumberOfRvaAndSizes);
2859
 
2860
  fprintf (file, "\nThe Data Directory\n");
2861
  for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2862
    {
2863
      fprintf (file, "Entry %1x ", j);
2864
      bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2865
      fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2866
      fprintf (file, "%s\n", dir_names[j]);
2867
    }
2868
 
2869
  pe_print_idata (abfd, vfile);
2870
  pe_print_edata (abfd, vfile);
2871
  if (bfd_coff_have_print_pdata (abfd))
2872
    bfd_coff_print_pdata (abfd, vfile);
2873
  else
2874
    pe_print_pdata (abfd, vfile);
2875
  pe_print_reloc (abfd, vfile);
6324 serge 2876
  pe_print_debugdata (abfd, file);
5197 serge 2877
 
6324 serge 2878
  rsrc_print_section (abfd, vfile);
2879
 
5197 serge 2880
  return TRUE;
2881
}
2882
 
6324 serge 2883
static bfd_boolean
2884
is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2885
{
2886
  bfd_vma addr = * (bfd_vma *) obj;
2887
  return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2888
}
2889
 
2890
static asection *
2891
find_section_by_vma (bfd *abfd, bfd_vma addr)
2892
{
2893
  return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2894
}
2895
 
5197 serge 2896
/* Copy any private info we understand from the input bfd
2897
   to the output bfd.  */
2898
 
2899
bfd_boolean
2900
_bfd_pe_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2901
{
2902
  pe_data_type *ipe, *ope;
2903
 
2904
  /* One day we may try to grok other private data.  */
2905
  if (ibfd->xvec->flavour != bfd_target_coff_flavour
2906
      || obfd->xvec->flavour != bfd_target_coff_flavour)
2907
    return TRUE;
2908
 
2909
  ipe = pe_data (ibfd);
2910
  ope = pe_data (obfd);
2911
 
2912
  /* pe_opthdr is copied in copy_object.  */
2913
  ope->dll = ipe->dll;
2914
 
2915
  /* Don't copy input subsystem if output is different from input.  */
2916
  if (obfd->xvec != ibfd->xvec)
2917
    ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
2918
 
2919
  /* For strip: if we removed .reloc, we'll make a real mess of things
2920
     if we don't remove this entry as well.  */
2921
  if (! pe_data (obfd)->has_reloc_section)
2922
    {
2923
      pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
2924
      pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
2925
    }
2926
 
2927
  /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
2928
     But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
2929
     won't be added.  */
2930
  if (! pe_data (ibfd)->has_reloc_section
2931
      && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
2932
    pe_data (obfd)->dont_strip_reloc = 1;
2933
 
6324 serge 2934
  /* The file offsets contained in the debug directory need rewriting.  */
2935
  if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0)
2936
    {
2937
      bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
2938
	+ ope->pe_opthdr.ImageBase;
2939
      asection *section = find_section_by_vma (obfd, addr);
2940
      bfd_byte *data;
2941
 
2942
      if (section && bfd_malloc_and_get_section (obfd, section, &data))
2943
        {
2944
          unsigned int i;
2945
          struct external_IMAGE_DEBUG_DIRECTORY *dd =
2946
	    (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma));
2947
 
2948
	  /* PR 17512: file: 0f15796a.  */
2949
	  if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size + (addr - section->vma)
2950
	      > bfd_get_section_size (section))
2951
	    {
2952
	      _bfd_error_handler (_("%B: Data Directory size (%lx) exceeds space left in section (%lx)"),
2953
				  obfd, ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size,
2954
				  bfd_get_section_size (section) - (addr - section->vma));
2955
	      return FALSE;
2956
	    }
2957
 
2958
          for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
2959
		 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2960
            {
2961
              asection *ddsection;
2962
              struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
2963
              struct internal_IMAGE_DEBUG_DIRECTORY idd;
2964
 
2965
              _bfd_pei_swap_debugdir_in (obfd, edd, &idd);
2966
 
2967
              if (idd.AddressOfRawData == 0)
2968
                continue; /* RVA 0 means only offset is valid, not handled yet.  */
2969
 
2970
              ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase);
2971
              if (!ddsection)
2972
                continue; /* Not in a section! */
2973
 
2974
              idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData
2975
							   + ope->pe_opthdr.ImageBase) - ddsection->vma;
2976
 
2977
              _bfd_pei_swap_debugdir_out (obfd, &idd, edd);
2978
            }
2979
 
2980
          if (!bfd_set_section_contents (obfd, section, data, 0, section->size))
2981
	    {
2982
	      _bfd_error_handler (_("Failed to update file offsets in debug directory"));
2983
	      return FALSE;
2984
	    }
2985
        }
2986
      else if (section)
2987
	{
2988
	  _bfd_error_handler (_("%B: Failed to read debug data section"), obfd);
2989
	  return FALSE;
2990
	}
2991
    }
2992
 
5197 serge 2993
  return TRUE;
2994
}
2995
 
2996
/* Copy private section data.  */
2997
 
2998
bfd_boolean
2999
_bfd_pe_bfd_copy_private_section_data (bfd *ibfd,
3000
				       asection *isec,
3001
				       bfd *obfd,
3002
				       asection *osec)
3003
{
3004
  if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
3005
      || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
3006
    return TRUE;
3007
 
3008
  if (coff_section_data (ibfd, isec) != NULL
3009
      && pei_section_data (ibfd, isec) != NULL)
3010
    {
3011
      if (coff_section_data (obfd, osec) == NULL)
3012
	{
3013
	  bfd_size_type amt = sizeof (struct coff_section_tdata);
3014
	  osec->used_by_bfd = bfd_zalloc (obfd, amt);
3015
	  if (osec->used_by_bfd == NULL)
3016
	    return FALSE;
3017
	}
3018
 
3019
      if (pei_section_data (obfd, osec) == NULL)
3020
	{
3021
	  bfd_size_type amt = sizeof (struct pei_section_tdata);
3022
	  coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
3023
	  if (coff_section_data (obfd, osec)->tdata == NULL)
3024
	    return FALSE;
3025
	}
3026
 
3027
      pei_section_data (obfd, osec)->virt_size =
3028
	pei_section_data (ibfd, isec)->virt_size;
3029
      pei_section_data (obfd, osec)->pe_flags =
3030
	pei_section_data (ibfd, isec)->pe_flags;
3031
    }
3032
 
3033
  return TRUE;
3034
}
3035
 
3036
void
3037
_bfd_pe_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3038
{
3039
  coff_get_symbol_info (abfd, symbol, ret);
3040
}
3041
 
3042
#if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
3043
static int
3044
sort_x64_pdata (const void *l, const void *r)
3045
{
3046
  const char *lp = (const char *) l;
3047
  const char *rp = (const char *) r;
3048
  bfd_vma vl, vr;
3049
  vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3050
  if (vl != vr)
3051
    return (vl < vr ? -1 : 1);
3052
  /* We compare just begin address.  */
3053
  return 0;
3054
}
3055
#endif
6324 serge 3056
 
3057
/* Functions to process a .rsrc section.  */
5197 serge 3058
 
6324 serge 3059
static unsigned int sizeof_leaves;
3060
static unsigned int sizeof_strings;
3061
static unsigned int sizeof_tables_and_entries;
3062
 
3063
static bfd_byte *
3064
rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3065
 
3066
static bfd_byte *
3067
rsrc_count_entries (bfd *          abfd,
3068
		    bfd_boolean    is_name,
3069
		    bfd_byte *     datastart,
3070
		    bfd_byte *     data,
3071
		    bfd_byte *     dataend,
3072
		    bfd_vma        rva_bias)
3073
{
3074
  unsigned long entry, addr, size;
3075
 
3076
  if (data + 8 >= dataend)
3077
    return dataend + 1;
3078
 
3079
  if (is_name)
3080
    {
3081
      bfd_byte * name;
3082
 
3083
      entry = (long) bfd_get_32 (abfd, data);
3084
 
3085
      if (HighBitSet (entry))
3086
	name = datastart + WithoutHighBit (entry);
3087
      else
3088
	name = datastart + entry - rva_bias;
3089
 
3090
      if (name + 2 >= dataend || name < datastart)
3091
	return dataend + 1;
3092
 
3093
      unsigned int len = bfd_get_16 (abfd, name);
3094
      if (len == 0 || len > 256)
3095
	return dataend + 1;
3096
    }
3097
 
3098
  entry = (long) bfd_get_32 (abfd, data + 4);
3099
 
3100
  if (HighBitSet (entry))
3101
    {
3102
      data = datastart + WithoutHighBit (entry);
3103
 
3104
      if (data <= datastart || data >= dataend)
3105
	return dataend + 1;
3106
 
3107
      return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3108
    }
3109
 
3110
  if (datastart + entry + 16 >= dataend)
3111
    return dataend + 1;
3112
 
3113
  addr = (long) bfd_get_32 (abfd, datastart + entry);
3114
  size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3115
 
3116
  return datastart + addr - rva_bias + size;
3117
}
3118
 
3119
static bfd_byte *
3120
rsrc_count_directory (bfd *          abfd,
3121
		      bfd_byte *     datastart,
3122
		      bfd_byte *     data,
3123
		      bfd_byte *     dataend,
3124
		      bfd_vma        rva_bias)
3125
{
3126
  unsigned int  num_entries, num_ids;
3127
  bfd_byte *    highest_data = data;
3128
 
3129
  if (data + 16 >= dataend)
3130
    return dataend + 1;
3131
 
3132
  num_entries  = (int) bfd_get_16 (abfd, data + 12);
3133
  num_ids      = (int) bfd_get_16 (abfd, data + 14);
3134
 
3135
  num_entries += num_ids;
3136
 
3137
  data += 16;
3138
 
3139
  while (num_entries --)
3140
    {
3141
      bfd_byte * entry_end;
3142
 
3143
      entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3144
				      datastart, data, dataend, rva_bias);
3145
      data += 8;
3146
      highest_data = max (highest_data, entry_end);
3147
      if (entry_end >= dataend)
3148
	break;
3149
    }
3150
 
3151
  return max (highest_data, data);
3152
}
3153
 
3154
typedef struct rsrc_dir_chain
3155
{
3156
  unsigned int         num_entries;
3157
  struct rsrc_entry *  first_entry;
3158
  struct rsrc_entry *  last_entry;
3159
} rsrc_dir_chain;
3160
 
3161
typedef struct rsrc_directory
3162
{
3163
  unsigned int characteristics;
3164
  unsigned int time;
3165
  unsigned int major;
3166
  unsigned int minor;
3167
 
3168
  rsrc_dir_chain names;
3169
  rsrc_dir_chain ids;
3170
 
3171
  struct rsrc_entry * entry;
3172
} rsrc_directory;
3173
 
3174
typedef struct rsrc_string
3175
{
3176
  unsigned int  len;
3177
  bfd_byte *    string;
3178
} rsrc_string;
3179
 
3180
typedef struct rsrc_leaf
3181
{
3182
  unsigned int  size;
3183
  unsigned int  codepage;
3184
  bfd_byte *    data;
3185
} rsrc_leaf;
3186
 
3187
typedef struct rsrc_entry
3188
{
3189
  bfd_boolean is_name;
3190
  union
3191
  {
3192
    unsigned int          id;
3193
    struct rsrc_string    name;
3194
  } name_id;
3195
 
3196
  bfd_boolean is_dir;
3197
  union
3198
  {
3199
    struct rsrc_directory * directory;
3200
    struct rsrc_leaf *      leaf;
3201
  } value;
3202
 
3203
  struct rsrc_entry *     next_entry;
3204
  struct rsrc_directory * parent;
3205
} rsrc_entry;
3206
 
3207
static bfd_byte *
3208
rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3209
		      bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3210
 
3211
static bfd_byte *
3212
rsrc_parse_entry (bfd *            abfd,
3213
		  bfd_boolean      is_name,
3214
		  rsrc_entry *     entry,
3215
		  bfd_byte *       datastart,
3216
		  bfd_byte *       data,
3217
		  bfd_byte *       dataend,
3218
		  bfd_vma          rva_bias,
3219
		  rsrc_directory * parent)
3220
{
3221
  unsigned long val, addr, size;
3222
 
3223
  val = bfd_get_32 (abfd, data);
3224
 
3225
  entry->parent = parent;
3226
  entry->is_name = is_name;
3227
 
3228
  if (is_name)
3229
    {
3230
      bfd_byte * address;
3231
 
3232
      if (HighBitSet (val))
3233
	{
3234
	  val = WithoutHighBit (val);
3235
 
3236
	  address = datastart + val;
3237
	}
3238
      else
3239
	{
3240
	  address = datastart + val - rva_bias;
3241
	}
3242
 
3243
      if (address + 3 > dataend)
3244
	return dataend;
3245
 
3246
      entry->name_id.name.len    = bfd_get_16 (abfd, address);
3247
      entry->name_id.name.string = address + 2;
3248
    }
3249
  else
3250
    entry->name_id.id = val;
3251
 
3252
  val = bfd_get_32 (abfd, data + 4);
3253
 
3254
  if (HighBitSet (val))
3255
    {
3256
      entry->is_dir = TRUE;
3257
      entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
3258
      if (entry->value.directory == NULL)
3259
	return dataend;
3260
 
3261
      return rsrc_parse_directory (abfd, entry->value.directory,
3262
				   datastart,
3263
				   datastart + WithoutHighBit (val),
3264
				   dataend, rva_bias, entry);
3265
    }
3266
 
3267
  entry->is_dir = FALSE;
3268
  entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
3269
  if (entry->value.leaf == NULL)
3270
    return dataend;
3271
 
3272
  data = datastart + val;
3273
  if (data < datastart || data >= dataend)
3274
    return dataend;
3275
 
3276
  addr = bfd_get_32 (abfd, data);
3277
  size = entry->value.leaf->size = bfd_get_32 (abfd, data + 4);
3278
  entry->value.leaf->codepage = bfd_get_32 (abfd, data + 8);
3279
  /* FIXME: We assume that the reserved field (data + 12) is OK.  */
3280
 
3281
  entry->value.leaf->data = bfd_malloc (size);
3282
  if (entry->value.leaf->data == NULL)
3283
    return dataend;
3284
 
3285
  memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3286
  return datastart + (addr - rva_bias) + size;
3287
}
3288
 
3289
static bfd_byte *
3290
rsrc_parse_entries (bfd *            abfd,
3291
		    rsrc_dir_chain * chain,
3292
		    bfd_boolean      is_name,
3293
		    bfd_byte *       highest_data,
3294
		    bfd_byte *       datastart,
3295
		    bfd_byte *       data,
3296
		    bfd_byte *       dataend,
3297
		    bfd_vma          rva_bias,
3298
		    rsrc_directory * parent)
3299
{
3300
  unsigned int i;
3301
  rsrc_entry * entry;
3302
 
3303
  if (chain->num_entries == 0)
3304
    {
3305
      chain->first_entry = chain->last_entry = NULL;
3306
      return highest_data;
3307
    }
3308
 
3309
  entry = bfd_malloc (sizeof * entry);
3310
  if (entry == NULL)
3311
    return dataend;
3312
 
3313
  chain->first_entry = entry;
3314
 
3315
  for (i = chain->num_entries; i--;)
3316
    {
3317
      bfd_byte * entry_end;
3318
 
3319
      entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3320
				    data, dataend, rva_bias, parent);
3321
      data += 8;
3322
      highest_data = max (entry_end, highest_data);
3323
      if (entry_end > dataend)
3324
	return dataend;
3325
 
3326
      if (i)
3327
	{
3328
	  entry->next_entry = bfd_malloc (sizeof * entry);
3329
	  entry = entry->next_entry;
3330
	  if (entry == NULL)
3331
	    return dataend;
3332
	}
3333
      else
3334
	entry->next_entry = NULL;
3335
    }
3336
 
3337
  chain->last_entry = entry;
3338
 
3339
  return highest_data;
3340
}
3341
 
3342
static bfd_byte *
3343
rsrc_parse_directory (bfd *            abfd,
3344
		      rsrc_directory * table,
3345
		      bfd_byte *       datastart,
3346
		      bfd_byte *       data,
3347
		      bfd_byte *       dataend,
3348
		      bfd_vma          rva_bias,
3349
		      rsrc_entry *     entry)
3350
{
3351
  bfd_byte * highest_data = data;
3352
 
3353
  if (table == NULL)
3354
    return dataend;
3355
 
3356
  table->characteristics = bfd_get_32 (abfd, data);
3357
  table->time = bfd_get_32 (abfd, data + 4);
3358
  table->major = bfd_get_16 (abfd, data + 8);
3359
  table->minor = bfd_get_16 (abfd, data + 10);
3360
  table->names.num_entries = bfd_get_16 (abfd, data + 12);
3361
  table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3362
  table->entry = entry;
3363
 
3364
  data += 16;
3365
 
3366
  highest_data = rsrc_parse_entries (abfd, & table->names, TRUE, data,
3367
				     datastart, data, dataend, rva_bias, table);
3368
  data += table->names.num_entries * 8;
3369
 
3370
  highest_data = rsrc_parse_entries (abfd, & table->ids, FALSE, highest_data,
3371
				     datastart, data, dataend, rva_bias, table);
3372
  data += table->ids.num_entries * 8;
3373
 
3374
  return max (highest_data, data);
3375
}
3376
 
3377
typedef struct rsrc_write_data
3378
{
3379
  bfd *      abfd;
3380
  bfd_byte * datastart;
3381
  bfd_byte * next_table;
3382
  bfd_byte * next_leaf;
3383
  bfd_byte * next_string;
3384
  bfd_byte * next_data;
3385
  bfd_vma    rva_bias;
3386
} rsrc_write_data;
3387
 
3388
static void
3389
rsrc_write_string (rsrc_write_data * data,
3390
		   rsrc_string *     string)
3391
{
3392
  bfd_put_16 (data->abfd, string->len, data->next_string);
3393
  memcpy (data->next_string + 2, string->string, string->len * 2);
3394
  data->next_string += (string->len + 1) * 2;
3395
}
3396
 
3397
static inline unsigned int
3398
rsrc_compute_rva (rsrc_write_data * data,
3399
		  bfd_byte *        addr)
3400
{
3401
  return (addr - data->datastart) + data->rva_bias;
3402
}
3403
 
3404
static void
3405
rsrc_write_leaf (rsrc_write_data * data,
3406
		 rsrc_leaf *       leaf)
3407
{
3408
  bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3409
	      data->next_leaf);
3410
  bfd_put_32 (data->abfd, leaf->size,     data->next_leaf + 4);
3411
  bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3412
  bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3413
  data->next_leaf += 16;
3414
 
3415
  memcpy (data->next_data, leaf->data, leaf->size);
3416
  /* An undocumented feature of Windows resources is that each unit
3417
     of raw data is 8-byte aligned...  */
3418
  data->next_data += ((leaf->size + 7) & ~7);
3419
}
3420
 
3421
static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3422
 
3423
static void
3424
rsrc_write_entry (rsrc_write_data *  data,
3425
		  bfd_byte *         where,
3426
		  rsrc_entry *       entry)
3427
{
3428
  if (entry->is_name)
3429
    {
3430
      bfd_put_32 (data->abfd,
3431
		  SetHighBit (data->next_string - data->datastart),
3432
		  where);
3433
      rsrc_write_string (data, & entry->name_id.name);
3434
    }
3435
  else
3436
    bfd_put_32 (data->abfd, entry->name_id.id, where);
3437
 
3438
  if (entry->is_dir)
3439
    {
3440
      bfd_put_32 (data->abfd,
3441
		  SetHighBit (data->next_table - data->datastart),
3442
		  where + 4);
3443
      rsrc_write_directory (data, entry->value.directory);
3444
    }
3445
  else
3446
    {
3447
      bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3448
      rsrc_write_leaf (data, entry->value.leaf);
3449
    }
3450
}
3451
 
3452
static void
3453
rsrc_compute_region_sizes (rsrc_directory * dir)
3454
{
3455
  struct rsrc_entry * entry;
3456
 
3457
  if (dir == NULL)
3458
    return;
3459
 
3460
  sizeof_tables_and_entries += 16;
3461
 
3462
  for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3463
    {
3464
      sizeof_tables_and_entries += 8;
3465
 
3466
      sizeof_strings += (entry->name_id.name.len + 1) * 2;
3467
 
3468
      if (entry->is_dir)
3469
	rsrc_compute_region_sizes (entry->value.directory);
3470
      else
3471
	sizeof_leaves += 16;
3472
    }
3473
 
3474
  for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3475
    {
3476
      sizeof_tables_and_entries += 8;
3477
 
3478
      if (entry->is_dir)
3479
	rsrc_compute_region_sizes (entry->value.directory);
3480
      else
3481
	sizeof_leaves += 16;
3482
    }
3483
}
3484
 
3485
static void
3486
rsrc_write_directory (rsrc_write_data * data,
3487
		      rsrc_directory *  dir)
3488
{
3489
  rsrc_entry * entry;
3490
  unsigned int i;
3491
  bfd_byte * next_entry;
3492
  bfd_byte * nt;
3493
 
3494
  bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3495
  bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3496
  bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3497
  bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3498
  bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3499
  bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3500
 
3501
  /* Compute where the entries and the next table will be placed.  */
3502
  next_entry = data->next_table + 16;
3503
  data->next_table = next_entry + (dir->names.num_entries * 8)
3504
    + (dir->ids.num_entries * 8);
3505
  nt = data->next_table;
3506
 
3507
  /* Write the entries.  */
3508
  for (i = dir->names.num_entries, entry = dir->names.first_entry;
3509
       i > 0 && entry != NULL;
3510
       i--, entry = entry->next_entry)
3511
    {
3512
      BFD_ASSERT (entry->is_name);
3513
      rsrc_write_entry (data, next_entry, entry);
3514
      next_entry += 8;
3515
    }
3516
  BFD_ASSERT (i == 0);
3517
  BFD_ASSERT (entry == NULL);
3518
 
3519
  for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3520
       i > 0 && entry != NULL;
3521
       i--, entry = entry->next_entry)
3522
    {
3523
      BFD_ASSERT (! entry->is_name);
3524
      rsrc_write_entry (data, next_entry, entry);
3525
      next_entry += 8;
3526
    }
3527
  BFD_ASSERT (i == 0);
3528
  BFD_ASSERT (entry == NULL);
3529
  BFD_ASSERT (nt == next_entry);
3530
}
3531
 
3532
#if defined HAVE_WCHAR_H && ! defined __CYGWIN__ && ! defined __MINGW32__
3533
/* Return the length (number of units) of the first character in S,
3534
   putting its 'ucs4_t' representation in *PUC.  */
3535
 
3536
static unsigned int
3537
#if defined HAVE_WCTYPE_H
3538
u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3539
#else
3540
u16_mbtouc (wchar_t * puc, const unsigned short * s, unsigned int n)
3541
#endif
3542
{
3543
  unsigned short c = * s;
3544
 
3545
  if (c < 0xd800 || c >= 0xe000)
3546
    {
3547
      *puc = c;
3548
      return 1;
3549
    }
3550
 
3551
  if (c < 0xdc00)
3552
    {
3553
      if (n >= 2)
3554
        {
3555
          if (s[1] >= 0xdc00 && s[1] < 0xe000)
3556
            {
3557
              *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3558
              return 2;
3559
            }
3560
        }
3561
      else
3562
        {
3563
          /* Incomplete multibyte character.  */
3564
          *puc = 0xfffd;
3565
          return n;
3566
        }
3567
    }
3568
 
3569
  /* Invalid multibyte character.  */
3570
  *puc = 0xfffd;
3571
  return 1;
3572
}
3573
#endif /* HAVE_WCHAR_H and not Cygwin/Mingw */
3574
 
3575
/* Perform a comparison of two entries.  */
3576
static signed int
3577
rsrc_cmp (bfd_boolean is_name, rsrc_entry * a, rsrc_entry * b)
3578
{
3579
  signed int    res;
3580
  bfd_byte *    astring;
3581
  unsigned int  alen;
3582
  bfd_byte *    bstring;
3583
  unsigned int  blen;
3584
 
3585
  if (! is_name)
3586
    return a->name_id.id - b->name_id.id;
3587
 
3588
  /* We have to perform a case insenstive, unicode string comparison...  */
3589
  astring = a->name_id.name.string;
3590
  alen    = a->name_id.name.len;
3591
  bstring = b->name_id.name.string;
3592
  blen    = b->name_id.name.len;
3593
 
3594
#if defined  __CYGWIN__ || defined __MINGW32__
3595
  /* Under Windows hosts (both Cygwin and Mingw types),
3596
     unicode == UTF-16 == wchar_t.  The case insensitive string comparison
3597
     function however goes by different names in the two environments...  */
3598
 
3599
#undef rscpcmp
3600
#ifdef __CYGWIN__
3601
#define rscpcmp wcsncasecmp
3602
#endif
3603
#ifdef __MINGW32__
3604
#define rscpcmp wcsnicmp
3605
#endif
3606
 
3607
  res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3608
		 min (alen, blen));
3609
 
3610
#elif defined HAVE_WCHAR_H
3611
  {
3612
    unsigned int  i;
3613
 
3614
    res = 0;
3615
    for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3616
      {
3617
#if defined HAVE_WCTYPE_H
3618
	wint_t awc;
3619
	wint_t bwc;
3620
#else
3621
	wchar_t awc;
3622
	wchar_t bwc;
3623
#endif
3624
 
3625
	/* Convert UTF-16 unicode characters into wchar_t characters
3626
	   so that we can then perform a case insensitive comparison.  */
3627
	unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3628
	unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3629
 
3630
	if (Alen != Blen)
3631
	  return Alen - Blen;
3632
 
3633
#ifdef HAVE_WCTYPE_H
3634
	awc = towlower (awc);
3635
	bwc = towlower (bwc);
3636
 
3637
	res = awc - bwc;
3638
#else
3639
	res = wcsncasecmp (& awc, & bwc, 1);
3640
#endif
3641
	if (res)
3642
	  break;
3643
      }
3644
  }
3645
#else
3646
  /* Do the best we can - a case sensitive, untranslated comparison.  */
3647
  res = memcmp (astring, bstring, min (alen, blen) * 2);
3648
#endif
3649
 
3650
  if (res == 0)
3651
    res = alen - blen;
3652
 
3653
  return res;
3654
}
3655
 
3656
static void
3657
rsrc_print_name (char * buffer, rsrc_string string)
3658
{
3659
  unsigned int  i;
3660
  bfd_byte *    name = string.string;
3661
 
3662
  for (i = string.len; i--; name += 2)
3663
    sprintf (buffer + strlen (buffer), "%.1s", name);
3664
}
3665
 
3666
static const char *
3667
rsrc_resource_name (rsrc_entry * entry, rsrc_directory * dir)
3668
{
3669
  static char buffer [256];
3670
  bfd_boolean is_string = FALSE;
3671
 
3672
  buffer[0] = 0;
3673
 
3674
  if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3675
      && dir->entry->parent->entry != NULL)
3676
    {
3677
      strcpy (buffer, "type: ");
3678
      if (dir->entry->parent->entry->is_name)
3679
	rsrc_print_name (buffer + strlen (buffer),
3680
			 dir->entry->parent->entry->name_id.name);
3681
      else
3682
	{
3683
	  unsigned int id = dir->entry->parent->entry->name_id.id;
3684
 
3685
	  sprintf (buffer + strlen (buffer), "%x", id);
3686
	  switch (id)
3687
	    {
3688
	    case 1: strcat (buffer, " (CURSOR)"); break;
3689
	    case 2: strcat (buffer, " (BITMAP)"); break;
3690
	    case 3: strcat (buffer, " (ICON)"); break;
3691
            case 4: strcat (buffer, " (MENU)"); break;
3692
	    case 5: strcat (buffer, " (DIALOG)"); break;
3693
	    case 6: strcat (buffer, " (STRING)"); is_string = TRUE; break;
3694
	    case 7: strcat (buffer, " (FONTDIR)"); break;
3695
	    case 8: strcat (buffer, " (FONT)"); break;
3696
	    case 9: strcat (buffer, " (ACCELERATOR)"); break;
3697
	    case 10: strcat (buffer, " (RCDATA)"); break;
3698
	    case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3699
	    case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3700
	    case 14: strcat (buffer, " (GROUP_ICON)"); break;
3701
	    case 16: strcat (buffer, " (VERSION)"); break;
3702
	    case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3703
	    case 19: strcat (buffer, " (PLUGPLAY)"); break;
3704
	    case 20: strcat (buffer, " (VXD)"); break;
3705
	    case 21: strcat (buffer, " (ANICURSOR)"); break;
3706
	    case 22: strcat (buffer, " (ANIICON)"); break;
3707
	    case 23: strcat (buffer, " (HTML)"); break;
3708
	    case 24: strcat (buffer, " (MANIFEST)"); break;
3709
	    case 240: strcat (buffer, " (DLGINIT)"); break;
3710
	    case 241: strcat (buffer, " (TOOLBAR)"); break;
3711
	    }
3712
	}
3713
    }
3714
 
3715
  if (dir != NULL && dir->entry != NULL)
3716
    {
3717
      strcat (buffer, " name: ");
3718
      if (dir->entry->is_name)
3719
	rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3720
      else
3721
	{
3722
	  unsigned int id = dir->entry->name_id.id;
3723
 
3724
	  sprintf (buffer + strlen (buffer), "%x", id);
3725
 
3726
	  if (is_string)
3727
	    sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3728
		     (id - 1) << 4, (id << 4) - 1);
3729
	}
3730
    }
3731
 
3732
  if (entry != NULL)
3733
    {
3734
      strcat (buffer, " lang: ");
3735
 
3736
      if (entry->is_name)
3737
	rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3738
      else
3739
	sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3740
    }
3741
 
3742
  return buffer;
3743
}
3744
 
3745
/* *sigh* Windows resource strings are special.  Only the top 28-bits of
3746
   their ID is stored in the NAME entry.  The bottom four bits are used as
3747
   an index into unicode string table that makes up the data of the leaf.
3748
   So identical type-name-lang string resources may not actually be
3749
   identical at all.
3750
 
3751
   This function is called when we have detected two string resources with
3752
   match top-28-bit IDs.  We have to scan the string tables inside the leaves
3753
   and discover if there are any real collisions.  If there are then we report
3754
   them and return FALSE.  Otherwise we copy any strings from B into A and
3755
   then return TRUE.  */
3756
 
3757
static bfd_boolean
3758
rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3759
			   rsrc_entry * b ATTRIBUTE_UNUSED)
3760
{
3761
  unsigned int copy_needed = 0;
3762
  unsigned int i;
3763
  bfd_byte * astring;
3764
  bfd_byte * bstring;
3765
  bfd_byte * new_data;
3766
  bfd_byte * nstring;
3767
 
3768
  /* Step one: Find out what we have to do.  */
3769
  BFD_ASSERT (! a->is_dir);
3770
  astring = a->value.leaf->data;
3771
 
3772
  BFD_ASSERT (! b->is_dir);
3773
  bstring = b->value.leaf->data;
3774
 
3775
  for (i = 0; i < 16; i++)
3776
    {
3777
      unsigned int alen = astring[0] + (astring[1] << 8);
3778
      unsigned int blen = bstring[0] + (bstring[1] << 8);
3779
 
3780
      if (alen == 0)
3781
	{
3782
	  copy_needed += blen * 2;
3783
	}
3784
      else if (blen == 0)
3785
	;
3786
      else if (alen != blen)
3787
	/* FIXME: Should we continue the loop in order to report other duplicates ?  */
3788
	break;
3789
      /* alen == blen != 0.  We might have two identical strings.  If so we
3790
	 can ignore the second one.  There is no need for wchar_t vs UTF-16
3791
	 theatrics here - we are only interested in (case sensitive) equality.  */
3792
      else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3793
	break;
3794
 
3795
      astring += (alen + 1) * 2;
3796
      bstring += (blen + 1) * 2;
3797
    }
3798
 
3799
  if (i != 16)
3800
    {
3801
      if (a->parent != NULL
3802
	  && a->parent->entry != NULL
3803
	  && a->parent->entry->is_name == FALSE)
3804
	_bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3805
			    ((a->parent->entry->name_id.id - 1) << 4) + i);
3806
      return FALSE;
3807
    }
3808
 
3809
  if (copy_needed == 0)
3810
    return TRUE;
3811
 
3812
  /* If we reach here then A and B must both have non-colliding strings.
3813
     (We never get string resources with fully empty string tables).
3814
     We need to allocate an extra COPY_NEEDED bytes in A and then bring
3815
     in B's strings.  */
3816
  new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3817
  if (new_data == NULL)
3818
    return FALSE;
3819
 
3820
  nstring = new_data;
3821
  astring = a->value.leaf->data;
3822
  bstring = b->value.leaf->data;
3823
 
3824
  for (i = 0; i < 16; i++)
3825
    {
3826
      unsigned int alen = astring[0] + (astring[1] << 8);
3827
      unsigned int blen = bstring[0] + (bstring[1] << 8);
3828
 
3829
      if (alen != 0)
3830
	{
3831
	  memcpy (nstring, astring, (alen + 1) * 2);
3832
	  nstring += (alen + 1) * 2;
3833
	}
3834
      else if (blen != 0)
3835
	{
3836
	  memcpy (nstring, bstring, (blen + 1) * 2);
3837
	  nstring += (blen + 1) * 2;
3838
	}
3839
      else
3840
	{
3841
	  * nstring++ = 0;
3842
	  * nstring++ = 0;
3843
	}
3844
 
3845
      astring += (alen + 1) * 2;
3846
      bstring += (blen + 1) * 2;
3847
    }
3848
 
3849
  BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3850
 
3851
  free (a->value.leaf->data);
3852
  a->value.leaf->data = new_data;
3853
  a->value.leaf->size += copy_needed;
3854
 
3855
  return TRUE;
3856
}
3857
 
3858
static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3859
 
3860
/* Sort the entries in given part of the directory.
3861
   We use an old fashioned bubble sort because we are dealing
3862
   with lists and we want to handle matches specially.  */
3863
 
3864
static void
3865
rsrc_sort_entries (rsrc_dir_chain *  chain,
3866
		   bfd_boolean       is_name,
3867
		   rsrc_directory *  dir)
3868
{
3869
  rsrc_entry * entry;
3870
  rsrc_entry * next;
3871
  rsrc_entry ** points_to_entry;
3872
  bfd_boolean swapped;
3873
 
3874
  if (chain->num_entries < 2)
3875
    return;
3876
 
3877
  do
3878
    {
3879
      swapped = FALSE;
3880
      points_to_entry = & chain->first_entry;
3881
      entry = * points_to_entry;
3882
      next  = entry->next_entry;
3883
 
3884
      do
3885
	{
3886
	  signed int cmp = rsrc_cmp (is_name, entry, next);
3887
 
3888
	  if (cmp > 0)
3889
	    {
3890
	      entry->next_entry = next->next_entry;
3891
	      next->next_entry = entry;
3892
	      * points_to_entry = next;
3893
	      points_to_entry = & next->next_entry;
3894
	      next = entry->next_entry;
3895
	      swapped = TRUE;
3896
	    }
3897
	  else if (cmp == 0)
3898
	    {
3899
	      if (entry->is_dir && next->is_dir)
3900
		{
3901
		  /* When we encounter identical directory entries we have to
3902
		     merge them together.  The exception to this rule is for
3903
		     resource manifests - there can only be one of these,
3904
		     even if they differ in language.  Zero-language manifests
3905
		     are assumed to be default manifests (provided by the
3906
		     Cygwin/MinGW build system) and these can be silently dropped,
3907
		     unless that would reduce the number of manifests to zero.
3908
		     There should only ever be one non-zero lang manifest -
3909
		     if there are more it is an error.  A non-zero lang
3910
		     manifest takes precedence over a default manifest.  */
3911
		  if (entry->is_name == FALSE
3912
		      && entry->name_id.id == 1
3913
		      && dir != NULL
3914
		      && dir->entry != NULL
3915
		      && dir->entry->is_name == FALSE
3916
		      && dir->entry->name_id.id == 0x18)
3917
		    {
3918
		      if (next->value.directory->names.num_entries == 0
3919
			  && next->value.directory->ids.num_entries == 1
3920
			  && next->value.directory->ids.first_entry->is_name == FALSE
3921
			  && next->value.directory->ids.first_entry->name_id.id == 0)
3922
			/* Fall through so that NEXT is dropped.  */
3923
			;
3924
		      else if (entry->value.directory->names.num_entries == 0
3925
			       && entry->value.directory->ids.num_entries == 1
3926
			       && entry->value.directory->ids.first_entry->is_name == FALSE
3927
			       && entry->value.directory->ids.first_entry->name_id.id == 0)
3928
			{
3929
			  /* Swap ENTRY and NEXT.  Then fall through so that the old ENTRY is dropped.  */
3930
			  entry->next_entry = next->next_entry;
3931
			  next->next_entry = entry;
3932
			  * points_to_entry = next;
3933
			  points_to_entry = & next->next_entry;
3934
			  next = entry->next_entry;
3935
			  swapped = TRUE;
3936
			}
3937
		      else
3938
			{
3939
			  _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
3940
			  bfd_set_error (bfd_error_file_truncated);
3941
			  return;
3942
			}
3943
 
3944
		      /* Unhook NEXT from the chain.  */
3945
		      /* FIXME: memory loss here.  */
3946
		      entry->next_entry = next->next_entry;
3947
		      chain->num_entries --;
3948
		      if (chain->num_entries < 2)
3949
			return;
3950
		      next = next->next_entry;
3951
		    }
3952
		  else
3953
		    rsrc_merge (entry, next);
3954
		}
3955
	      else if (entry->is_dir != next->is_dir)
3956
		{
3957
		  _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
3958
		  bfd_set_error (bfd_error_file_truncated);
3959
		  return;
3960
		}
3961
	      else
3962
		{
3963
		  /* Otherwise with identical leaves we issue an error
3964
		     message - because there should never be duplicates.
3965
		     The exception is Type 18/Name 1/Lang 0 which is the
3966
		     defaul manifest - this can just be dropped.  */
3967
		  if (entry->is_name == FALSE
3968
		      && entry->name_id.id == 0
3969
		      && dir != NULL
3970
		      && dir->entry != NULL
3971
		      && dir->entry->is_name == FALSE
3972
		      && dir->entry->name_id.id == 1
3973
		      && dir->entry->parent != NULL
3974
		      && dir->entry->parent->entry != NULL
3975
		      && dir->entry->parent->entry->is_name == FALSE
3976
		      && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
3977
		    ;
3978
		  else if (dir != NULL
3979
			   && dir->entry != NULL
3980
			   && dir->entry->parent != NULL
3981
			   && dir->entry->parent->entry != NULL
3982
			   && dir->entry->parent->entry->is_name == FALSE
3983
			   && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
3984
		    {
3985
		      /* Strings need special handling.  */
3986
		      if (! rsrc_merge_string_entries (entry, next))
3987
			{
3988
			  /* _bfd_error_handler should have been called inside merge_strings.  */
3989
			  bfd_set_error (bfd_error_file_truncated);
3990
			  return;
3991
			}
3992
		    }
3993
		  else
3994
		    {
3995
		      if (dir == NULL
3996
			  || dir->entry == NULL
3997
			  || dir->entry->parent == NULL
3998
			  || dir->entry->parent->entry == NULL)
3999
			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
4000
		      else
4001
			_bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
4002
					    rsrc_resource_name (entry, dir));
4003
		      bfd_set_error (bfd_error_file_truncated);
4004
		      return;
4005
		    }
4006
		}
4007
 
4008
	      /* Unhook NEXT from the chain.  */
4009
	      entry->next_entry = next->next_entry;
4010
	      chain->num_entries --;
4011
	      if (chain->num_entries < 2)
4012
		return;
4013
	      next = next->next_entry;
4014
	    }
4015
	  else
4016
	    {
4017
	      points_to_entry = & entry->next_entry;
4018
	      entry = next;
4019
	      next = next->next_entry;
4020
	    }
4021
	}
4022
      while (next);
4023
 
4024
      chain->last_entry = entry;
4025
    }
4026
  while (swapped);
4027
}
4028
 
4029
/* Attach B's chain onto A.  */
4030
static void
4031
rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4032
{
4033
  if (bchain->num_entries == 0)
4034
    return;
4035
 
4036
  achain->num_entries += bchain->num_entries;
4037
 
4038
  if (achain->first_entry == NULL)
4039
    {
4040
      achain->first_entry = bchain->first_entry;
4041
      achain->last_entry  = bchain->last_entry;
4042
    }
4043
  else
4044
    {
4045
      achain->last_entry->next_entry = bchain->first_entry;
4046
      achain->last_entry = bchain->last_entry;
4047
    }
4048
 
4049
  bchain->num_entries = 0;
4050
  bchain->first_entry = bchain->last_entry = NULL;
4051
}
4052
 
4053
static void
4054
rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4055
{
4056
  rsrc_directory * adir;
4057
  rsrc_directory * bdir;
4058
 
4059
  BFD_ASSERT (a->is_dir);
4060
  BFD_ASSERT (b->is_dir);
4061
 
4062
  adir = a->value.directory;
4063
  bdir = b->value.directory;
4064
 
4065
  if (adir->characteristics != bdir->characteristics)
4066
    {
4067
      _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics\n"));
4068
      bfd_set_error (bfd_error_file_truncated);
4069
      return;
4070
    }
4071
 
4072
  if (adir->major != bdir->major || adir->minor != bdir->minor)
4073
    {
4074
      _bfd_error_handler (_(".rsrc merge failure: differing directory versions\n"));
4075
      bfd_set_error (bfd_error_file_truncated);
4076
      return;
4077
    }
4078
 
4079
  /* Attach B's name chain to A.  */
4080
  rsrc_attach_chain (& adir->names, & bdir->names);
4081
 
4082
  /* Attach B's ID chain to A.  */
4083
  rsrc_attach_chain (& adir->ids, & bdir->ids);
4084
 
4085
  /* Now sort A's entries.  */
4086
  rsrc_sort_entries (& adir->names, TRUE, adir);
4087
  rsrc_sort_entries (& adir->ids, FALSE, adir);
4088
}
4089
 
4090
/* Check the .rsrc section.  If it contains multiple concatenated
4091
   resources then we must merge them properly.  Otherwise Windows
4092
   will ignore all but the first set.  */
4093
 
4094
static void
4095
rsrc_process_section (bfd * abfd,
4096
		      struct coff_final_link_info * pfinfo)
4097
{
4098
  rsrc_directory    new_table;
4099
  bfd_size_type     size;
4100
  asection *        sec;
4101
  pe_data_type *    pe;
4102
  bfd_vma           rva_bias;
4103
  bfd_byte *        data;
4104
  bfd_byte *        datastart;
4105
  bfd_byte *        dataend;
4106
  bfd_byte *        new_data;
4107
  unsigned int      num_resource_sets;
4108
  rsrc_directory *  type_tables;
4109
  rsrc_write_data   write_data;
4110
  unsigned int      indx;
4111
  bfd *             input;
4112
  unsigned int      num_input_rsrc = 0;
4113
  unsigned int      max_num_input_rsrc = 4;
4114
  ptrdiff_t *       rsrc_sizes = NULL;
4115
 
4116
  new_table.names.num_entries = 0;
4117
  new_table.ids.num_entries = 0;
4118
 
4119
  sec = bfd_get_section_by_name (abfd, ".rsrc");
4120
  if (sec == NULL || (size = sec->rawsize) == 0)
4121
    return;
4122
 
4123
  pe = pe_data (abfd);
4124
  if (pe == NULL)
4125
    return;
4126
 
4127
  rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4128
 
4129
  data = bfd_malloc (size);
4130
  if (data == NULL)
4131
    return;
4132
 
4133
  datastart = data;
4134
 
4135
  if (! bfd_get_section_contents (abfd, sec, data, 0, size))
4136
    goto end;
4137
 
4138
  /* Step zero: Scan the input bfds looking for .rsrc sections and record
4139
     their lengths.  Note - we rely upon the fact that the linker script
4140
     does *not* sort the input .rsrc sections, so that the order in the
4141
     linkinfo list matches the order in the output .rsrc section.
4142
 
4143
     We need to know the lengths because each input .rsrc section has padding
4144
     at the end of a variable amount.  (It does not appear to be based upon
4145
     the section alignment or the file alignment).  We need to skip any
4146
     padding bytes when parsing the input .rsrc sections.  */
4147
  rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes);
4148
  if (rsrc_sizes == NULL)
4149
    goto end;
4150
 
4151
  for (input = pfinfo->info->input_bfds;
4152
       input != NULL;
4153
       input = input->link.next)
4154
    {
4155
      asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4156
 
4157
      /* PR 18372 - skip discarded .rsrc sections.  */
4158
      if (rsrc_sec != NULL && !discarded_section (rsrc_sec))
4159
	{
4160
	  if (num_input_rsrc == max_num_input_rsrc)
4161
	    {
4162
	      max_num_input_rsrc += 10;
4163
	      rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4164
					* sizeof * rsrc_sizes);
4165
	      if (rsrc_sizes == NULL)
4166
		goto end;
4167
	    }
4168
 
4169
	  BFD_ASSERT (rsrc_sec->size > 0);
4170
	  rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4171
	}
4172
    }
4173
 
4174
  if (num_input_rsrc < 2)
4175
    goto end;
4176
 
4177
  /* Step one: Walk the section, computing the size of the tables,
4178
     leaves and data and decide if we need to do anything.  */
4179
  dataend = data + size;
4180
  num_resource_sets = 0;
4181
 
4182
  while (data < dataend)
4183
    {
4184
      bfd_byte * p = data;
4185
 
4186
      data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4187
 
4188
      if (data > dataend)
4189
	{
4190
	  /* Corrupted .rsrc section - cannot merge.  */
4191
	  _bfd_error_handler (_("%s: .rsrc merge failure: corrupt .rsrc section"),
4192
			      bfd_get_filename (abfd));
4193
	  bfd_set_error (bfd_error_file_truncated);
4194
	  goto end;
4195
	}
4196
 
4197
      if ((data - p) > rsrc_sizes [num_resource_sets])
4198
	{
4199
	  _bfd_error_handler (_("%s: .rsrc merge failure: unexpected .rsrc size"),
4200
			      bfd_get_filename (abfd));
4201
	  bfd_set_error (bfd_error_file_truncated);
4202
	  goto end;
4203
	}
4204
      /* FIXME: Should we add a check for "data - p" being much smaller
4205
	 than rsrc_sizes[num_resource_sets] ?  */
4206
 
4207
      data = p + rsrc_sizes[num_resource_sets];
4208
      rva_bias += data - p;
4209
      ++ num_resource_sets;
4210
    }
4211
  BFD_ASSERT (num_resource_sets == num_input_rsrc);
4212
 
4213
  /* Step two: Walk the data again, building trees of the resources.  */
4214
  data = datastart;
4215
  rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4216
 
4217
  type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
4218
  if (type_tables == NULL)
4219
    goto end;
4220
 
4221
  indx = 0;
4222
  while (data < dataend)
4223
    {
4224
      bfd_byte * p = data;
4225
 
4226
      (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4227
				   dataend, rva_bias, NULL);
4228
      data = p + rsrc_sizes[indx];
4229
      rva_bias += data - p;
4230
      ++ indx;
4231
    }
4232
  BFD_ASSERT (indx == num_resource_sets);
4233
 
4234
  /* Step three: Merge the top level tables (there can be only one).
4235
 
4236
     We must ensure that the merged entries are in ascending order.
4237
 
4238
     We also thread the top level table entries from the old tree onto
4239
     the new table, so that they can be pulled off later.  */
4240
 
4241
  /* FIXME: Should we verify that all type tables are the same ?  */
4242
  new_table.characteristics = type_tables[0].characteristics;
4243
  new_table.time            = type_tables[0].time;
4244
  new_table.major           = type_tables[0].major;
4245
  new_table.minor           = type_tables[0].minor;
4246
 
4247
  /* Chain the NAME entries onto the table.  */
4248
  new_table.names.first_entry = NULL;
4249
  new_table.names.last_entry = NULL;
4250
 
4251
  for (indx = 0; indx < num_resource_sets; indx++)
4252
    rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4253
 
4254
  rsrc_sort_entries (& new_table.names, TRUE, & new_table);
4255
 
4256
  /* Chain the ID entries onto the table.  */
4257
  new_table.ids.first_entry = NULL;
4258
  new_table.ids.last_entry = NULL;
4259
 
4260
  for (indx = 0; indx < num_resource_sets; indx++)
4261
    rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4262
 
4263
  rsrc_sort_entries (& new_table.ids, FALSE, & new_table);
4264
 
4265
  /* Step four: Create new contents for the .rsrc section.  */
4266
  /* Step four point one: Compute the size of each region of the .rsrc section.
4267
     We do this now, rather than earlier, as the merging above may have dropped
4268
     some entries.  */
4269
  sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4270
  rsrc_compute_region_sizes (& new_table);
4271
  /* We increment sizeof_strings to make sure that resource data
4272
     starts on an 8-byte boundary.  FIXME: Is this correct ?  */
4273
  sizeof_strings = (sizeof_strings + 7) & ~ 7;
4274
 
4275
  new_data = bfd_zalloc (abfd, size);
4276
  if (new_data == NULL)
4277
    goto end;
4278
 
4279
  write_data.abfd        = abfd;
4280
  write_data.datastart   = new_data;
4281
  write_data.next_table  = new_data;
4282
  write_data.next_leaf   = new_data + sizeof_tables_and_entries;
4283
  write_data.next_string = write_data.next_leaf + sizeof_leaves;
4284
  write_data.next_data   = write_data.next_string + sizeof_strings;
4285
  write_data.rva_bias    = sec->vma - pe->pe_opthdr.ImageBase;
4286
 
4287
  rsrc_write_directory (& write_data, & new_table);
4288
 
4289
  /* Step five: Replace the old contents with the new.
4290
     We recompute the size as we may have lost entries due to mergeing.  */
4291
  size = ((write_data.next_data - new_data) + 3) & ~ 3;
4292
 
4293
  {
4294
    int page_size;
4295
 
4296
    if (coff_data (abfd)->link_info)
4297
      {
4298
	page_size = pe_data (abfd)->pe_opthdr.FileAlignment;
4299
 
4300
	/* If no file alignment has been set, default to one.
4301
	   This repairs 'ld -r' for arm-wince-pe target.  */
4302
	if (page_size == 0)
4303
	  page_size = 1;
4304
      }
4305
    else
4306
      page_size = PE_DEF_FILE_ALIGNMENT;
4307
    size = (size + page_size - 1) & - page_size;
4308
  }
4309
 
4310
  bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4311
  sec->size = sec->rawsize = size;
4312
 
4313
 end:
4314
  /* Step six: Free all the memory that we have used.  */
4315
  /* FIXME: Free the resource tree, if we have one.  */
4316
  free (datastart);
4317
  free (rsrc_sizes);
4318
}
4319
 
5197 serge 4320
/* Handle the .idata section and other things that need symbol table
4321
   access.  */
4322
 
4323
bfd_boolean
4324
_bfd_pei_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4325
{
4326
  struct coff_link_hash_entry *h1;
4327
  struct bfd_link_info *info = pfinfo->info;
4328
  bfd_boolean result = TRUE;
4329
 
4330
  /* There are a few fields that need to be filled in now while we
4331
     have symbol table access.
4332
 
4333
     The .idata subsections aren't directly available as sections, but
4334
     they are in the symbol table, so get them from there.  */
4335
 
4336
  /* The import directory.  This is the address of .idata$2, with size
4337
     of .idata$2 + .idata$3.  */
4338
  h1 = coff_link_hash_lookup (coff_hash_table (info),
4339
			      ".idata$2", FALSE, FALSE, TRUE);
4340
  if (h1 != NULL)
4341
    {
4342
      /* PR ld/2729: We cannot rely upon all the output sections having been
4343
	 created properly, so check before referencing them.  Issue a warning
4344
	 message for any sections tht could not be found.  */
4345
      if ((h1->root.type == bfd_link_hash_defined
4346
	   || h1->root.type == bfd_link_hash_defweak)
4347
	  && h1->root.u.def.section != NULL
4348
	  && h1->root.u.def.section->output_section != NULL)
4349
	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4350
	  (h1->root.u.def.value
4351
	   + h1->root.u.def.section->output_section->vma
4352
	   + h1->root.u.def.section->output_offset);
4353
      else
4354
	{
4355
	  _bfd_error_handler
4356
	    (_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4357
	     abfd);
4358
	  result = FALSE;
4359
	}
4360
 
4361
      h1 = coff_link_hash_lookup (coff_hash_table (info),
4362
				  ".idata$4", FALSE, FALSE, TRUE);
4363
      if (h1 != NULL
4364
	  && (h1->root.type == bfd_link_hash_defined
4365
	   || h1->root.type == bfd_link_hash_defweak)
4366
	  && h1->root.u.def.section != NULL
4367
	  && h1->root.u.def.section->output_section != NULL)
4368
	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4369
	  ((h1->root.u.def.value
4370
	    + h1->root.u.def.section->output_section->vma
4371
	    + h1->root.u.def.section->output_offset)
4372
	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4373
      else
4374
	{
4375
	  _bfd_error_handler
4376
	    (_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4377
	     abfd);
4378
	  result = FALSE;
4379
	}
4380
 
4381
      /* The import address table.  This is the size/address of
4382
         .idata$5.  */
4383
      h1 = coff_link_hash_lookup (coff_hash_table (info),
4384
				  ".idata$5", FALSE, FALSE, TRUE);
4385
      if (h1 != NULL
4386
	  && (h1->root.type == bfd_link_hash_defined
4387
	   || h1->root.type == bfd_link_hash_defweak)
4388
	  && h1->root.u.def.section != NULL
4389
	  && h1->root.u.def.section->output_section != NULL)
4390
	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4391
	  (h1->root.u.def.value
4392
	   + h1->root.u.def.section->output_section->vma
4393
	   + h1->root.u.def.section->output_offset);
4394
      else
4395
	{
4396
	  _bfd_error_handler
4397
	    (_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4398
	     abfd);
4399
	  result = FALSE;
4400
	}
4401
 
4402
      h1 = coff_link_hash_lookup (coff_hash_table (info),
4403
				  ".idata$6", FALSE, FALSE, TRUE);
4404
      if (h1 != NULL
4405
	  && (h1->root.type == bfd_link_hash_defined
4406
	   || h1->root.type == bfd_link_hash_defweak)
4407
	  && h1->root.u.def.section != NULL
4408
	  && h1->root.u.def.section->output_section != NULL)
4409
	pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4410
	  ((h1->root.u.def.value
4411
	    + h1->root.u.def.section->output_section->vma
4412
	    + h1->root.u.def.section->output_offset)
4413
	   - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4414
      else
4415
	{
4416
	  _bfd_error_handler
4417
	    (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4418
	     abfd);
4419
	  result = FALSE;
4420
	}
4421
    }
4422
  else
4423
    {
4424
      h1 = coff_link_hash_lookup (coff_hash_table (info),
4425
				  "__IAT_start__", FALSE, FALSE, TRUE);
4426
      if (h1 != NULL
4427
	  && (h1->root.type == bfd_link_hash_defined
4428
	   || h1->root.type == bfd_link_hash_defweak)
4429
	  && h1->root.u.def.section != NULL
4430
	  && h1->root.u.def.section->output_section != NULL)
4431
	{
4432
	  bfd_vma iat_va;
4433
 
4434
	  iat_va =
4435
	    (h1->root.u.def.value
4436
	     + h1->root.u.def.section->output_section->vma
4437
	     + h1->root.u.def.section->output_offset);
4438
 
4439
	  h1 = coff_link_hash_lookup (coff_hash_table (info),
4440
				      "__IAT_end__", FALSE, FALSE, TRUE);
4441
	  if (h1 != NULL
4442
	      && (h1->root.type == bfd_link_hash_defined
4443
	       || h1->root.type == bfd_link_hash_defweak)
4444
	      && h1->root.u.def.section != NULL
4445
	      && h1->root.u.def.section->output_section != NULL)
4446
	    {
4447
	      pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4448
		((h1->root.u.def.value
4449
		  + h1->root.u.def.section->output_section->vma
4450
		  + h1->root.u.def.section->output_offset)
4451
		 - iat_va);
4452
	      if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4453
		pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4454
		  iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4455
	    }
4456
	  else
4457
	    {
4458
	      _bfd_error_handler
4459
		(_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4460
		   " because .idata$6 is missing"), abfd);
4461
	      result = FALSE;
4462
	    }
4463
        }
4464
    }
4465
 
4466
  h1 = coff_link_hash_lookup (coff_hash_table (info),
6324 serge 4467
			      (bfd_get_symbol_leading_char (abfd) != 0
5197 serge 4468
			       ? "__tls_used" : "_tls_used"),
4469
			      FALSE, FALSE, TRUE);
4470
  if (h1 != NULL)
4471
    {
4472
      if ((h1->root.type == bfd_link_hash_defined
4473
	   || h1->root.type == bfd_link_hash_defweak)
4474
	  && h1->root.u.def.section != NULL
4475
	  && h1->root.u.def.section->output_section != NULL)
4476
	pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4477
	  (h1->root.u.def.value
4478
	   + h1->root.u.def.section->output_section->vma
4479
	   + h1->root.u.def.section->output_offset
4480
	   - pe_data (abfd)->pe_opthdr.ImageBase);
4481
      else
4482
	{
4483
	  _bfd_error_handler
4484
	    (_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"),
4485
	     abfd);
4486
	  result = FALSE;
4487
	}
4488
     /* According to PECOFF sepcifications by Microsoft version 8.2
4489
	the TLS data directory consists of 4 pointers, followed
4490
	by two 4-byte integer. This implies that the total size
4491
	is different for 32-bit and 64-bit executables.  */
4492
#if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
4493
      pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4494
#else
4495
      pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4496
#endif
4497
    }
4498
 
4499
/* If there is a .pdata section and we have linked pdata finally, we
4500
     need to sort the entries ascending.  */
4501
#if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
4502
  {
4503
    asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4504
 
4505
    if (sec)
4506
      {
4507
	bfd_size_type x = sec->rawsize;
4508
	bfd_byte *tmp_data = NULL;
4509
 
4510
	if (x)
4511
	  tmp_data = bfd_malloc (x);
4512
 
4513
	if (tmp_data != NULL)
4514
	  {
4515
	    if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
4516
	      {
4517
		qsort (tmp_data,
4518
		       (size_t) (x / 12),
4519
		       12, sort_x64_pdata);
4520
		bfd_set_section_contents (pfinfo->output_bfd, sec,
4521
					  tmp_data, 0, x);
4522
	      }
4523
	    free (tmp_data);
4524
	  }
6324 serge 4525
	else
4526
	  result = FALSE;
5197 serge 4527
      }
4528
  }
4529
#endif
4530
 
6324 serge 4531
  rsrc_process_section (abfd, pfinfo);
4532
 
5197 serge 4533
  /* If we couldn't find idata$2, we either have an excessively
4534
     trivial program or are in DEEP trouble; we have to assume trivial
4535
     program....  */
4536
  return result;
4537
}