VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/ldr/ldrELFRelocatable.cpp.h@ 87110

Last change on this file since 87110 was 85556, checked in by vboxsync, 4 years ago

IPRT/ldrELF: Fixed bug in segment enum and conversion for ET_REL files, iFirstSect should be 1 for these. bugref:9801

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 130.9 KB
Line 
1/* $Id: ldrELFRelocatable.cpp.h 85556 2020-07-30 13:15:06Z vboxsync $ */
2/** @file
3 * IPRT - Binary Image Loader, Template for ELF Relocatable Images.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Defined Constants And Macros *
30*******************************************************************************/
31#if ELF_MODE == 32
32# define RTLDRELF_NAME(name) rtldrELF32##name
33# define RTLDRELF_SUFF(name) name##32
34# define RTLDRELF_MID(pre,suff) pre##32##suff
35# define FMT_ELF_ADDR "%08RX32"
36# define FMT_ELF_ADDR7 "%07RX32"
37# define FMT_ELF_HALF "%04RX16"
38# define FMT_ELF_OFF "%08RX32"
39# define FMT_ELF_SIZE "%08RX32"
40# define FMT_ELF_SWORD "%RI32"
41# define FMT_ELF_WORD "%08RX32"
42# define FMT_ELF_XWORD "%08RX32"
43# define FMT_ELF_SXWORD "%RI32"
44# define Elf_Xword Elf32_Word
45# define Elf_Sxword Elf32_Sword
46
47#elif ELF_MODE == 64
48# define RTLDRELF_NAME(name) rtldrELF64##name
49# define RTLDRELF_SUFF(name) name##64
50# define RTLDRELF_MID(pre,suff) pre##64##suff
51# define FMT_ELF_ADDR "%016RX64"
52# define FMT_ELF_ADDR7 "%08RX64"
53# define FMT_ELF_HALF "%04RX16"
54# define FMT_ELF_SHALF "%RI16"
55# define FMT_ELF_OFF "%016RX64"
56# define FMT_ELF_SIZE "%016RX64"
57# define FMT_ELF_SWORD "%RI32"
58# define FMT_ELF_WORD "%08RX32"
59# define FMT_ELF_XWORD "%016RX64"
60# define FMT_ELF_SXWORD "%RI64"
61# define Elf_Xword Elf64_Xword
62# define Elf_Sxword Elf64_Sxword
63#endif
64
65#define Elf_Ehdr RTLDRELF_MID(Elf,_Ehdr)
66#define Elf_Phdr RTLDRELF_MID(Elf,_Phdr)
67#define Elf_Shdr RTLDRELF_MID(Elf,_Shdr)
68#define Elf_Sym RTLDRELF_MID(Elf,_Sym)
69#define Elf_Rel RTLDRELF_MID(Elf,_Rel)
70#define Elf_Rela RTLDRELF_MID(Elf,_Rela)
71#define Elf_Nhdr RTLDRELF_MID(Elf,_Nhdr)
72#define Elf_Dyn RTLDRELF_MID(Elf,_Dyn)
73#define Elf_Addr RTLDRELF_MID(Elf,_Addr)
74#define Elf_Half RTLDRELF_MID(Elf,_Half)
75#define Elf_Off RTLDRELF_MID(Elf,_Off)
76#define Elf_Size RTLDRELF_MID(Elf,_Size)
77#define Elf_Sword RTLDRELF_MID(Elf,_Sword)
78#define Elf_Word RTLDRELF_MID(Elf,_Word)
79
80#define RTLDRMODELF RTLDRELF_MID(RTLDRMODELF,RT_NOTHING)
81#define PRTLDRMODELF RTLDRELF_MID(PRTLDRMODELF,RT_NOTHING)
82
83#define RTLDRMODELFSHX RTLDRELF_MID(RTLDRMODELFSHX,RT_NOTHING)
84#define PRTLDRMODELFSHX RTLDRELF_MID(PRTLDRMODELFSHX,RT_NOTHING)
85
86#define ELF_R_SYM(info) RTLDRELF_MID(ELF,_R_SYM)(info)
87#define ELF_R_TYPE(info) RTLDRELF_MID(ELF,_R_TYPE)(info)
88#define ELF_R_INFO(sym, type) RTLDRELF_MID(ELF,_R_INFO)(sym, type)
89
90#define ELF_ST_BIND(info) RTLDRELF_MID(ELF,_ST_BIND)(info)
91
92
93
94/*******************************************************************************
95* Structures and Typedefs *
96*******************************************************************************/
97/**
98 * Extra section info.
99 */
100typedef struct RTLDRMODELFSHX
101{
102 /** The corresponding program header. */
103 uint16_t idxPhdr;
104 /** The corresponding dynamic section entry (address). */
105 uint16_t idxDt;
106 /** The DT tag. */
107 uint32_t uDtTag;
108} RTLDRMODELFSHX;
109typedef RTLDRMODELFSHX *PRTLDRMODELFSHX;
110
111/**
112 * The ELF loader structure.
113 */
114typedef struct RTLDRMODELF
115{
116 /** Core module structure. */
117 RTLDRMODINTERNAL Core;
118 /** Pointer to readonly mapping of the image bits.
119 * This mapping is provided by the pReader. */
120 const void *pvBits;
121
122 /** The ELF header. */
123 Elf_Ehdr Ehdr;
124 /** Pointer to our copy of the section headers with sh_addr as RVAs.
125 * The virtual addresses in this array is the 0 based assignments we've given the image.
126 * Not valid if the image is DONE. */
127 Elf_Shdr *paShdrs;
128 /** Unmodified section headers (allocated after paShdrs, so no need to free).
129 * Not valid if the image is DONE. */
130 Elf_Shdr const *paOrgShdrs;
131 /** Runs parallel to paShdrs and is part of the same allocation. */
132 PRTLDRMODELFSHX paShdrExtras;
133 /** Base section number, either 1 or zero depending on whether we've
134 * re-used the NULL entry for .elf.headers in ET_EXEC/ET_DYN. */
135 unsigned iFirstSect;
136 /** Set if the SHF_ALLOC section headers are in order of sh_addr. */
137 bool fShdrInOrder;
138 /** The size of the loaded image. */
139 size_t cbImage;
140
141 /** The image base address if it's an EXEC or DYN image. */
142 Elf_Addr LinkAddress;
143
144 struct
145 {
146 /** The symbol section index. */
147 unsigned iSymSh;
148 /** Number of symbols in the table. */
149 unsigned cSyms;
150 /** Pointer to symbol table within RTLDRMODELF::pvBits. */
151 const Elf_Sym *paSyms;
152
153 /** The string section index. */
154 unsigned iStrSh;
155 /** Size of the string table. */
156 unsigned cbStr;
157 /** Pointer to string table within RTLDRMODELF::pvBits. */
158 const char *pStr;
159 } Rel /**< Regular symbols and strings. */
160 , Dyn /**< Dynamic symbols and strings. */;
161
162 /** Pointer to section header string table within RTLDRMODELF::pvBits. */
163 const char *pShStr;
164 /** Size of the section header string table. */
165 unsigned cbShStr;
166
167 /** The '.eh_frame' section index. Zero if not searched for, ~0U if not found. */
168 unsigned iShEhFrame;
169 /** The '.eh_frame_hdr' section index. Zero if not searched for, ~0U if not found. */
170 unsigned iShEhFrameHdr;
171
172 /** The '.dynamic' / SHT_DYNAMIC section index. ~0U if not present. */
173 unsigned iShDynamic;
174 /** Number of entries in paDynamic. */
175 unsigned cDynamic;
176 /** The dynamic section (NULL for ET_REL). */
177 Elf_Dyn *paDynamic;
178 /** Program headers (NULL for ET_REL). */
179 Elf_Phdr *paPhdrs;
180
181 /** Info extracted from PT_DYNAMIC and the program headers. */
182 struct
183 {
184 /** DT_RELA/DT_REL. */
185 Elf_Addr uPtrRelocs;
186 /** DT_RELASZ/DT_RELSZ. */
187 Elf_Xword cbRelocs;
188 /** Non-zero if we've seen DT_RELAENT/DT_RELENT. */
189 unsigned cbRelocEntry;
190 /** DT_RELA or DT_REL. */
191 unsigned uRelocType;
192 /** The index of the section header matching DT_RELA/DT_REL. */
193 unsigned idxShRelocs;
194
195 /** DT_JMPREL. */
196 Elf_Addr uPtrJmpRelocs;
197 /** DT_PLTRELSZ. */
198 Elf_Xword cbJmpRelocs;
199 /** DT_RELA or DT_REL (if we've seen DT_PLTREL). */
200 unsigned uJmpRelocType;
201 /** The index of the section header matching DT_JMPREL. */
202 unsigned idxShJmpRelocs;
203 } DynInfo;
204} RTLDRMODELF;
205/** Pointer to an ELF module instance. */
206typedef RTLDRMODELF *PRTLDRMODELF;
207
208
209/**
210 * Maps the image bits into memory and resolve pointers into it.
211 *
212 * @returns iprt status code.
213 * @param pModElf The ELF loader module instance data.
214 * @param fNeedsBits Set if we actually need the pvBits member.
215 * If we don't, we can simply read the string and symbol sections, thus saving memory.
216 */
217static int RTLDRELF_NAME(MapBits)(PRTLDRMODELF pModElf, bool fNeedsBits)
218{
219 NOREF(fNeedsBits);
220 if (pModElf->pvBits)
221 return VINF_SUCCESS;
222 int rc = pModElf->Core.pReader->pfnMap(pModElf->Core.pReader, &pModElf->pvBits);
223 if (RT_SUCCESS(rc))
224 {
225 const uint8_t *pu8 = (const uint8_t *)pModElf->pvBits;
226 if (pModElf->Rel.iSymSh != ~0U)
227 pModElf->Rel.paSyms = (const Elf_Sym *)(pu8 + pModElf->paShdrs[pModElf->Rel.iSymSh].sh_offset);
228 if (pModElf->Rel.iStrSh != ~0U)
229 pModElf->Rel.pStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Rel.iStrSh].sh_offset);
230 if (pModElf->Dyn.iSymSh != ~0U)
231 pModElf->Dyn.paSyms = (const Elf_Sym *)(pu8 + pModElf->paShdrs[pModElf->Dyn.iSymSh].sh_offset);
232 if (pModElf->Dyn.iStrSh != ~0U)
233 pModElf->Dyn.pStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Dyn.iStrSh].sh_offset);
234 pModElf->pShStr = (const char *)(pu8 + pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_offset);
235
236 /*
237 * Verify that the ends of the string tables have a zero terminator
238 * (this avoids duplicating the appropriate checks later in the code accessing the string tables).
239 *
240 * sh_offset and sh_size were verfied in RTLDRELF_NAME(ValidateSectionHeader)() already so they
241 * are safe to use.
242 */
243 AssertMsgStmt( pModElf->Rel.iStrSh == ~0U
244 || pModElf->Rel.pStr[pModElf->paShdrs[pModElf->Rel.iStrSh].sh_size - 1] == '\0',
245 ("The string table is not zero terminated!\n"),
246 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
247 AssertMsgStmt( pModElf->Dyn.iStrSh == ~0U
248 || pModElf->Dyn.pStr[pModElf->paShdrs[pModElf->Dyn.iStrSh].sh_size - 1] == '\0',
249 ("The string table is not zero terminated!\n"),
250 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
251 AssertMsgStmt(pModElf->pShStr[pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_size - 1] == '\0',
252 ("The section header string table is not zero terminated!\n"),
253 rc = VERR_LDRELF_UNTERMINATED_STRING_TAB);
254
255 if (RT_FAILURE(rc))
256 {
257 /* Unmap. */
258 int rc2 = pModElf->Core.pReader->pfnUnmap(pModElf->Core.pReader, pModElf->pvBits);
259 AssertRC(rc2);
260 pModElf->pvBits = NULL;
261 pModElf->Rel.paSyms = NULL;
262 pModElf->Rel.pStr = NULL;
263 pModElf->Dyn.paSyms = NULL;
264 pModElf->Dyn.pStr = NULL;
265 pModElf->pShStr = NULL;
266 }
267 }
268 return rc;
269}
270
271
272/*
273 *
274 * EXEC & DYN.
275 * EXEC & DYN.
276 * EXEC & DYN.
277 * EXEC & DYN.
278 * EXEC & DYN.
279 *
280 */
281
282/**
283 * Get the symbol and symbol value.
284 *
285 * @returns iprt status code.
286 * @param pModElf The ELF loader module instance data.
287 * @param BaseAddr The base address which the module is being fixedup to.
288 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
289 * @param pvUser User argument to pass to the callback.
290 * @param iSym The symbol to get.
291 * @param ppSym Where to store the symbol pointer on success. (read only)
292 * @param pSymValue Where to store the symbol value on success.
293 */
294static int RTLDRELF_NAME(SymbolExecDyn)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
295 Elf_Size iSym, const Elf_Sym **ppSym, Elf_Addr *pSymValue)
296{
297 /*
298 * Validate and find the symbol.
299 */
300 AssertMsgReturn(iSym < pModElf->Dyn.cSyms, ("iSym=%d is an invalid symbol index!\n", iSym), VERR_LDRELF_INVALID_SYMBOL_INDEX);
301 const Elf_Sym *pSym = &pModElf->Dyn.paSyms[iSym];
302 *ppSym = pSym;
303
304 AssertMsgReturn(pSym->st_name < pModElf->Dyn.cbStr,
305 ("iSym=%d st_name=%d str sh_size=%d\n", iSym, pSym->st_name, pModElf->Dyn.cbStr),
306 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
307 const char * const pszName = pModElf->Dyn.pStr + pSym->st_name;
308
309 /*
310 * Determine the symbol value.
311 *
312 * Symbols needs different treatment depending on which section their are in.
313 * Undefined and absolute symbols goes into special non-existing sections.
314 */
315 switch (pSym->st_shndx)
316 {
317 /*
318 * Undefined symbol, needs resolving.
319 *
320 * Since ELF has no generic concept of importing from specific module (the OS/2 ELF format
321 * has but that's an OS extension and only applies to programs and dlls), we'll have to ask
322 * the resolver callback to do a global search.
323 */
324 case SHN_UNDEF:
325 {
326 /* Try to resolve the symbol. */
327 RTUINTPTR Value;
328 int rc = pfnGetImport(&pModElf->Core, "", pszName, ~0U, &Value, pvUser);
329 AssertMsgRCReturn(rc, ("Failed to resolve '%s' (iSym=" FMT_ELF_SIZE " rc=%Rrc\n", pszName, iSym, rc), rc);
330
331 *pSymValue = (Elf_Addr)Value;
332 AssertMsgReturn((RTUINTPTR)*pSymValue == Value,
333 ("Symbol value overflowed! '%s' (iSym=" FMT_ELF_SIZE "\n", pszName, iSym), VERR_SYMBOL_VALUE_TOO_BIG);
334
335 Log2(("rtldrELF: #%-3d - UNDEF " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
336 break;
337 }
338
339 /*
340 * Absolute symbols needs no fixing since they are, well, absolute.
341 */
342 case SHN_ABS:
343 *pSymValue = pSym->st_value;
344 Log2(("rtldrELF: #%-3d - ABS " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
345 break;
346
347 /*
348 * All other symbols are addressed relative the image base in DYN and EXEC binaries.
349 */
350 default:
351 AssertMsgReturn(pSym->st_shndx < pModElf->Ehdr.e_shnum,
352 ("iSym=%d st_shndx=%d e_shnum=%d pszName=%s\n", iSym, pSym->st_shndx, pModElf->Ehdr.e_shnum, pszName),
353 VERR_BAD_EXE_FORMAT);
354 *pSymValue = pSym->st_value + BaseAddr;
355 Log2(("rtldrELF: #%-3d - %5d " FMT_ELF_ADDR " '%s'\n", iSym, pSym->st_shndx, *pSymValue, pszName));
356 break;
357 }
358
359 return VINF_SUCCESS;
360}
361
362
363#if ELF_MODE == 32
364/** Helper for RelocateSectionExecDyn. */
365DECLINLINE(const Elf_Shdr *) RTLDRELF_NAME(RvaToSectionHeader)(PRTLDRMODELF pModElf, Elf_Addr uRva)
366{
367 const Elf_Shdr * const pShdrFirst = pModElf->paShdrs;
368 const Elf_Shdr *pShdr = pShdrFirst + pModElf->Ehdr.e_shnum;
369 while (--pShdr != pShdrFirst)
370 if (uRva - pShdr->sh_addr /*rva*/ < pShdr->sh_size)
371 return pShdr;
372 AssertFailed();
373 return pShdr;
374}
375#endif
376
377
378/**
379 * Applies the fixups for a section in an executable image.
380 *
381 * @returns iprt status code.
382 * @param pModElf The ELF loader module instance data.
383 * @param BaseAddr The base address which the module is being fixedup to.
384 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
385 * @param pvUser User argument to pass to the callback.
386 * @param SecAddr The section address. This is the address the relocations are relative to.
387 * @param cbSec The section size. The relocations must be inside this.
388 * @param pu8SecBaseR Where we read section bits from.
389 * @param pu8SecBaseW Where we write section bits to.
390 * @param pvRelocs Pointer to where we read the relocations from.
391 * @param cbRelocs Size of the relocations.
392 */
393static int RTLDRELF_NAME(RelocateSectionExecDyn)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr,
394 PFNRTLDRIMPORT pfnGetImport, void *pvUser,
395 const Elf_Addr SecAddr, Elf_Size cbSec,
396 const uint8_t *pu8SecBaseR, uint8_t *pu8SecBaseW,
397 const void *pvRelocs, Elf_Size cbRelocs)
398{
399#if ELF_MODE != 32
400 NOREF(pu8SecBaseR);
401#endif
402
403 /*
404 * Iterate the relocations.
405 * The relocations are stored in an array of Elf32_Rel records and covers the entire relocation section.
406 */
407#if ELF_MODE == 32
408 const Elf_Shdr *pShdr = pModElf->paShdrs;
409 const Elf_Addr offDelta = BaseAddr - pModElf->LinkAddress;
410#endif
411 const Elf_Reloc *paRels = (const Elf_Reloc *)pvRelocs;
412 const unsigned iRelMax = (unsigned)(cbRelocs / sizeof(paRels[0]));
413 AssertMsgReturn(iRelMax == cbRelocs / sizeof(paRels[0]), (FMT_ELF_SIZE "\n", cbRelocs / sizeof(paRels[0])),
414 VERR_IMAGE_TOO_BIG);
415 for (unsigned iRel = 0; iRel < iRelMax; iRel++)
416 {
417 /*
418 * Apply fixups not taking a symbol (will 'continue' rather than 'break').
419 */
420 AssertMsgReturn(paRels[iRel].r_offset < cbSec, (FMT_ELF_ADDR " " FMT_ELF_SIZE "\n", paRels[iRel].r_offset, cbSec),
421 VERR_LDRELF_INVALID_RELOCATION_OFFSET);
422#if ELF_MODE == 32
423 if (paRels[iRel].r_offset - pShdr->sh_addr /*rva*/ >= pShdr->sh_size)
424 pShdr = RTLDRELF_NAME(RvaToSectionHeader)(pModElf, paRels[iRel].r_offset);
425 static const Elf_Addr s_uZero = 0;
426 const Elf_Addr *pAddrR = RT_LIKELY(pShdr->sh_type != SHT_NOBITS) /* Where to read the addend. */
427 ? (const Elf_Addr *)(pu8SecBaseR + paRels[iRel].r_offset - pShdr->sh_addr /*rva*/
428 + pShdr->sh_offset)
429 : &s_uZero;
430#endif
431 Elf_Addr *pAddrW = (Elf_Addr *)(pu8SecBaseW + paRels[iRel].r_offset); /* Where to write the fixup. */
432 switch (ELF_R_TYPE(paRels[iRel].r_info))
433 {
434 /*
435 * Image relative (addend + base).
436 */
437#if ELF_MODE == 32
438 case R_386_RELATIVE:
439 {
440 const Elf_Addr Value = *pAddrR + BaseAddr;
441 *(uint32_t *)pAddrW = Value;
442 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_RELATIVE Value=" FMT_ELF_ADDR "\n",
443 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
444 AssertCompile(sizeof(Value) == sizeof(uint32_t));
445 continue;
446 }
447#elif ELF_MODE == 64
448 case R_X86_64_RELATIVE:
449 {
450 const Elf_Addr Value = paRels[iRel].r_addend + BaseAddr;
451 *(uint64_t *)pAddrW = (uint64_t)Value;
452 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_RELATIVE Value=" FMT_ELF_ADDR "\n",
453 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
454 AssertCompile(sizeof(Value) == sizeof(uint64_t));
455 continue;
456 }
457#endif
458
459 /*
460 * R_XXX_NONE.
461 */
462#if ELF_MODE == 32
463 case R_386_NONE:
464#elif ELF_MODE == 64
465 case R_X86_64_NONE:
466#endif
467 continue;
468 }
469
470 /*
471 * Validate and find the symbol, resolve undefined ones.
472 */
473 const Elf_Sym *pSym = NULL; /* shut up gcc */
474 Elf_Addr SymValue = 0; /* shut up gcc-4 */
475 int rc = RTLDRELF_NAME(SymbolExecDyn)(pModElf, BaseAddr, pfnGetImport, pvUser, ELF_R_SYM(paRels[iRel].r_info), &pSym, &SymValue);
476 if (RT_FAILURE(rc))
477 return rc;
478
479 /*
480 * Apply the fixup.
481 */
482 switch (ELF_R_TYPE(paRels[iRel].r_info))
483 {
484#if ELF_MODE == 32
485 /*
486 * GOT/PLT.
487 */
488 case R_386_GLOB_DAT:
489 {
490 *(uint32_t *)pAddrW = (uint32_t)SymValue;
491 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_GLOB_DAT Value=" FMT_ELF_ADDR "\n",
492 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
493 AssertCompile(sizeof(SymValue) == sizeof(uint32_t));
494 break;
495 }
496
497 case R_386_JMP_SLOT:
498 {
499 *(uint32_t *)pAddrW = (uint32_t)SymValue;
500 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_JMP_SLOT Value=" FMT_ELF_ADDR "\n",
501 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
502 AssertCompile(sizeof(SymValue) == sizeof(uint32_t));
503 break;
504 }
505
506 /*
507 * Absolute addressing.
508 */
509 case R_386_32:
510 {
511 Elf_Addr Value;
512 if (pSym->st_shndx < pModElf->Ehdr.e_shnum)
513 Value = *pAddrR + offDelta; /* Simplified. */
514 else if (pSym->st_shndx == SHN_ABS)
515 continue; /* Internal fixup, no need to apply it. */
516 else if (pSym->st_shndx == SHN_UNDEF)
517 Value = SymValue + *pAddrR;
518 else
519 AssertFailedReturn(VERR_LDR_GENERAL_FAILURE); /** @todo SHN_COMMON */
520 *(uint32_t *)pAddrW = Value;
521 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_32 Value=" FMT_ELF_ADDR "\n",
522 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
523 break;
524 }
525
526 /*
527 * PC relative addressing.
528 */
529 case R_386_PC32:
530 {
531 Elf_Addr Value;
532 if (pSym->st_shndx < pModElf->Ehdr.e_shnum)
533 continue; /* Internal fixup, no need to apply it. */
534 else if (pSym->st_shndx == SHN_ABS)
535 Value = *pAddrR + offDelta; /* Simplified. */
536 else if (pSym->st_shndx == SHN_UNDEF)
537 {
538 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
539 Value = SymValue + *(uint32_t *)pAddrR - SourceAddr;
540 *(uint32_t *)pAddrW = Value;
541 }
542 else
543 AssertFailedReturn(VERR_LDR_GENERAL_FAILURE); /** @todo SHN_COMMON */
544 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_386_PC32 Value=" FMT_ELF_ADDR "\n",
545 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value));
546 break;
547 }
548
549#elif ELF_MODE == 64
550 /*
551 * GOT/PLT.
552 */
553 case R_X86_64_GLOB_DAT:
554 {
555 *(uint64_t *)pAddrW = (uint64_t)SymValue;
556 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_GLOB_DAT Value=" FMT_ELF_ADDR "\n",
557 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
558 AssertCompile(sizeof(SymValue) == sizeof(uint64_t));
559 break;
560 }
561
562 case R_X86_64_JMP_SLOT:
563 {
564 *(uint64_t *)pAddrW = (uint64_t)SymValue;
565 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_JMP_SLOT Value=" FMT_ELF_ADDR "\n",
566 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, SymValue));
567 AssertCompile(sizeof(SymValue) == sizeof(uint64_t));
568 break;
569 }
570
571 /*
572 * Absolute addressing.
573 */
574 case R_X86_64_64:
575 {
576 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
577 *(uint64_t *)pAddrW = Value;
578 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_64 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
579 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
580 break;
581 }
582
583 /*
584 * Truncated 32-bit value (zero-extendedable to the 64-bit value).
585 */
586 case R_X86_64_32:
587 {
588 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
589 *(uint32_t *)pAddrW = (uint32_t)Value;
590 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
591 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
592 AssertMsgReturn((Elf_Addr)*(uint32_t *)pAddrW == SymValue, ("Value=" FMT_ELF_ADDR "\n", SymValue),
593 VERR_SYMBOL_VALUE_TOO_BIG);
594 break;
595 }
596
597 /*
598 * Truncated 32-bit value (sign-extendedable to the 64-bit value).
599 */
600 case R_X86_64_32S:
601 {
602 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
603 *(int32_t *)pAddrW = (int32_t)Value;
604 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_32S Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
605 SecAddr + paRels[iRel].r_offset + BaseAddr, paRels[iRel].r_offset, Value, SymValue));
606 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
607 break;
608 }
609
610 /*
611 * PC relative addressing.
612 */
613 case R_X86_64_PC32:
614 {
615 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
616 const Elf_Addr Value = SymValue + paRels[iRel].r_addend - SourceAddr;
617 *(int32_t *)pAddrW = (int32_t)Value;
618 Log4((FMT_ELF_ADDR "/" FMT_ELF_ADDR7 ": R_X86_64_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
619 SourceAddr, paRels[iRel].r_offset, Value, SymValue));
620 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
621 break;
622 }
623
624#endif
625 default:
626 AssertMsgFailed(("Unknown relocation type: %d (iRel=%d iRelMax=%d)\n",
627 ELF_R_TYPE(paRels[iRel].r_info), iRel, iRelMax));
628 return VERR_LDRELF_RELOCATION_NOT_SUPPORTED;
629 }
630 }
631
632 return VINF_SUCCESS;
633}
634
635
636
637/*
638 *
639 * REL
640 * REL
641 * REL
642 * REL
643 * REL
644 *
645 */
646
647/**
648 * Get the symbol and symbol value.
649 *
650 * @returns iprt status code.
651 * @param pModElf The ELF loader module instance data.
652 * @param BaseAddr The base address which the module is being fixedup to.
653 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
654 * @param pvUser User argument to pass to the callback.
655 * @param iSym The symbol to get.
656 * @param ppSym Where to store the symbol pointer on success. (read only)
657 * @param pSymValue Where to store the symbol value on success.
658 */
659static int RTLDRELF_NAME(Symbol)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
660 Elf_Size iSym, const Elf_Sym **ppSym, Elf_Addr *pSymValue)
661{
662 /*
663 * Validate and find the symbol.
664 */
665 AssertMsgReturn(iSym < pModElf->Rel.cSyms, ("iSym=%d is an invalid symbol index!\n", iSym), VERR_LDRELF_INVALID_SYMBOL_INDEX);
666 const Elf_Sym *pSym = &pModElf->Rel.paSyms[iSym];
667 *ppSym = pSym;
668
669 AssertMsgReturn(pSym->st_name < pModElf->Rel.cbStr,
670 ("iSym=%d st_name=%d str sh_size=%d\n", iSym, pSym->st_name, pModElf->Rel.cbStr),
671 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
672 const char *pszName = ELF_STR(pModElf, pSym->st_name);
673
674 /*
675 * Determine the symbol value.
676 *
677 * Symbols needs different treatment depending on which section their are in.
678 * Undefined and absolute symbols goes into special non-existing sections.
679 */
680 switch (pSym->st_shndx)
681 {
682 /*
683 * Undefined symbol, needs resolving.
684 *
685 * Since ELF has no generic concept of importing from specific module (the OS/2 ELF format
686 * has but that's an OS extension and only applies to programs and dlls), we'll have to ask
687 * the resolver callback to do a global search.
688 */
689 case SHN_UNDEF:
690 {
691 /* Try to resolve the symbol. */
692 RTUINTPTR Value;
693 int rc = pfnGetImport(&pModElf->Core, "", pszName, ~0U, &Value, pvUser);
694 AssertMsgRCReturn(rc, ("Failed to resolve '%s' (iSym=" FMT_ELF_SIZE " rc=%Rrc\n", pszName, iSym, rc), rc);
695 *pSymValue = (Elf_Addr)Value;
696
697 AssertMsgReturn((RTUINTPTR)*pSymValue == Value,
698 ("Symbol value overflowed! '%s' (iSym=" FMT_ELF_SIZE ")\n", pszName, iSym),
699 VERR_SYMBOL_VALUE_TOO_BIG);
700
701 Log2(("rtldrELF: #%-3d - UNDEF " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
702 break;
703 }
704
705 /*
706 * Absolute symbols needs no fixing since they are, well, absolute.
707 */
708 case SHN_ABS:
709 *pSymValue = pSym->st_value;
710 Log2(("rtldrELF: #%-3d - ABS " FMT_ELF_ADDR " '%s'\n", iSym, *pSymValue, pszName));
711 break;
712
713 /*
714 * All other symbols are addressed relative to their section and need to be fixed up.
715 */
716 default:
717 if (pSym->st_shndx >= pModElf->Ehdr.e_shnum)
718 {
719 /* what about common symbols? */
720 AssertMsg(pSym->st_shndx < pModElf->Ehdr.e_shnum,
721 ("iSym=%d st_shndx=%d e_shnum=%d pszName=%s\n", iSym, pSym->st_shndx, pModElf->Ehdr.e_shnum, pszName));
722 return VERR_BAD_EXE_FORMAT;
723 }
724 *pSymValue = pSym->st_value + pModElf->paShdrs[pSym->st_shndx].sh_addr + BaseAddr;
725 Log2(("rtldrELF: #%-3d - %5d " FMT_ELF_ADDR " '%s'\n", iSym, pSym->st_shndx, *pSymValue, pszName));
726 break;
727 }
728
729 return VINF_SUCCESS;
730}
731
732
733/**
734 * Applies the fixups for a sections.
735 *
736 * @returns iprt status code.
737 * @param pModElf The ELF loader module instance data.
738 * @param BaseAddr The base address which the module is being fixedup to.
739 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
740 * @param pvUser User argument to pass to the callback.
741 * @param SecAddr The section address. This is the address the relocations are relative to.
742 * @param cbSec The section size. The relocations must be inside this.
743 * @param pu8SecBaseR Where we read section bits from.
744 * @param pu8SecBaseW Where we write section bits to.
745 * @param pvRelocs Pointer to where we read the relocations from.
746 * @param cbRelocs Size of the relocations.
747 */
748static int RTLDRELF_NAME(RelocateSectionRel)(PRTLDRMODELF pModElf, Elf_Addr BaseAddr, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
749 const Elf_Addr SecAddr, Elf_Size cbSec, const uint8_t *pu8SecBaseR,
750 uint8_t *pu8SecBaseW, const void *pvRelocs, Elf_Size cbRelocs)
751{
752#if ELF_MODE != 32
753 NOREF(pu8SecBaseR);
754#endif
755
756 /*
757 * Iterate the relocations.
758 * The relocations are stored in an array of Elf32_Rel records and covers the entire relocation section.
759 */
760 const Elf_Reloc *paRels = (const Elf_Reloc *)pvRelocs;
761 const unsigned iRelMax = (unsigned)(cbRelocs / sizeof(paRels[0]));
762 AssertMsgReturn(iRelMax == cbRelocs / sizeof(paRels[0]), (FMT_ELF_SIZE "\n", cbRelocs / sizeof(paRels[0])), VERR_IMAGE_TOO_BIG);
763 for (unsigned iRel = 0; iRel < iRelMax; iRel++)
764 {
765 /*
766 * Skip R_XXX_NONE entries early to avoid confusion in the symbol
767 * getter code.
768 */
769#if ELF_MODE == 32
770 if (ELF_R_TYPE(paRels[iRel].r_info) == R_386_NONE)
771 continue;
772#elif ELF_MODE == 64
773 if (ELF_R_TYPE(paRels[iRel].r_info) == R_X86_64_NONE)
774 continue;
775#endif
776
777
778 /*
779 * Get the symbol.
780 */
781 const Elf_Sym *pSym = NULL; /* shut up gcc */
782 Elf_Addr SymValue = 0; /* shut up gcc-4 */
783 int rc = RTLDRELF_NAME(Symbol)(pModElf, BaseAddr, pfnGetImport, pvUser, ELF_R_SYM(paRels[iRel].r_info), &pSym, &SymValue);
784 if (RT_FAILURE(rc))
785 return rc;
786
787 Log3(("rtldrELF: " FMT_ELF_ADDR " %02x %06x - " FMT_ELF_ADDR " %3d %02x %s\n",
788 paRels[iRel].r_offset, ELF_R_TYPE(paRels[iRel].r_info), (unsigned)ELF_R_SYM(paRels[iRel].r_info),
789 SymValue, (unsigned)pSym->st_shndx, pSym->st_info, ELF_STR(pModElf, pSym->st_name)));
790
791 /*
792 * Apply the fixup.
793 */
794 AssertMsgReturn(paRels[iRel].r_offset < cbSec, (FMT_ELF_ADDR " " FMT_ELF_SIZE "\n", paRels[iRel].r_offset, cbSec), VERR_LDRELF_INVALID_RELOCATION_OFFSET);
795#if ELF_MODE == 32
796 const Elf_Addr *pAddrR = (const Elf_Addr *)(pu8SecBaseR + paRels[iRel].r_offset); /* Where to read the addend. */
797#endif
798 Elf_Addr *pAddrW = (Elf_Addr *)(pu8SecBaseW + paRels[iRel].r_offset); /* Where to write the fixup. */
799 switch (ELF_R_TYPE(paRels[iRel].r_info))
800 {
801#if ELF_MODE == 32
802 /*
803 * Absolute addressing.
804 */
805 case R_386_32:
806 {
807 const Elf_Addr Value = SymValue + *pAddrR;
808 *(uint32_t *)pAddrW = Value;
809 Log4((FMT_ELF_ADDR": R_386_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
810 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
811 break;
812 }
813
814 /*
815 * PC relative addressing.
816 */
817 case R_386_PC32:
818 {
819 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
820 const Elf_Addr Value = SymValue + *(uint32_t *)pAddrR - SourceAddr;
821 *(uint32_t *)pAddrW = Value;
822 Log4((FMT_ELF_ADDR": R_386_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
823 SourceAddr, Value, SymValue));
824 break;
825 }
826
827 /* ignore */
828 case R_386_NONE:
829 break;
830
831#elif ELF_MODE == 64
832
833 /*
834 * Absolute addressing
835 */
836 case R_X86_64_64:
837 {
838 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
839 *(uint64_t *)pAddrW = Value;
840 Log4((FMT_ELF_ADDR": R_X86_64_64 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
841 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
842 break;
843 }
844
845 /*
846 * Truncated 32-bit value (zero-extendedable to the 64-bit value).
847 */
848 case R_X86_64_32:
849 {
850 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
851 *(uint32_t *)pAddrW = (uint32_t)Value;
852 Log4((FMT_ELF_ADDR": R_X86_64_32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
853 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
854 AssertMsgReturn((Elf_Addr)*(uint32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
855 break;
856 }
857
858 /*
859 * Truncated 32-bit value (sign-extendedable to the 64-bit value).
860 */
861 case R_X86_64_32S:
862 {
863 const Elf_Addr Value = SymValue + paRels[iRel].r_addend;
864 *(int32_t *)pAddrW = (int32_t)Value;
865 Log4((FMT_ELF_ADDR": R_X86_64_32S Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
866 SecAddr + paRels[iRel].r_offset + BaseAddr, Value, SymValue));
867 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
868 break;
869 }
870
871 /*
872 * PC relative addressing.
873 */
874 case R_X86_64_PC32:
875 case R_X86_64_PLT32: /* binutils commit 451875b4f976a527395e9303224c7881b65e12ed feature/regression. */
876 {
877 const Elf_Addr SourceAddr = SecAddr + paRels[iRel].r_offset + BaseAddr; /* Where the source really is. */
878 const Elf_Addr Value = SymValue + paRels[iRel].r_addend - SourceAddr;
879 *(int32_t *)pAddrW = (int32_t)Value;
880 Log4((FMT_ELF_ADDR": R_X86_64_PC32 Value=" FMT_ELF_ADDR " SymValue=" FMT_ELF_ADDR "\n",
881 SourceAddr, Value, SymValue));
882 AssertMsgReturn((Elf_Addr)*(int32_t *)pAddrW == Value, ("Value=" FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG); /** @todo check the sign-extending here. */
883 break;
884 }
885
886 /* ignore */
887 case R_X86_64_NONE:
888 break;
889#endif
890
891 default:
892 AssertMsgFailed(("Unknown relocation type: %d (iRel=%d iRelMax=%d)\n",
893 ELF_R_TYPE(paRels[iRel].r_info), iRel, iRelMax));
894 return VERR_LDRELF_RELOCATION_NOT_SUPPORTED;
895 }
896 }
897
898 return VINF_SUCCESS;
899}
900
901
902
903/** @copydoc RTLDROPS::pfnClose */
904static DECLCALLBACK(int) RTLDRELF_NAME(Close)(PRTLDRMODINTERNAL pMod)
905{
906 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
907
908 if (pModElf->paShdrs)
909 {
910 RTMemFree(pModElf->paShdrs);
911 pModElf->paShdrs = NULL;
912 }
913
914 if (pModElf->paPhdrs)
915 {
916 RTMemFree(pModElf->paPhdrs);
917 pModElf->paPhdrs = NULL;
918 }
919
920 if (pModElf->paDynamic)
921 {
922 RTMemFree(pModElf->paDynamic);
923 pModElf->paDynamic = NULL;
924 }
925
926 if (pModElf->pvBits)
927 {
928 pModElf->Core.pReader->pfnUnmap(pModElf->Core.pReader, pModElf->pvBits);
929 pModElf->pvBits = NULL;
930 }
931
932 return VINF_SUCCESS;
933}
934
935
936/** @copydoc RTLDROPS::Done */
937static DECLCALLBACK(int) RTLDRELF_NAME(Done)(PRTLDRMODINTERNAL pMod)
938{
939 NOREF(pMod); /*PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;*/
940 /** @todo Have to think more about this .... */
941 return -1;
942}
943
944
945/** @copydoc RTLDROPS::pfnEnumSymbols */
946static DECLCALLBACK(int) RTLDRELF_NAME(EnumSymbols)(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits,
947 RTUINTPTR BaseAddress, PFNRTLDRENUMSYMS pfnCallback, void *pvUser)
948{
949 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
950 NOREF(pvBits);
951
952 /*
953 * Validate the input.
954 */
955 Elf_Addr BaseAddr = (Elf_Addr)BaseAddress;
956 AssertMsgReturn((RTUINTPTR)BaseAddr == BaseAddress, ("%RTptr", BaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
957
958 /*
959 * Make sure we've got the string and symbol tables. (We don't need the pvBits.)
960 */
961 int rc = RTLDRELF_NAME(MapBits)(pModElf, false);
962 if (RT_FAILURE(rc))
963 return rc;
964
965 /*
966 * Enumerate the symbol table.
967 */
968 const Elf_Sym *paSyms = pModElf->Rel.paSyms;
969 unsigned cSyms = pModElf->Rel.cSyms;
970 const char *pszzStr = pModElf->Rel.pStr;
971 unsigned cbStr = pModElf->Rel.cbStr;
972 if ( ( !(fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL)
973 && pModElf->Dyn.cSyms > 0)
974 || cSyms == 0)
975 {
976 paSyms = pModElf->Dyn.paSyms;
977 cSyms = pModElf->Dyn.cSyms;
978 pszzStr = pModElf->Dyn.pStr;
979 cbStr = pModElf->Dyn.cbStr;
980 }
981
982 for (unsigned iSym = 1; iSym < cSyms; iSym++)
983 {
984 /*
985 * Skip imports (undefined).
986 */
987 if (paSyms[iSym].st_shndx != SHN_UNDEF)
988 {
989 /*
990 * Calc value and get name.
991 */
992 Elf_Addr Value;
993 if (paSyms[iSym].st_shndx == SHN_ABS)
994 /* absolute symbols are not subject to any relocation. */
995 Value = paSyms[iSym].st_value;
996 else if (paSyms[iSym].st_shndx < pModElf->Ehdr.e_shnum)
997 {
998 if (pModElf->Ehdr.e_type == ET_REL)
999 /* relative to the section. */
1000 Value = BaseAddr + paSyms[iSym].st_value + pModElf->paShdrs[paSyms[iSym].st_shndx].sh_addr;
1001 else /* Fixed up for link address. */
1002 Value = BaseAddr + paSyms[iSym].st_value - pModElf->LinkAddress;
1003 }
1004 else
1005 {
1006 AssertMsgFailed(("Arg! paSyms[%u].st_shndx=" FMT_ELF_HALF "\n", iSym, paSyms[iSym].st_shndx));
1007 return VERR_BAD_EXE_FORMAT;
1008 }
1009
1010 AssertMsgReturn(paSyms[iSym].st_name < cbStr,
1011 ("String outside string table! iSym=%d paSyms[iSym].st_name=%#x\n", iSym, paSyms[iSym].st_name),
1012 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
1013 const char * const pszName = pszzStr + paSyms[iSym].st_name;
1014
1015 /* String termination was already checked when the string table was mapped. */
1016 if ( *pszName != '\0'
1017 && ( (fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL)
1018 || ELF_ST_BIND(paSyms[iSym].st_info) == STB_GLOBAL) )
1019 {
1020 /*
1021 * Call back.
1022 */
1023 AssertMsgReturn(Value == (RTUINTPTR)Value, (FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
1024 rc = pfnCallback(pMod, pszName, iSym, (RTUINTPTR)Value, pvUser);
1025 if (rc)
1026 return rc;
1027 }
1028 }
1029 }
1030
1031 return VINF_SUCCESS;
1032}
1033
1034
1035/** @copydoc RTLDROPS::GetImageSize */
1036static DECLCALLBACK(size_t) RTLDRELF_NAME(GetImageSize)(PRTLDRMODINTERNAL pMod)
1037{
1038 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1039
1040 return pModElf->cbImage;
1041}
1042
1043
1044/** @copydoc RTLDROPS::GetBits */
1045static DECLCALLBACK(int) RTLDRELF_NAME(GetBits)(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
1046{
1047 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1048
1049 /*
1050 * This operation is currently only available on relocatable images.
1051 */
1052 switch (pModElf->Ehdr.e_type)
1053 {
1054 case ET_REL:
1055 case ET_DYN:
1056 break;
1057 case ET_EXEC:
1058 Log(("RTLdrELF: %s: Executable images are not supported yet!\n", pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader)));
1059 return VERR_LDRELF_EXEC;
1060 default: AssertFailedReturn(VERR_BAD_EXE_FORMAT);
1061 }
1062
1063 /*
1064 * Load the bits into pvBits.
1065 */
1066 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1067 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1068 {
1069 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1070 {
1071 AssertMsgReturn((size_t)paShdrs[iShdr].sh_size == (size_t)paShdrs[iShdr].sh_size, (FMT_ELF_SIZE "\n", paShdrs[iShdr].sh_size), VERR_IMAGE_TOO_BIG);
1072 switch (paShdrs[iShdr].sh_type)
1073 {
1074 case SHT_NOBITS:
1075 memset((uint8_t *)pvBits + paShdrs[iShdr].sh_addr, 0, (size_t)paShdrs[iShdr].sh_size);
1076 break;
1077
1078 case SHT_PROGBITS:
1079 default:
1080 {
1081 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, (uint8_t *)pvBits + paShdrs[iShdr].sh_addr,
1082 (size_t)paShdrs[iShdr].sh_size, paShdrs[iShdr].sh_offset);
1083 if (RT_FAILURE(rc))
1084 {
1085 Log(("RTLdrELF: %s: Read error when reading " FMT_ELF_SIZE " bytes at " FMT_ELF_OFF ", iShdr=%d\n",
1086 pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader),
1087 paShdrs[iShdr].sh_size, paShdrs[iShdr].sh_offset, iShdr));
1088 return rc;
1089 }
1090 }
1091 }
1092 }
1093 }
1094
1095 /*
1096 * Relocate the image.
1097 */
1098 return pModElf->Core.pOps->pfnRelocate(pMod, pvBits, BaseAddress, ~(RTUINTPTR)0, pfnGetImport, pvUser);
1099}
1100
1101
1102/** @copydoc RTLDROPS::Relocate */
1103static DECLCALLBACK(int) RTLDRELF_NAME(Relocate)(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress,
1104 RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
1105{
1106 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1107#ifdef LOG_ENABLED
1108 const char *pszLogName = pModElf->Core.pReader->pfnLogName(pModElf->Core.pReader);
1109#endif
1110 NOREF(OldBaseAddress);
1111
1112 /*
1113 * This operation is currently only available on relocatable images.
1114 */
1115 switch (pModElf->Ehdr.e_type)
1116 {
1117 case ET_REL:
1118 case ET_DYN:
1119 break;
1120 case ET_EXEC:
1121 Log(("RTLdrELF: %s: Executable images are not supported yet!\n", pszLogName));
1122 return VERR_LDRELF_EXEC;
1123 default: AssertFailedReturn(VERR_BAD_EXE_FORMAT);
1124 }
1125
1126 /*
1127 * Validate the input.
1128 */
1129 Elf_Addr BaseAddr = (Elf_Addr)NewBaseAddress;
1130 AssertMsgReturn((RTUINTPTR)BaseAddr == NewBaseAddress, ("%RTptr", NewBaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
1131
1132 /*
1133 * Map the image bits if not already done and setup pointer into it.
1134 */
1135 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1136 if (RT_FAILURE(rc))
1137 return rc;
1138
1139 /*
1140 * Iterate the sections looking for interesting SHT_REL[A] sections.
1141 *
1142 * In ET_REL files the SHT_REL[A] sections have the section index of
1143 * the section they contain fixups for in the sh_info member.
1144 */
1145 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1146 Log2(("rtLdrElf: %s: Fixing up image\n", pszLogName));
1147 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1148 {
1149 const Elf_Shdr *pShdrRel = &paShdrs[iShdr];
1150
1151 /*
1152 * Skip sections without interest to us.
1153 */
1154#if ELF_MODE == 32
1155 if (pShdrRel->sh_type != SHT_REL)
1156#else
1157 if (pShdrRel->sh_type != SHT_RELA)
1158#endif
1159 continue;
1160 if (pModElf->Ehdr.e_type == ET_REL)
1161 {
1162 if (pShdrRel->sh_info >= pModElf->Ehdr.e_shnum)
1163 continue;
1164 const Elf_Shdr *pShdr = &paShdrs[pShdrRel->sh_info]; /* the section to fixup. */
1165 if (!(pShdr->sh_flags & SHF_ALLOC))
1166 continue;
1167
1168 /*
1169 * Relocate the section.
1170 */
1171 Log2(("rtldrELF: %s: Relocation records for #%d [%s] (sh_info=%d sh_link=%d) found in #%d [%s] (sh_info=%d sh_link=%d)\n",
1172 pszLogName, (int)pShdrRel->sh_info, ELF_SH_STR(pModElf, pShdr->sh_name), (int)pShdr->sh_info, (int)pShdr->sh_link,
1173 iShdr, ELF_SH_STR(pModElf, pShdrRel->sh_name), (int)pShdrRel->sh_info, (int)pShdrRel->sh_link));
1174
1175 rc = RTLDRELF_NAME(RelocateSectionRel)(pModElf, BaseAddr, pfnGetImport, pvUser,
1176 pShdr->sh_addr,
1177 pShdr->sh_size,
1178 (const uint8_t *)pModElf->pvBits + pShdr->sh_offset,
1179 (uint8_t *)pvBits + pShdr->sh_addr,
1180 (const uint8_t *)pModElf->pvBits + pShdrRel->sh_offset,
1181 pShdrRel->sh_size);
1182 }
1183 else
1184 rc = RTLDRELF_NAME(RelocateSectionExecDyn)(pModElf, BaseAddr, pfnGetImport, pvUser,
1185 0, (Elf_Size)pModElf->cbImage,
1186 (const uint8_t *)pModElf->pvBits /** @todo file offset ?? */,
1187 (uint8_t *)pvBits,
1188 (const uint8_t *)pModElf->pvBits + pShdrRel->sh_offset,
1189 pShdrRel->sh_size);
1190
1191 if (RT_FAILURE(rc))
1192 return rc;
1193 }
1194 return VINF_SUCCESS;
1195}
1196
1197
1198/**
1199 * Worker for pfnGetSymbolEx.
1200 */
1201static int RTLDRELF_NAME(ReturnSymbol)(PRTLDRMODELF pThis, const Elf_Sym *pSym, Elf_Addr uBaseAddr, PRTUINTPTR pValue)
1202{
1203 Elf_Addr Value;
1204 if (pSym->st_shndx == SHN_ABS)
1205 /* absolute symbols are not subject to any relocation. */
1206 Value = pSym->st_value;
1207 else if (pSym->st_shndx < pThis->Ehdr.e_shnum)
1208 {
1209 if (pThis->Ehdr.e_type == ET_REL)
1210 /* relative to the section. */
1211 Value = uBaseAddr + pSym->st_value + pThis->paShdrs[pSym->st_shndx].sh_addr;
1212 else /* Fixed up for link address. */
1213 Value = uBaseAddr + pSym->st_value - pThis->LinkAddress;
1214 }
1215 else
1216 {
1217 AssertMsgFailed(("Arg! pSym->st_shndx=%d\n", pSym->st_shndx));
1218 return VERR_BAD_EXE_FORMAT;
1219 }
1220 AssertMsgReturn(Value == (RTUINTPTR)Value, (FMT_ELF_ADDR "\n", Value), VERR_SYMBOL_VALUE_TOO_BIG);
1221 *pValue = (RTUINTPTR)Value;
1222 return VINF_SUCCESS;
1223}
1224
1225
1226/** @copydoc RTLDROPS::pfnGetSymbolEx */
1227static DECLCALLBACK(int) RTLDRELF_NAME(GetSymbolEx)(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress,
1228 uint32_t iOrdinal, const char *pszSymbol, RTUINTPTR *pValue)
1229{
1230 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1231 NOREF(pvBits);
1232
1233 /*
1234 * Validate the input.
1235 */
1236 Elf_Addr uBaseAddr = (Elf_Addr)BaseAddress;
1237 AssertMsgReturn((RTUINTPTR)uBaseAddr == BaseAddress, ("%RTptr", BaseAddress), VERR_IMAGE_BASE_TOO_HIGH);
1238
1239 /*
1240 * Map the image bits if not already done and setup pointer into it.
1241 */
1242 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1243 if (RT_FAILURE(rc))
1244 return rc;
1245
1246 /*
1247 * Calc all kinds of pointers before we start iterating the symbol table.
1248 */
1249 const Elf_Sym *paSyms = pModElf->Rel.paSyms;
1250 unsigned cSyms = pModElf->Rel.cSyms;
1251 const char *pszzStr = pModElf->Rel.pStr;
1252 unsigned cbStr = pModElf->Rel.cbStr;
1253 if (pModElf->Dyn.cSyms > 0)
1254 {
1255 paSyms = pModElf->Dyn.paSyms;
1256 cSyms = pModElf->Dyn.cSyms;
1257 pszzStr = pModElf->Dyn.pStr;
1258 cbStr = pModElf->Dyn.cbStr;
1259 }
1260
1261 if (iOrdinal == UINT32_MAX)
1262 {
1263 for (unsigned iSym = 1; iSym < cSyms; iSym++)
1264 {
1265 /* Undefined symbols are not exports, they are imports. */
1266 if ( paSyms[iSym].st_shndx != SHN_UNDEF
1267 && ( ELF_ST_BIND(paSyms[iSym].st_info) == STB_GLOBAL
1268 || ELF_ST_BIND(paSyms[iSym].st_info) == STB_WEAK))
1269 {
1270 /* Validate the name string and try match with it. */
1271 AssertMsgReturn(paSyms[iSym].st_name < cbStr,
1272 ("String outside string table! iSym=%d paSyms[iSym].st_name=%#x\n", iSym, paSyms[iSym].st_name),
1273 VERR_LDRELF_INVALID_SYMBOL_NAME_OFFSET);
1274 if (!strcmp(pszSymbol, pszzStr + paSyms[iSym].st_name))
1275 {
1276 /* matched! */
1277 return RTLDRELF_NAME(ReturnSymbol)(pModElf, &paSyms[iSym], uBaseAddr, pValue);
1278 }
1279 }
1280 }
1281 }
1282 else if (iOrdinal < cSyms)
1283 {
1284 if ( paSyms[iOrdinal].st_shndx != SHN_UNDEF
1285 && ( ELF_ST_BIND(paSyms[iOrdinal].st_info) == STB_GLOBAL
1286 || ELF_ST_BIND(paSyms[iOrdinal].st_info) == STB_WEAK))
1287 return RTLDRELF_NAME(ReturnSymbol)(pModElf, &paSyms[iOrdinal], uBaseAddr, pValue);
1288 }
1289
1290 return VERR_SYMBOL_NOT_FOUND;
1291}
1292
1293
1294/** @copydoc RTLDROPS::pfnEnumDbgInfo */
1295static DECLCALLBACK(int) RTLDRELF_NAME(EnumDbgInfo)(PRTLDRMODINTERNAL pMod, const void *pvBits,
1296 PFNRTLDRENUMDBG pfnCallback, void *pvUser)
1297{
1298 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1299 RT_NOREF_PV(pvBits);
1300
1301 /*
1302 * Map the image bits if not already done and setup pointer into it.
1303 */
1304 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1305 if (RT_FAILURE(rc))
1306 return rc;
1307
1308 /*
1309 * Do the enumeration.
1310 */
1311 const Elf_Shdr *paShdrs = pModElf->paOrgShdrs;
1312 for (unsigned iShdr = 0; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1313 {
1314 /* Debug sections are expected to be PROGBITS and not allocated. */
1315 if (paShdrs[iShdr].sh_type != SHT_PROGBITS)
1316 continue;
1317 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1318 continue;
1319
1320 RTLDRDBGINFO DbgInfo;
1321 const char *pszSectName = ELF_SH_STR(pModElf, paShdrs[iShdr].sh_name);
1322 if ( !strncmp(pszSectName, RT_STR_TUPLE(".debug_"))
1323 || !strcmp(pszSectName, ".WATCOM_references") )
1324 {
1325 RT_ZERO(DbgInfo.u);
1326 DbgInfo.enmType = RTLDRDBGINFOTYPE_DWARF;
1327 DbgInfo.pszExtFile = NULL;
1328 DbgInfo.offFile = paShdrs[iShdr].sh_offset;
1329 DbgInfo.cb = paShdrs[iShdr].sh_size;
1330 DbgInfo.u.Dwarf.pszSection = pszSectName;
1331 }
1332 else if (!strcmp(pszSectName, ".gnu_debuglink"))
1333 {
1334 if ((paShdrs[iShdr].sh_size & 3) || paShdrs[iShdr].sh_size < 8)
1335 return VERR_BAD_EXE_FORMAT;
1336
1337 RT_ZERO(DbgInfo.u);
1338 DbgInfo.enmType = RTLDRDBGINFOTYPE_DWARF_DWO;
1339 DbgInfo.pszExtFile = (const char *)((uintptr_t)pModElf->pvBits + (uintptr_t)paShdrs[iShdr].sh_offset);
1340 if (!RTStrEnd(DbgInfo.pszExtFile, paShdrs[iShdr].sh_size))
1341 return VERR_BAD_EXE_FORMAT;
1342 DbgInfo.u.Dwo.uCrc32 = *(uint32_t *)((uintptr_t)DbgInfo.pszExtFile + (uintptr_t)paShdrs[iShdr].sh_size
1343 - sizeof(uint32_t));
1344 DbgInfo.offFile = -1;
1345 DbgInfo.cb = 0;
1346 }
1347 else
1348 continue;
1349
1350 DbgInfo.LinkAddress = NIL_RTLDRADDR;
1351 DbgInfo.iDbgInfo = iShdr - 1;
1352
1353 rc = pfnCallback(pMod, &DbgInfo, pvUser);
1354 if (rc != VINF_SUCCESS)
1355 return rc;
1356
1357 }
1358
1359 return VINF_SUCCESS;
1360}
1361
1362
1363/**
1364 * Locate the next allocated section by RVA (sh_addr).
1365 *
1366 * This is a helper for EnumSegments and SegOffsetToRva.
1367 *
1368 * @returns Pointer to the section header if found, NULL if none.
1369 * @param pModElf The module instance.
1370 * @param iShdrCur The current section header.
1371 */
1372static const Elf_Shdr *RTLDRELF_NAME(GetNextAllocatedSection)(PRTLDRMODELF pModElf, unsigned iShdrCur)
1373{
1374 unsigned const cShdrs = pModElf->Ehdr.e_shnum;
1375 const Elf_Shdr * const paShdrs = pModElf->paShdrs;
1376 if (pModElf->fShdrInOrder)
1377 {
1378 for (unsigned iShdr = iShdrCur + 1; iShdr < cShdrs; iShdr++)
1379 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1380 return &paShdrs[iShdr];
1381 }
1382 else
1383 {
1384 Elf_Addr const uEndCur = paShdrs[iShdrCur].sh_addr + paShdrs[iShdrCur].sh_size;
1385 Elf_Addr offBest = ~(Elf_Addr)0;
1386 unsigned iBest = cShdrs;
1387 for (unsigned iShdr = pModElf->iFirstSect; iShdr < cShdrs; iShdr++)
1388 if ((paShdrs[iShdr].sh_flags & SHF_ALLOC) && iShdr != iShdrCur)
1389 {
1390 Elf_Addr const offDelta = paShdrs[iShdr].sh_addr - uEndCur;
1391 if ( offDelta < offBest
1392 && paShdrs[iShdr].sh_addr >= uEndCur)
1393 {
1394 offBest = offDelta;
1395 iBest = iShdr;
1396 }
1397 }
1398 if (iBest < cShdrs)
1399 return &paShdrs[iBest];
1400 }
1401 return NULL;
1402}
1403
1404
1405/** @copydoc RTLDROPS::pfnEnumSegments. */
1406static DECLCALLBACK(int) RTLDRELF_NAME(EnumSegments)(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
1407{
1408 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1409
1410 /*
1411 * Map the image bits if not already done and setup pointer into it.
1412 */
1413 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1414 if (RT_FAILURE(rc))
1415 return rc;
1416
1417 /*
1418 * Do the enumeration.
1419 */
1420 char szName[32];
1421 Elf_Addr uPrevMappedRva = 0;
1422 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1423 const Elf_Shdr *paOrgShdrs = pModElf->paOrgShdrs;
1424 for (unsigned iShdr = pModElf->iFirstSect; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1425 {
1426 RTLDRSEG Seg;
1427 if (iShdr != 0)
1428 {
1429 Seg.pszName = ELF_SH_STR(pModElf, paShdrs[iShdr].sh_name);
1430 Seg.cchName = (uint32_t)strlen(Seg.pszName);
1431 if (Seg.cchName == 0)
1432 {
1433 Seg.pszName = szName;
1434 Seg.cchName = (uint32_t)RTStrPrintf(szName, sizeof(szName), "UnamedSect%02u", iShdr);
1435 }
1436 }
1437 else
1438 {
1439 Seg.pszName = ".elf.headers";
1440 Seg.cchName = 12;
1441 }
1442 Seg.SelFlat = 0;
1443 Seg.Sel16bit = 0;
1444 Seg.fFlags = 0;
1445 Seg.fProt = RTMEM_PROT_READ;
1446 if (paShdrs[iShdr].sh_flags & SHF_WRITE)
1447 Seg.fProt |= RTMEM_PROT_WRITE;
1448 if (paShdrs[iShdr].sh_flags & SHF_EXECINSTR)
1449 Seg.fProt |= RTMEM_PROT_EXEC;
1450 Seg.cb = paShdrs[iShdr].sh_size;
1451 Seg.Alignment = paShdrs[iShdr].sh_addralign;
1452 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1453 {
1454 Seg.LinkAddress = paOrgShdrs[iShdr].sh_addr;
1455 Seg.RVA = paShdrs[iShdr].sh_addr;
1456 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetNextAllocatedSection)(pModElf, iShdr);
1457 if (pShdr2)
1458 Seg.cbMapped = pShdr2->sh_addr - paShdrs[iShdr].sh_addr;
1459 else
1460 Seg.cbMapped = pModElf->cbImage - paShdrs[iShdr].sh_addr;
1461 uPrevMappedRva = Seg.RVA;
1462 }
1463 else
1464 {
1465 Seg.LinkAddress = NIL_RTLDRADDR;
1466 Seg.RVA = NIL_RTLDRADDR;
1467 Seg.cbMapped = NIL_RTLDRADDR;
1468 }
1469 if (paShdrs[iShdr].sh_type != SHT_NOBITS)
1470 {
1471 Seg.offFile = paShdrs[iShdr].sh_offset;
1472 Seg.cbFile = paShdrs[iShdr].sh_size;
1473 }
1474 else
1475 {
1476 Seg.offFile = -1;
1477 Seg.cbFile = 0;
1478 }
1479
1480 rc = pfnCallback(pMod, &Seg, pvUser);
1481 if (rc != VINF_SUCCESS)
1482 return rc;
1483 }
1484
1485 return VINF_SUCCESS;
1486}
1487
1488
1489/** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */
1490static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress,
1491 uint32_t *piSeg, PRTLDRADDR poffSeg)
1492{
1493 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1494
1495 const Elf_Shdr *pShdrEnd = NULL;
1496 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1497 const Elf_Shdr *pShdr = &pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
1498 while (cLeft-- > 0)
1499 {
1500 pShdr--;
1501 if (pShdr->sh_flags & SHF_ALLOC)
1502 {
1503 RTLDRADDR offSeg = LinkAddress - pShdr->sh_addr;
1504 if (offSeg < pShdr->sh_size)
1505 {
1506 *poffSeg = offSeg;
1507 *piSeg = cLeft;
1508 return VINF_SUCCESS;
1509 }
1510 if (offSeg == pShdr->sh_size)
1511 pShdrEnd = pShdr;
1512 }
1513 }
1514
1515 if (pShdrEnd)
1516 {
1517 *poffSeg = pShdrEnd->sh_size;
1518 *piSeg = pShdrEnd - pModElf->paOrgShdrs - pModElf->iFirstSect;
1519 return VINF_SUCCESS;
1520 }
1521
1522 return VERR_LDR_INVALID_LINK_ADDRESS;
1523}
1524
1525
1526/** @copydoc RTLDROPS::pfnLinkAddressToRva. */
1527static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToRva)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva)
1528{
1529 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1530 uint32_t iSeg;
1531 RTLDRADDR offSeg;
1532 int rc = RTLDRELF_NAME(LinkAddressToSegOffset)(pMod, LinkAddress, &iSeg, &offSeg);
1533 if (RT_SUCCESS(rc))
1534 *pRva = pModElf->paShdrs[iSeg + pModElf->iFirstSect].sh_addr + offSeg;
1535 return rc;
1536}
1537
1538
1539/** @copydoc RTLDROPS::pfnSegOffsetToRva. */
1540static DECLCALLBACK(int) RTLDRELF_NAME(SegOffsetToRva)(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg,
1541 PRTLDRADDR pRva)
1542{
1543 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1544 if (iSeg >= pModElf->Ehdr.e_shnum - pModElf->iFirstSect)
1545 return VERR_LDR_INVALID_SEG_OFFSET;
1546
1547 iSeg += pModElf->iFirstSect; /* skip section 0 if not used */
1548 if (offSeg > pModElf->paShdrs[iSeg].sh_size)
1549 {
1550 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetNextAllocatedSection)(pModElf, iSeg);
1551 if ( !pShdr2
1552 || offSeg > (pShdr2->sh_addr - pModElf->paShdrs[iSeg].sh_addr))
1553 return VERR_LDR_INVALID_SEG_OFFSET;
1554 }
1555
1556 if (!(pModElf->paShdrs[iSeg].sh_flags & SHF_ALLOC))
1557 return VERR_LDR_INVALID_SEG_OFFSET;
1558
1559 *pRva = pModElf->paShdrs[iSeg].sh_addr;
1560 return VINF_SUCCESS;
1561}
1562
1563
1564/** @copydoc RTLDROPS::pfnRvaToSegOffset. */
1565static DECLCALLBACK(int) RTLDRELF_NAME(RvaToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva,
1566 uint32_t *piSeg, PRTLDRADDR poffSeg)
1567{
1568 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1569 Elf_Addr PrevAddr = 0;
1570 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1571 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->Ehdr.e_shnum];
1572 while (cLeft-- > 0)
1573 {
1574 pShdr--;
1575 if (pShdr->sh_flags & SHF_ALLOC)
1576 {
1577 Elf_Addr cbSeg = PrevAddr ? PrevAddr - pShdr->sh_addr : pShdr->sh_size;
1578 RTLDRADDR offSeg = Rva - pShdr->sh_addr;
1579 if (offSeg <= cbSeg)
1580 {
1581 *poffSeg = offSeg;
1582 *piSeg = cLeft;
1583 return VINF_SUCCESS;
1584 }
1585 PrevAddr = pShdr->sh_addr;
1586 }
1587 }
1588
1589 return VERR_LDR_INVALID_RVA;
1590}
1591
1592
1593/** @callback_method_impl{FNRTLDRIMPORT, Stub used by ReadDbgInfo.} */
1594static DECLCALLBACK(int) RTLDRELF_NAME(GetImportStubCallback)(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol,
1595 unsigned uSymbol, PRTLDRADDR pValue, void *pvUser)
1596{
1597 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(pszModule); RT_NOREF_PV(pszSymbol);
1598 RT_NOREF_PV(uSymbol); RT_NOREF_PV(pValue); RT_NOREF_PV(pvUser);
1599 return VERR_SYMBOL_NOT_FOUND;
1600}
1601
1602
1603/** @copydoc RTLDROPS::pfnReadDbgInfo. */
1604static DECLCALLBACK(int) RTLDRELF_NAME(ReadDbgInfo)(PRTLDRMODINTERNAL pMod, uint32_t iDbgInfo, RTFOFF off,
1605 size_t cb, void *pvBuf)
1606{
1607 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1608 LogFlow(("%s: iDbgInfo=%#x off=%RTfoff cb=%#zu\n", __FUNCTION__, iDbgInfo, off, cb));
1609
1610 /*
1611 * Input validation.
1612 */
1613 AssertReturn(iDbgInfo < pThis->Ehdr.e_shnum && iDbgInfo + 1 < pThis->Ehdr.e_shnum, VERR_INVALID_PARAMETER);
1614 iDbgInfo++;
1615 AssertReturn(!(pThis->paShdrs[iDbgInfo].sh_flags & SHF_ALLOC), VERR_INVALID_PARAMETER);
1616 AssertReturn(pThis->paShdrs[iDbgInfo].sh_type == SHT_PROGBITS, VERR_INVALID_PARAMETER);
1617 AssertReturn(pThis->paShdrs[iDbgInfo].sh_offset == (uint64_t)off, VERR_INVALID_PARAMETER);
1618 AssertReturn(pThis->paShdrs[iDbgInfo].sh_size == cb, VERR_INVALID_PARAMETER);
1619 uint64_t cbRawImage = pThis->Core.pReader->pfnSize(pThis->Core.pReader);
1620 AssertReturn(off >= 0 && cb <= cbRawImage && (uint64_t)off + cb <= cbRawImage, VERR_INVALID_PARAMETER);
1621
1622 /*
1623 * Read it from the file and look for fixup sections.
1624 */
1625 int rc;
1626 if (pThis->pvBits)
1627 memcpy(pvBuf, (const uint8_t *)pThis->pvBits + (size_t)off, cb);
1628 else
1629 {
1630 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pvBuf, cb, off);
1631 if (RT_FAILURE(rc))
1632 return rc;
1633 }
1634
1635 uint32_t iRelocs = iDbgInfo + 1;
1636 if ( iRelocs >= pThis->Ehdr.e_shnum
1637 || pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1638 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1639 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA) )
1640 {
1641 iRelocs = 0;
1642 while ( iRelocs < pThis->Ehdr.e_shnum
1643 && ( pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1644 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1645 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA)) )
1646 iRelocs++;
1647 }
1648 if ( iRelocs < pThis->Ehdr.e_shnum
1649 && pThis->paShdrs[iRelocs].sh_size > 0)
1650 {
1651 /*
1652 * Load the relocations.
1653 */
1654 uint8_t *pbRelocsBuf = NULL;
1655 const uint8_t *pbRelocs;
1656 if (pThis->pvBits)
1657 pbRelocs = (const uint8_t *)pThis->pvBits + pThis->paShdrs[iRelocs].sh_offset;
1658 else
1659 {
1660 pbRelocs = pbRelocsBuf = (uint8_t *)RTMemTmpAlloc(pThis->paShdrs[iRelocs].sh_size);
1661 if (!pbRelocsBuf)
1662 return VERR_NO_TMP_MEMORY;
1663 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pbRelocsBuf,
1664 pThis->paShdrs[iRelocs].sh_size,
1665 pThis->paShdrs[iRelocs].sh_offset);
1666 if (RT_FAILURE(rc))
1667 {
1668 RTMemTmpFree(pbRelocsBuf);
1669 return rc;
1670 }
1671 }
1672
1673 /*
1674 * Apply the relocations.
1675 */
1676 if (pThis->Ehdr.e_type == ET_REL)
1677 rc = RTLDRELF_NAME(RelocateSectionRel)(pThis, pThis->LinkAddress,
1678 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1679 pThis->paShdrs[iDbgInfo].sh_addr,
1680 pThis->paShdrs[iDbgInfo].sh_size,
1681 (const uint8_t *)pvBuf,
1682 (uint8_t *)pvBuf,
1683 pbRelocs,
1684 pThis->paShdrs[iRelocs].sh_size);
1685 else
1686 rc = RTLDRELF_NAME(RelocateSectionExecDyn)(pThis, pThis->LinkAddress,
1687 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1688 pThis->paShdrs[iDbgInfo].sh_addr,
1689 pThis->paShdrs[iDbgInfo].sh_size,
1690 (const uint8_t *)pvBuf,
1691 (uint8_t *)pvBuf,
1692 pbRelocs,
1693 pThis->paShdrs[iRelocs].sh_size);
1694
1695 RTMemTmpFree(pbRelocsBuf);
1696 }
1697 else
1698 rc = VINF_SUCCESS;
1699 return rc;
1700}
1701
1702
1703/**
1704 * @interface_method_impl{RTLDROPS,pfnUnwindFrame}
1705 */
1706static DECLCALLBACK(int)
1707RTLDRELF_NAME(UnwindFrame)(PRTLDRMODINTERNAL pMod, void const *pvBits, uint32_t iSeg, RTUINTPTR off, PRTDBGUNWINDSTATE pState)
1708{
1709 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1710 LogFlow(("%s: iSeg=%#x off=%RTptr\n", __FUNCTION__, iSeg, off));
1711
1712 /*
1713 * Process the input address, making us both RVA and proper seg:offset out of it.
1714 */
1715 int rc;
1716 RTLDRADDR uRva = off;
1717 if (iSeg == UINT32_MAX)
1718 rc = RTLDRELF_NAME(RvaToSegOffset)(pMod, uRva, &iSeg, &off);
1719 else
1720 rc = RTLDRELF_NAME(SegOffsetToRva)(pMod, iSeg, off, &uRva);
1721 AssertRCReturn(rc, rc);
1722
1723 /*
1724 * Map the image bits if not already done and setup pointer into it.
1725 */
1726 RT_NOREF(pvBits); /** @todo Try use passed in pvBits? */
1727 rc = RTLDRELF_NAME(MapBits)(pThis, true);
1728 if (RT_FAILURE(rc))
1729 return rc;
1730
1731 /*
1732 * Do we need to search for .eh_frame and .eh_frame_hdr?
1733 */
1734 if (pThis->iShEhFrame == 0)
1735 {
1736 pThis->iShEhFrame = ~0U;
1737 pThis->iShEhFrameHdr = ~0U;
1738 unsigned cLeft = 2;
1739 for (unsigned iShdr = 1; iShdr < pThis->Ehdr.e_shnum; iShdr++)
1740 {
1741 const char *pszName = ELF_SH_STR(pThis, pThis->paShdrs[iShdr].sh_name);
1742 if ( pszName[0] == '.'
1743 && pszName[1] == 'e'
1744 && pszName[2] == 'h'
1745 && pszName[3] == '_'
1746 && pszName[4] == 'f'
1747 && pszName[5] == 'r'
1748 && pszName[6] == 'a'
1749 && pszName[7] == 'm'
1750 && pszName[8] == 'e')
1751 {
1752 if (pszName[9] == '\0')
1753 pThis->iShEhFrame = iShdr;
1754 else if ( pszName[9] == '_'
1755 && pszName[10] == 'h'
1756 && pszName[11] == 'd'
1757 && pszName[12] == 'r'
1758 && pszName[13] == '\0')
1759 pThis->iShEhFrameHdr = iShdr;
1760 else
1761 continue;
1762 if (--cLeft == 0)
1763 break;
1764 }
1765 }
1766 }
1767
1768 /*
1769 * Any info present?
1770 */
1771 unsigned iShdr = pThis->iShEhFrame;
1772 if ( iShdr != ~0U
1773 && pThis->paShdrs[iShdr].sh_size > 0)
1774 {
1775 if (pThis->paShdrs[iShdr].sh_flags & SHF_ALLOC)
1776 return rtDwarfUnwind_EhData((uint8_t const *)pThis->pvBits + pThis->paShdrs[iShdr].sh_addr,
1777 pThis->paShdrs[iShdr].sh_size, pThis->paShdrs[iShdr].sh_addr,
1778 iSeg, off, uRva, pState, pThis->Core.enmArch);
1779 }
1780 return VERR_DBG_NO_UNWIND_INFO;
1781}
1782
1783
1784/**
1785 * The ELF module operations.
1786 */
1787static RTLDROPS RTLDRELF_MID(s_rtldrElf,Ops) =
1788{
1789#if ELF_MODE == 32
1790 "elf32",
1791#elif ELF_MODE == 64
1792 "elf64",
1793#endif
1794 RTLDRELF_NAME(Close),
1795 NULL, /* Get Symbol */
1796 RTLDRELF_NAME(Done),
1797 RTLDRELF_NAME(EnumSymbols),
1798 /* ext: */
1799 RTLDRELF_NAME(GetImageSize),
1800 RTLDRELF_NAME(GetBits),
1801 RTLDRELF_NAME(Relocate),
1802 RTLDRELF_NAME(GetSymbolEx),
1803 NULL /*pfnQueryForwarderInfo*/,
1804 RTLDRELF_NAME(EnumDbgInfo),
1805 RTLDRELF_NAME(EnumSegments),
1806 RTLDRELF_NAME(LinkAddressToSegOffset),
1807 RTLDRELF_NAME(LinkAddressToRva),
1808 RTLDRELF_NAME(SegOffsetToRva),
1809 RTLDRELF_NAME(RvaToSegOffset),
1810 RTLDRELF_NAME(ReadDbgInfo),
1811 NULL /*pfnQueryProp*/,
1812 NULL /*pfnVerifySignature*/,
1813 NULL /*pfnHashImage*/,
1814 RTLDRELF_NAME(UnwindFrame),
1815 42
1816};
1817
1818
1819
1820/**
1821 * Validates the ELF header.
1822 *
1823 * @returns iprt status code.
1824 * @param pEhdr Pointer to the ELF header.
1825 * @param cbRawImage The size of the raw image.
1826 * @param pszLogName The log name.
1827 * @param penmArch Where to return the architecture.
1828 * @param pErrInfo Where to return extended error info. Optional.
1829 */
1830static int RTLDRELF_NAME(ValidateElfHeader)(const Elf_Ehdr *pEhdr, uint64_t cbRawImage, const char *pszLogName,
1831 PRTLDRARCH penmArch, PRTERRINFO pErrInfo)
1832{
1833 Log3(("RTLdrELF: e_ident: %.*Rhxs\n"
1834 "RTLdrELF: e_type: " FMT_ELF_HALF "\n"
1835 "RTLdrELF: e_version: " FMT_ELF_HALF "\n"
1836 "RTLdrELF: e_entry: " FMT_ELF_ADDR "\n"
1837 "RTLdrELF: e_phoff: " FMT_ELF_OFF "\n"
1838 "RTLdrELF: e_shoff: " FMT_ELF_OFF "\n"
1839 "RTLdrELF: e_flags: " FMT_ELF_WORD "\n"
1840 "RTLdrELF: e_ehsize: " FMT_ELF_HALF "\n"
1841 "RTLdrELF: e_phentsize: " FMT_ELF_HALF "\n"
1842 "RTLdrELF: e_phnum: " FMT_ELF_HALF "\n"
1843 "RTLdrELF: e_shentsize: " FMT_ELF_HALF "\n"
1844 "RTLdrELF: e_shnum: " FMT_ELF_HALF "\n"
1845 "RTLdrELF: e_shstrndx: " FMT_ELF_HALF "\n",
1846 RT_ELEMENTS(pEhdr->e_ident), &pEhdr->e_ident[0], pEhdr->e_type, pEhdr->e_version,
1847 pEhdr->e_entry, pEhdr->e_phoff, pEhdr->e_shoff,pEhdr->e_flags, pEhdr->e_ehsize, pEhdr->e_phentsize,
1848 pEhdr->e_phnum, pEhdr->e_shentsize, pEhdr->e_shnum, pEhdr->e_shstrndx));
1849
1850 if ( pEhdr->e_ident[EI_MAG0] != ELFMAG0
1851 || pEhdr->e_ident[EI_MAG1] != ELFMAG1
1852 || pEhdr->e_ident[EI_MAG2] != ELFMAG2
1853 || pEhdr->e_ident[EI_MAG3] != ELFMAG3)
1854 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1855 "%s: Invalid ELF magic (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1856 if (pEhdr->e_ident[EI_CLASS] != RTLDRELF_SUFF(ELFCLASS))
1857 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1858 "%s: Invalid ELF class (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1859 if (pEhdr->e_ident[EI_DATA] != ELFDATA2LSB)
1860 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_ODD_ENDIAN,
1861 "%s: ELF endian %x is unsupported", pszLogName, pEhdr->e_ident[EI_DATA]);
1862 if (pEhdr->e_version != EV_CURRENT)
1863 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_VERSION,
1864 "%s: ELF version %x is unsupported", pszLogName, pEhdr->e_version);
1865
1866 if (sizeof(Elf_Ehdr) != pEhdr->e_ehsize)
1867 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1868 "%s: Elf header e_ehsize is %d expected %d!", pszLogName, pEhdr->e_ehsize, sizeof(Elf_Ehdr));
1869 if ( sizeof(Elf_Phdr) != pEhdr->e_phentsize
1870 && ( pEhdr->e_phnum != 0
1871 || pEhdr->e_type == ET_DYN
1872 || pEhdr->e_type == ET_EXEC))
1873 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_phentsize is %d expected %d!",
1874 pszLogName, pEhdr->e_phentsize, sizeof(Elf_Phdr));
1875 if (sizeof(Elf_Shdr) != pEhdr->e_shentsize)
1876 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_shentsize is %d expected %d!",
1877 pszLogName, pEhdr->e_shentsize, sizeof(Elf_Shdr));
1878
1879 switch (pEhdr->e_type)
1880 {
1881 case ET_REL:
1882 case ET_EXEC:
1883 case ET_DYN:
1884 break;
1885 default:
1886 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: image type %#x is not supported!",
1887 pszLogName, pEhdr->e_type);
1888 }
1889
1890 switch (pEhdr->e_machine)
1891 {
1892#if ELF_MODE == 32
1893 case EM_386:
1894 case EM_486:
1895 *penmArch = RTLDRARCH_X86_32;
1896 break;
1897#elif ELF_MODE == 64
1898 case EM_X86_64:
1899 *penmArch = RTLDRARCH_AMD64;
1900 break;
1901#endif
1902 default:
1903 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MACHINE,
1904 "%s: machine type %u is not supported!", pszLogName, pEhdr->e_machine);
1905 }
1906
1907 if ( pEhdr->e_phoff < pEhdr->e_ehsize
1908 && !(pEhdr->e_phoff && pEhdr->e_phnum)
1909 && pEhdr->e_phnum)
1910 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1911 "%s: The program headers overlap with the ELF header! e_phoff=" FMT_ELF_OFF,
1912 pszLogName, pEhdr->e_phoff);
1913 if ( pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize > cbRawImage
1914 || pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize < pEhdr->e_phoff)
1915 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1916 "%s: The program headers extends beyond the file! e_phoff=" FMT_ELF_OFF " e_phnum=" FMT_ELF_HALF,
1917 pszLogName, pEhdr->e_phoff, pEhdr->e_phnum);
1918
1919
1920 if ( pEhdr->e_shoff < pEhdr->e_ehsize
1921 && !(pEhdr->e_shoff && pEhdr->e_shnum))
1922 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1923 "%s: The section headers overlap with the ELF header! e_shoff=" FMT_ELF_OFF,
1924 pszLogName, pEhdr->e_shoff);
1925 if ( pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize > cbRawImage
1926 || pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize < pEhdr->e_shoff)
1927 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1928 "%s: The section headers extends beyond the file! e_shoff=" FMT_ELF_OFF " e_shnum=" FMT_ELF_HALF,
1929 pszLogName, pEhdr->e_shoff, pEhdr->e_shnum);
1930
1931 if (pEhdr->e_shstrndx == 0 || pEhdr->e_shstrndx > pEhdr->e_shnum)
1932 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1933 "%s: The section headers string table is out of bounds! e_shstrndx=" FMT_ELF_HALF " e_shnum=" FMT_ELF_HALF,
1934 pszLogName, pEhdr->e_shstrndx, pEhdr->e_shnum);
1935
1936 return VINF_SUCCESS;
1937}
1938
1939
1940/**
1941 * Gets the section header name.
1942 *
1943 * @returns pszName.
1944 * @param pEhdr The elf header.
1945 * @param offName The offset of the section header name.
1946 * @param pszName Where to store the name.
1947 * @param cbName The size of the buffer pointed to by pszName.
1948 */
1949const char *RTLDRELF_NAME(GetSHdrName)(PRTLDRMODELF pModElf, Elf_Word offName, char *pszName, size_t cbName)
1950{
1951 RTFOFF off = pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_offset + offName;
1952 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName, cbName - 1, off);
1953 if (RT_FAILURE(rc))
1954 {
1955 /* read by for byte. */
1956 for (unsigned i = 0; i < cbName; i++, off++)
1957 {
1958 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName + i, 1, off);
1959 if (RT_FAILURE(rc))
1960 {
1961 pszName[i] = '\0';
1962 break;
1963 }
1964 }
1965 }
1966
1967 pszName[cbName - 1] = '\0';
1968 return pszName;
1969}
1970
1971
1972/**
1973 * Validates a section header.
1974 *
1975 * @returns iprt status code.
1976 * @param pModElf Pointer to the module structure.
1977 * @param iShdr The index of section header which should be validated.
1978 * The section headers are found in the pModElf->paShdrs array.
1979 * @param cbRawImage The size of the raw image.
1980 * @param pszLogName The log name.
1981 * @param pErrInfo Where to return extended error info. Optional.
1982 */
1983static int RTLDRELF_NAME(ValidateSectionHeader)(PRTLDRMODELF pModElf, unsigned iShdr, uint64_t cbRawImage,
1984 const char *pszLogName, PRTERRINFO pErrInfo)
1985{
1986 const Elf_Shdr *pShdr = &pModElf->paShdrs[iShdr];
1987 char szSectionName[80]; NOREF(szSectionName);
1988 Log3(("RTLdrELF: Section Header #%d:\n"
1989 "RTLdrELF: sh_name: " FMT_ELF_WORD " - %s\n"
1990 "RTLdrELF: sh_type: " FMT_ELF_WORD " (%s)\n"
1991 "RTLdrELF: sh_flags: " FMT_ELF_XWORD "\n"
1992 "RTLdrELF: sh_addr: " FMT_ELF_ADDR "\n"
1993 "RTLdrELF: sh_offset: " FMT_ELF_OFF "\n"
1994 "RTLdrELF: sh_size: " FMT_ELF_XWORD "\n"
1995 "RTLdrELF: sh_link: " FMT_ELF_WORD "\n"
1996 "RTLdrELF: sh_info: " FMT_ELF_WORD "\n"
1997 "RTLdrELF: sh_addralign: " FMT_ELF_XWORD "\n"
1998 "RTLdrELF: sh_entsize: " FMT_ELF_XWORD "\n",
1999 iShdr,
2000 pShdr->sh_name, RTLDRELF_NAME(GetSHdrName)(pModElf, pShdr->sh_name, szSectionName, sizeof(szSectionName)),
2001 pShdr->sh_type, rtldrElfGetShdrType(pShdr->sh_type), pShdr->sh_flags, pShdr->sh_addr,
2002 pShdr->sh_offset, pShdr->sh_size, pShdr->sh_link, pShdr->sh_info, pShdr->sh_addralign,
2003 pShdr->sh_entsize));
2004
2005 if (iShdr == 0)
2006 {
2007 if ( pShdr->sh_name != 0
2008 || pShdr->sh_type != SHT_NULL
2009 || pShdr->sh_flags != 0
2010 || pShdr->sh_addr != 0
2011 || pShdr->sh_size != 0
2012 || pShdr->sh_offset != 0
2013 || pShdr->sh_link != SHN_UNDEF
2014 || pShdr->sh_addralign != 0
2015 || pShdr->sh_entsize != 0 )
2016 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2017 "%s: Bad #0 section: %.*Rhxs", pszLogName, sizeof(*pShdr), pShdr);
2018 return VINF_SUCCESS;
2019 }
2020
2021 if (pShdr->sh_name >= pModElf->cbShStr)
2022 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2023 "%s: Shdr #%d: sh_name (%d) is beyond the end of the section header string table (%d)!",
2024 pszLogName, iShdr, pShdr->sh_name, pModElf->cbShStr);
2025
2026 if (pShdr->sh_link >= pModElf->Ehdr.e_shnum)
2027 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2028 "%s: Shdr #%d: sh_link (%d) is beyond the end of the section table (%d)!",
2029 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2030
2031 switch (pShdr->sh_type)
2032 {
2033 /** @todo find specs and check up which sh_info fields indicates section table entries */
2034 case 12301230:
2035 if (pShdr->sh_info >= pModElf->Ehdr.e_shnum)
2036 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2037 "%s: Shdr #%d: sh_info (%d) is beyond the end of the section table (%d)!",
2038 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2039 break;
2040
2041 case SHT_NULL:
2042 break;
2043 case SHT_PROGBITS:
2044 case SHT_SYMTAB:
2045 case SHT_STRTAB:
2046 case SHT_RELA:
2047 case SHT_HASH:
2048 case SHT_DYNAMIC:
2049 case SHT_NOTE:
2050 case SHT_NOBITS:
2051 case SHT_REL:
2052 case SHT_SHLIB:
2053 case SHT_DYNSYM:
2054 /*
2055 * For these types sh_info doesn't have any special meaning, or anything which
2056 * we need/can validate now.
2057 */
2058 break;
2059
2060
2061 default:
2062 Log(("RTLdrELF: %s: Warning, unknown type %d!\n", pszLogName, pShdr->sh_type));
2063 break;
2064 }
2065
2066 if ( pShdr->sh_type != SHT_NOBITS
2067 && pShdr->sh_size)
2068 {
2069 uint64_t offEnd = pShdr->sh_offset + pShdr->sh_size;
2070 if ( offEnd > cbRawImage
2071 || offEnd < (uint64_t)pShdr->sh_offset)
2072 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2073 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD " = %RX64) is beyond the end of the file (%RX64)!",
2074 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size, offEnd, cbRawImage);
2075 if (pShdr->sh_offset < sizeof(Elf_Ehdr))
2076 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2077 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD ") is starting in the ELF header!",
2078 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size);
2079 }
2080
2081 return VINF_SUCCESS;
2082}
2083
2084
2085/**
2086 * Process the section headers.
2087 *
2088 * @returns iprt status code.
2089 * @param pModElf Pointer to the module structure.
2090 * @param paShdrs The section headers.
2091 * @param cbRawImage The size of the raw image.
2092 * @param pszLogName The log name.
2093 * @param pErrInfo Where to return extended error info. Optional.
2094 */
2095static int RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(PRTLDRMODELF pModElf, Elf_Shdr *paShdrs, uint64_t cbRawImage,
2096 const char *pszLogName, PRTERRINFO pErrInfo)
2097{
2098 Elf_Addr uNextAddr = 0;
2099 for (unsigned i = 0; i < pModElf->Ehdr.e_shnum; i++)
2100 {
2101 int rc = RTLDRELF_NAME(ValidateSectionHeader)(pModElf, i, cbRawImage, pszLogName, pErrInfo);
2102 if (RT_FAILURE(rc))
2103 return rc;
2104
2105 /*
2106 * We're looking for symbol tables.
2107 */
2108 if (paShdrs[i].sh_type == SHT_SYMTAB)
2109 {
2110 if (pModElf->Rel.iSymSh != ~0U)
2111 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2112 "%s: Multiple symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Rel.iSymSh, i);
2113 pModElf->Rel.iSymSh = i;
2114 pModElf->Rel.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2115 AssertBreakStmt(pModElf->Rel.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2116 pModElf->Rel.iStrSh = paShdrs[i].sh_link;
2117 pModElf->Rel.cbStr = (unsigned)paShdrs[pModElf->Rel.iStrSh].sh_size;
2118 AssertBreakStmt(pModElf->Rel.cbStr == paShdrs[pModElf->Rel.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2119 }
2120 else if (paShdrs[i].sh_type == SHT_DYNSYM)
2121 {
2122 if (pModElf->Dyn.iSymSh != ~0U)
2123 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2124 "%s: Multiple dynamic symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Dyn.iSymSh, i);
2125 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2126 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2127 "%s: Unexpected SHT_DYNSYM (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2128 pModElf->Dyn.iSymSh = i;
2129 pModElf->Dyn.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2130 AssertBreakStmt(pModElf->Dyn.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2131 pModElf->Dyn.iStrSh = paShdrs[i].sh_link;
2132 pModElf->Dyn.cbStr = (unsigned)paShdrs[pModElf->Dyn.iStrSh].sh_size;
2133 AssertBreakStmt(pModElf->Dyn.cbStr == paShdrs[pModElf->Dyn.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2134 }
2135 /*
2136 * We're also look for the dynamic section.
2137 */
2138 else if (paShdrs[i].sh_type == SHT_DYNAMIC)
2139 {
2140 if (pModElf->iShDynamic != ~0U)
2141 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2142 "%s: Multiple dynamic sections! iShDynamic=%d i=%d",
2143 pszLogName, pModElf->iShDynamic, i);
2144 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2145 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2146 "%s: Unexpected SHT_DYNAMIC (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2147 if (paShdrs[i].sh_entsize != sizeof(Elf_Dyn))
2148 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2149 "%s: SHT_DYNAMIC (i=%d) sh_entsize=" FMT_ELF_XWORD ", expected %#zx",
2150 pszLogName, i, paShdrs[i].sh_entsize, sizeof(Elf_Dyn));
2151 pModElf->iShDynamic = i;
2152 Elf_Xword const cDynamic = paShdrs[i].sh_size / sizeof(Elf_Dyn);
2153 if (cDynamic > _64K || cDynamic < 2)
2154 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2155 "%s: SHT_DYNAMIC (i=%d) sh_size=" FMT_ELF_XWORD " is out of range (2..64K)",
2156 pszLogName, i, paShdrs[i].sh_size);
2157 pModElf->cDynamic = (unsigned)cDynamic;
2158 }
2159
2160 /*
2161 * Special checks for the section string table.
2162 */
2163 if (i == pModElf->Ehdr.e_shstrndx)
2164 {
2165 if (paShdrs[i].sh_type != SHT_STRTAB)
2166 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2167 "%s: Section header string table is not a SHT_STRTAB: %#x",
2168 pszLogName, paShdrs[i].sh_type);
2169 if (paShdrs[i].sh_size == 0)
2170 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Section header string table is empty", pszLogName);
2171 }
2172
2173 /*
2174 * Kluge for the .data..percpu segment in 64-bit linux kernels.
2175 */
2176 if (paShdrs[i].sh_flags & SHF_ALLOC)
2177 {
2178 if ( paShdrs[i].sh_addr == 0
2179 && paShdrs[i].sh_addr < uNextAddr)
2180 {
2181 Elf_Addr uAddr = RT_ALIGN_T(uNextAddr, paShdrs[i].sh_addralign, Elf_Addr);
2182 Log(("RTLdrElf: Out of order section #%d; adjusting sh_addr from " FMT_ELF_ADDR " to " FMT_ELF_ADDR "\n",
2183 i, paShdrs[i].sh_addr, uAddr));
2184 paShdrs[i].sh_addr = uAddr;
2185 }
2186 uNextAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2187 }
2188 } /* for each section header */
2189
2190 return VINF_SUCCESS;
2191}
2192
2193
2194/**
2195 * Process the section headers.
2196 *
2197 * @returns iprt status code.
2198 * @param pModElf Pointer to the module structure.
2199 * @param paShdrs The section headers.
2200 * @param cbRawImage The size of the raw image.
2201 * @param pszLogName The log name.
2202 * @param pErrInfo Where to return extended error info. Optional.
2203 */
2204static int RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(PRTLDRMODELF pModElf, uint64_t cbRawImage, uint32_t fFlags,
2205 const char *pszLogName, PRTERRINFO pErrInfo)
2206{
2207 /*
2208 * Check preconditions.
2209 */
2210 AssertReturn(pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC, VERR_INTERNAL_ERROR_2);
2211 if (pModElf->Ehdr.e_phnum <= 1 || pModElf->Ehdr.e_phnum >= _32K)
2212 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2213 "%s: e_phnum=%u is out of bounds (2..32K)", pszLogName, pModElf->Ehdr.e_phnum);
2214 if (pModElf->iShDynamic == ~0U)
2215 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: no .dynamic section", pszLogName);
2216 AssertReturn(pModElf->cDynamic > 1 && pModElf->cDynamic <= _64K, VERR_INTERNAL_ERROR_3);
2217
2218 /* ASSUME that the sections are ordered by address. That simplifies
2219 validation code further down. */
2220 AssertReturn(pModElf->Ehdr.e_shnum >= 2, VERR_INTERNAL_ERROR_4);
2221 Elf_Shdr const *paShdrs = pModElf->paShdrs;
2222 Elf_Addr uPrevEnd = paShdrs[1].sh_addr + paShdrs[1].sh_size;
2223 for (unsigned i = 2; i < pModElf->Ehdr.e_shnum; i++)
2224 if (paShdrs[i].sh_flags & SHF_ALLOC)
2225 {
2226 if (uPrevEnd > paShdrs[i].sh_addr)
2227 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2228 "%s: section %u is out of order: uPrevEnd=" FMT_ELF_ADDR " sh_addr=" FMT_ELF_ADDR,
2229 pszLogName, i, uPrevEnd, paShdrs[i].sh_addr);
2230 uPrevEnd = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2231 }
2232
2233 /* Must have string and symbol tables. */
2234 if (pModElf->Dyn.iStrSh == ~0U)
2235 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic string table section", pszLogName);
2236 if (pModElf->Dyn.iSymSh == ~0U)
2237 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic symbol table section", pszLogName);
2238
2239 /*
2240 * Load the program headers.
2241 */
2242 size_t const cbPhdrs = sizeof(pModElf->paPhdrs[0]) * pModElf->Ehdr.e_phnum;
2243 Elf_Phdr *paPhdrs = (Elf_Phdr *)RTMemAllocZ(cbPhdrs);
2244 pModElf->paPhdrs = paPhdrs;
2245 AssertReturn(paPhdrs, VERR_NO_MEMORY);
2246
2247 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paPhdrs, cbPhdrs, pModElf->Ehdr.e_phoff);
2248 if (RT_FAILURE(rc))
2249 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2250 pszLogName, cbPhdrs, pModElf->Ehdr.e_phoff, rc);
2251
2252 /*
2253 * Validate them.
2254 */
2255 unsigned cbPage = _4K; /** @todo generalize architecture specific stuff using its own code template header. */
2256 switch (pModElf->Core.enmArch)
2257 {
2258 case RTLDRARCH_AMD64:
2259 case RTLDRARCH_X86_32:
2260 break;
2261 default:
2262 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2263 }
2264 unsigned iLoad = 0;
2265 unsigned iLoadShdr = 1; /* ASSUMES ordered (checked above). */
2266 unsigned cDynamic = 0;
2267 Elf_Addr cbImage = 0;
2268 Elf_Addr uLinkAddress = ~(Elf_Addr)0;
2269 for (unsigned i = 0; i < pModElf->Ehdr.e_phnum; i++)
2270 {
2271 const Elf_Phdr * const pPhdr = &paPhdrs[i];
2272 Log3(("RTLdrELF: Program Header #%d:\n"
2273 "RTLdrELF: p_type: " FMT_ELF_WORD " (%s)\n"
2274 "RTLdrELF: p_flags: " FMT_ELF_WORD "\n"
2275 "RTLdrELF: p_offset: " FMT_ELF_OFF "\n"
2276 "RTLdrELF: p_vaddr: " FMT_ELF_ADDR "\n"
2277 "RTLdrELF: p_paddr: " FMT_ELF_ADDR "\n"
2278 "RTLdrELF: p_filesz: " FMT_ELF_XWORD "\n"
2279 "RTLdrELF: p_memsz: " FMT_ELF_XWORD "\n"
2280 "RTLdrELF: p_align: " FMT_ELF_XWORD "\n",
2281 i,
2282 pPhdr->p_type, rtldrElfGetPhdrType(pPhdr->p_type), pPhdr->p_flags, pPhdr->p_offset,
2283 pPhdr->p_vaddr, pPhdr->p_paddr, pPhdr->p_filesz, pPhdr->p_memsz, pPhdr->p_align));
2284
2285 if (pPhdr->p_type == DT_NULL)
2286 continue;
2287
2288 if ( pPhdr->p_filesz != 0
2289 && ( pPhdr->p_offset >= cbRawImage
2290 || pPhdr->p_filesz > cbRawImage
2291 || pPhdr->p_offset + pPhdr->p_filesz > cbRawImage))
2292 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2293 "%s: Prog Hdr #%u: bogus p_offset=" FMT_ELF_OFF " & p_filesz=" FMT_ELF_XWORD " (file size %#RX64)",
2294 pszLogName, i, pPhdr->p_offset, pPhdr->p_filesz, cbRawImage);
2295
2296 if (pPhdr->p_flags & ~(Elf64_Word)(PF_X | PF_R | PF_W))
2297 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_flags=" FMT_ELF_WORD,
2298 pszLogName, i, pPhdr->p_flags);
2299
2300 if (!RT_IS_POWER_OF_TWO(pPhdr->p_align))
2301 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_align=" FMT_ELF_XWORD,
2302 pszLogName, i, pPhdr->p_align);
2303
2304 if ( pPhdr->p_align > 1
2305 && pPhdr->p_memsz > 0
2306 && pPhdr->p_filesz > 0
2307 && (pPhdr->p_offset & (pPhdr->p_align - 1)) != (pPhdr->p_vaddr & (pPhdr->p_align - 1)))
2308 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2309 "%s: Prog Hdr #%u: misaligned p_offset=" FMT_ELF_OFF " p_vaddr=" FMT_ELF_ADDR " p_align=" FMT_ELF_XWORD,
2310 pszLogName, i, pPhdr->p_offset, pPhdr->p_vaddr, pPhdr->p_align);
2311
2312 /* Do some type specfic checks: */
2313 switch (pPhdr->p_type)
2314 {
2315 case PT_LOAD:
2316 {
2317 if (pPhdr->p_memsz < pPhdr->p_filesz)
2318 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2319 "%s: Prog Hdr #%u/LOAD#%u: bogus p_memsz=" FMT_ELF_XWORD " or p_filesz=" FMT_ELF_XWORD,
2320 pszLogName, i, iLoad, pPhdr->p_memsz, pPhdr->p_filesz);
2321 cbImage = pPhdr->p_vaddr + pPhdr->p_memsz;
2322 if (iLoad == 0)
2323 uLinkAddress = pPhdr->p_vaddr;
2324
2325 /* Find the corresponding sections, checking their addresses and
2326 file offsets since the rest of the code is still section based
2327 rather than using program headers as it should... */
2328 Elf_Off off = pPhdr->p_offset;
2329 Elf_Addr uAddr = pPhdr->p_vaddr;
2330 Elf_Xword cbMem = pPhdr->p_memsz;
2331 Elf_Xword cbFile = pPhdr->p_filesz;
2332 while (cbMem > 0)
2333 {
2334 if (iLoadShdr < pModElf->Ehdr.e_shnum)
2335 { /* likely */ }
2336 else if (iLoadShdr == pModElf->Ehdr.e_shnum)
2337 {
2338 /** @todo anything else to check here? */
2339 iLoadShdr++;
2340 break;
2341 }
2342 else
2343 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2344 "%s: Prog Hdr #%u/LOAD#%u: Out of sections at " FMT_ELF_ADDR " LB " FMT_ELF_XWORD,
2345 pszLogName, i, iLoad, uAddr, cbMem);
2346 if (!(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC))
2347 {
2348 if ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2349 && paShdrs[iLoadShdr].sh_size > 0
2350 && off < paShdrs[iLoadShdr].sh_offset + paShdrs[iLoadShdr].sh_size
2351 && paShdrs[iLoadShdr].sh_offset < off + cbMem)
2352 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2353 "%s: Prog Hdr #%u/LOAD#%u: Overlaps with !SHF_ALLOC section at " FMT_ELF_OFF " LB " FMT_ELF_XWORD,
2354 pszLogName, i, iLoad, paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_size);
2355 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2356 iLoadShdr++;
2357 continue;
2358 }
2359
2360 if (uAddr != paShdrs[iLoadShdr].sh_addr)
2361 {
2362 /* Before the first section we expect headers to be loaded, so
2363 that the file is simply mapped from file offset zero. */
2364 if ( iLoadShdr == 1
2365 && iLoad == 0
2366 && paShdrs[1].sh_addr == paShdrs[1].sh_offset
2367 && cbFile >= paShdrs[1].sh_offset
2368 && cbMem >= paShdrs[1].sh_offset)
2369 {
2370 /* Modify paShdrs[0] to describe the gap. ".elf.headers" */
2371 pModElf->iFirstSect = 0;
2372 pModElf->paShdrs[0].sh_name = 0;
2373 pModElf->paShdrs[0].sh_type = SHT_PROGBITS;
2374 pModElf->paShdrs[0].sh_flags = SHF_ALLOC
2375 | (pPhdr->p_flags & PF_W ? SHF_WRITE : 0)
2376 | (pPhdr->p_flags & PF_X ? SHF_EXECINSTR : 0);
2377 pModElf->paShdrs[0].sh_addr = uAddr;
2378 pModElf->paShdrs[0].sh_offset = off;
2379 pModElf->paShdrs[0].sh_size = paShdrs[1].sh_offset;
2380 pModElf->paShdrs[0].sh_link = 0;
2381 pModElf->paShdrs[0].sh_info = 0;
2382 pModElf->paShdrs[0].sh_addralign = pPhdr->p_align;
2383 pModElf->paShdrs[0].sh_entsize = 0;
2384 *(Elf_Shdr *)pModElf->paOrgShdrs = pModElf->paShdrs[0]; /* (necessary for segment enumeration) */
2385
2386 uAddr += paShdrs[1].sh_offset;
2387 cbMem -= paShdrs[1].sh_offset;
2388 cbFile -= paShdrs[1].sh_offset;
2389 off = paShdrs[1].sh_offset;
2390 }
2391 /* Alignment padding? Allow up to a page size. */
2392 else if ( paShdrs[iLoadShdr].sh_addr > uAddr
2393 && paShdrs[iLoadShdr].sh_addr - uAddr
2394 < RT_MAX(paShdrs[iLoadShdr].sh_addralign, cbPage /*got.plt hack*/))
2395 {
2396 Elf_Xword cbAlignPadding = paShdrs[iLoadShdr].sh_addr - uAddr;
2397 if (cbAlignPadding >= cbMem)
2398 break;
2399 cbMem -= cbAlignPadding;
2400 uAddr += cbAlignPadding;
2401 if (cbFile > cbAlignPadding)
2402 {
2403 off += cbAlignPadding;
2404 cbFile -= cbAlignPadding;
2405 }
2406 else
2407 {
2408 off += cbFile;
2409 cbFile = 0;
2410 }
2411 }
2412 }
2413
2414 if ( uAddr == paShdrs[iLoadShdr].sh_addr
2415 && cbMem >= paShdrs[iLoadShdr].sh_size
2416 && ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2417 ? off == paShdrs[iLoadShdr].sh_offset
2418 && cbFile >= paShdrs[iLoadShdr].sh_size /* this might be too strict... */
2419 : cbFile == 0) )
2420 {
2421 if (paShdrs[iLoadShdr].sh_type != SHT_NOBITS)
2422 {
2423 off += paShdrs[iLoadShdr].sh_size;
2424 cbFile -= paShdrs[iLoadShdr].sh_size;
2425 }
2426 uAddr += paShdrs[iLoadShdr].sh_size;
2427 cbMem -= paShdrs[iLoadShdr].sh_size;
2428 }
2429 else
2430 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2431 "%s: Prog Hdr #%u/LOAD#%u: Mismatch at " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " LB " FMT_ELF_XWORD ") with section #%u " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " sh_type=" FMT_ELF_WORD ")",
2432 pszLogName, i, iLoad, uAddr, cbMem, off, cbFile,
2433 iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2434 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2435
2436 pModElf->paShdrExtras[iLoadShdr].idxPhdr = iLoad;
2437 iLoadShdr++;
2438 } /* section loop */
2439
2440 iLoad++;
2441 break;
2442 }
2443
2444 case PT_DYNAMIC:
2445 {
2446 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->iShDynamic];
2447 if (pPhdr->p_offset != pShdr->sh_offset)
2448 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2449 "%s: Prog Hdr #%u/DYNAMIC: p_offset=" FMT_ELF_OFF " expected " FMT_ELF_OFF,
2450 pszLogName, i, pPhdr->p_offset, pShdr->sh_offset);
2451 if (RT_MAX(pPhdr->p_memsz, pPhdr->p_filesz) != pShdr->sh_size)
2452 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2453 "%s: Prog Hdr #%u/DYNAMIC: expected " FMT_ELF_XWORD " for RT_MAX(p_memsz=" FMT_ELF_XWORD ", p_filesz=" FMT_ELF_XWORD ")",
2454 pszLogName, i, pShdr->sh_size, pPhdr->p_memsz, pPhdr->p_filesz);
2455 cDynamic++;
2456 break;
2457 }
2458 }
2459 }
2460
2461 if (iLoad == 0)
2462 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No PT_LOAD program headers", pszLogName);
2463 if (cDynamic != 1)
2464 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No program header for the DYNAMIC section", pszLogName);
2465
2466 cbImage -= uLinkAddress;
2467 pModElf->cbImage = (uint64_t)cbImage;
2468 pModElf->LinkAddress = uLinkAddress;
2469 AssertReturn(pModElf->cbImage == cbImage, VERR_INTERNAL_ERROR_5);
2470 Log3(("RTLdrELF: LinkAddress=" FMT_ELF_ADDR " cbImage=" FMT_ELF_ADDR " (from PT_LOAD)\n", uLinkAddress, cbImage));
2471
2472 for (; iLoadShdr < pModElf->Ehdr.e_shnum; iLoadShdr++)
2473 if ( !(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC)
2474 || paShdrs[iLoadShdr].sh_size == 0)
2475 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2476 else
2477 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2478 "%s: No PT_LOAD for section #%u " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " sh_type=" FMT_ELF_WORD ")",
2479 pszLogName, iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2480 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2481
2482 /*
2483 * Load and validate the dynamic table. We have got / will get most of the
2484 * info we need from the section table, so we must make sure this matches up.
2485 */
2486 Log3(("RTLdrELF: Dynamic section - %u entries\n", pModElf->cDynamic));
2487 size_t const cbDynamic = pModElf->cDynamic * sizeof(pModElf->paDynamic[0]);
2488 Elf_Dyn * const paDynamic = (Elf_Dyn *)RTMemAlloc(cbDynamic);
2489 AssertReturn(paDynamic, VERR_NO_MEMORY);
2490 pModElf->paDynamic = paDynamic;
2491
2492 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paDynamic, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset);
2493 if (RT_FAILURE(rc))
2494 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2495 pszLogName, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset, rc);
2496
2497 for (uint32_t i = 0; i < pModElf->cDynamic; i++)
2498 {
2499#define LOG_VALIDATE_PTR_RET(szName) do { \
2500 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, paDynamic[i].d_un.d_ptr)); \
2501 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress < cbImage) { /* likely */ } \
2502 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": Invalid address " FMT_ELF_ADDR " (valid range: " FMT_ELF_ADDR " LB " FMT_ELF_ADDR ")", \
2503 pszLogName, i, paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage); \
2504 } while (0)
2505#define LOG_VALIDATE_PTR_VAL_RET(szName, uExpected) do { \
2506 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, (uint64_t)paDynamic[i].d_un.d_ptr)); \
2507 if (paDynamic[i].d_un.d_ptr == (Elf_Addr)(uExpected)) { /* likely */ } \
2508 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": " FMT_ELF_ADDR ", expected " FMT_ELF_ADDR, \
2509 pszLogName, i, paDynamic[i].d_un.d_ptr, (Elf_Addr)(uExpected)); \
2510 } while (0)
2511#define LOG_VALIDATE_STR_RET(szName) do { \
2512 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2513 if ((uint64_t)paDynamic[i].d_un.d_val < pModElf->Dyn.cbStr) { /* likely */ } \
2514 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": Invalid string table offset %#RX64 (max %#x)", \
2515 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, pModElf->Dyn.cbStr); \
2516 } while (0)
2517#define LOG_VALIDATE_VAL_RET(szName, uExpected) do { \
2518 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2519 if ((uint64_t)paDynamic[i].d_un.d_val == (uint64_t)(uExpected)) { /* likely */ } \
2520 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": %#RX64, expected %#RX64", \
2521 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, (uint64_t)(uExpected)); \
2522 } while (0)
2523#define SET_RELOC_TYPE_RET(a_szName, a_uType) do { \
2524 if (pModElf->DynInfo.uRelocType == 0 || pModElf->DynInfo.uRelocType == (a_uType)) \
2525 pModElf->DynInfo.uRelocType = (a_uType); \
2526 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Mixing DT_RELA and DT_REL", pszLogName, i); \
2527 } while (0)
2528#define SET_INFO_FIELD_RET(a_szName, a_Field, a_Value, a_UnsetValue, a_szFmt) do { \
2529 if ((a_Field) == (a_UnsetValue) && (a_Value) != (a_UnsetValue)) \
2530 (a_Field) = (a_Value); /* likely */ \
2531 else if ((a_Field) != (a_UnsetValue)) \
2532 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Multiple entries (first value " a_szFmt ", second " a_szFmt ")", pszLogName, i, (a_Field), (a_Value)); \
2533 else if ((a_Value) != (a_UnsetValue)) \
2534 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Unexpected value " a_szFmt, pszLogName, i, (a_Value)); \
2535 } while (0)
2536#define FIND_MATCHING_SECTION_RET(a_szName, a_ExtraMatchExpr, a_idxShFieldToSet) do { \
2537 unsigned iSh; \
2538 for (iSh = 1; iSh < pModElf->Ehdr.e_shnum; iSh++) \
2539 if ( paShdrs[iSh].sh_addr == paDynamic[i].d_un.d_ptr \
2540 && (a_ExtraMatchExpr)) \
2541 { \
2542 (a_idxShFieldToSet) = iSh; \
2543 if (pModElf->paShdrExtras[iSh].idxDt != UINT16_MAX) \
2544 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, \
2545 "%s: DT[%u]/" a_szName ": section #%u (" FMT_ELF_ADDR ") already referenced by DT[%u]", \
2546 pszLogName, i, iSh, paShdrs[iSh].sh_addr, pModElf->paShdrExtras[iSh].idxDt); \
2547 pModElf->paShdrExtras[iSh].idxDt = i; \
2548 pModElf->paShdrExtras[iSh].uDtTag = (uint32_t)paDynamic[i].d_tag; \
2549 break; \
2550 } \
2551 if (iSh < pModElf->Ehdr.e_shnum) { /* likely */ } \
2552 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": No matching section for " FMT_ELF_ADDR, pszLogName, i, paDynamic[i].d_un.d_ptr); \
2553 } while (0)
2554#define ONLY_FOR_DEBUG_OR_VALIDATION_RET(a_szName) do { \
2555 if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)) { /* likely */ } \
2556 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Not supported (" FMT_ELF_ADDR ")", pszLogName, i, paDynamic[i].d_un.d_ptr); \
2557 } while (0)
2558#define LOG_NON_VALUE_ENTRY(a_szName) Log3(("RTLdrELF: DT[%u]: %16s (%#RX64)\n", i, a_szName, (uint64_t)paDynamic[i].d_un.d_val))
2559
2560 switch (paDynamic[i].d_tag)
2561 {
2562 case DT_NULL:
2563 LOG_NON_VALUE_ENTRY("DT_NULL");
2564 for (unsigned iNull = i + 1; iNull < pModElf->cDynamic; iNull++)
2565 if (paDynamic[i].d_tag == DT_NULL) /* Not technically a bug, but let's try being extremely strict for now */
2566 LOG_NON_VALUE_ENTRY("DT_NULL");
2567 else if (!(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
2568 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2569 "%s: DT[%u]/DT_NULL: Dynamic section isn't zero padded (extra #%u of #%u)",
2570 pszLogName, i, iNull - i, pModElf->cDynamic - i);
2571 i = pModElf->cDynamic;
2572 break;
2573 case DT_NEEDED:
2574 LOG_VALIDATE_STR_RET("DT_NEEDED");
2575 break;
2576 case DT_PLTRELSZ:
2577 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PLTRELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2578 SET_INFO_FIELD_RET("DT_PLTRELSZ", pModElf->DynInfo.cbJmpRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2579 break;
2580 case DT_PLTGOT:
2581 LOG_VALIDATE_PTR_RET("DT_PLTGOT");
2582 break;
2583 case DT_HASH:
2584 LOG_VALIDATE_PTR_RET("DT_HASH");
2585 break;
2586 case DT_STRTAB:
2587 LOG_VALIDATE_PTR_VAL_RET("DT_STRTAB", paShdrs[pModElf->Dyn.iStrSh].sh_addr);
2588 pModElf->paShdrExtras[pModElf->Dyn.iStrSh].idxDt = i;
2589 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_STRTAB;
2590 break;
2591 case DT_SYMTAB:
2592 LOG_VALIDATE_PTR_VAL_RET("DT_SYMTAB", paShdrs[pModElf->Dyn.iSymSh].sh_addr);
2593 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].idxDt = i;
2594 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_SYMTAB;
2595 break;
2596 case DT_RELA:
2597 LOG_VALIDATE_PTR_RET("DT_RELA");
2598 SET_RELOC_TYPE_RET("DT_RELA", DT_RELA);
2599 SET_INFO_FIELD_RET("DT_RELA", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2600 FIND_MATCHING_SECTION_RET("DT_RELA", paShdrs[iSh].sh_type == SHT_RELA, pModElf->DynInfo.idxShRelocs);
2601 break;
2602 case DT_RELASZ:
2603 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELASZ", (uint64_t)paDynamic[i].d_un.d_val));
2604 SET_RELOC_TYPE_RET("DT_RELASZ", DT_RELA);
2605 SET_INFO_FIELD_RET("DT_RELASZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2606 break;
2607 case DT_RELAENT:
2608 LOG_VALIDATE_VAL_RET("DT_RELAENT", sizeof(Elf_Rela));
2609 SET_RELOC_TYPE_RET("DT_RELAENT", DT_RELA);
2610 SET_INFO_FIELD_RET("DT_RELAENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rela), 0, "%u");
2611 break;
2612 case DT_STRSZ:
2613 LOG_VALIDATE_VAL_RET("DT_STRSZ", pModElf->Dyn.cbStr);
2614 break;
2615 case DT_SYMENT:
2616 LOG_VALIDATE_VAL_RET("DT_SYMENT", sizeof(Elf_Sym));
2617 break;
2618 case DT_INIT:
2619 LOG_VALIDATE_PTR_RET("DT_INIT");
2620 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT");
2621 break;
2622 case DT_FINI:
2623 LOG_VALIDATE_PTR_RET("DT_FINI");
2624 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI");
2625 break;
2626 case DT_SONAME:
2627 LOG_VALIDATE_STR_RET("DT_SONAME");
2628 break;
2629 case DT_RPATH:
2630 LOG_VALIDATE_STR_RET("DT_RPATH");
2631 break;
2632 case DT_SYMBOLIC:
2633 LOG_NON_VALUE_ENTRY("DT_SYMBOLIC");
2634 break;
2635 case DT_REL:
2636 LOG_VALIDATE_PTR_RET("DT_REL");
2637 SET_RELOC_TYPE_RET("DT_REL", DT_REL);
2638 SET_INFO_FIELD_RET("DT_REL", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2639 FIND_MATCHING_SECTION_RET("DT_REL", paShdrs[iSh].sh_type == SHT_REL, pModElf->DynInfo.idxShRelocs);
2640 break;
2641 case DT_RELSZ:
2642 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2643 SET_RELOC_TYPE_RET("DT_RELSZ", DT_REL);
2644 SET_INFO_FIELD_RET("DT_RELSZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2645 break;
2646 case DT_RELENT:
2647 LOG_VALIDATE_VAL_RET("DT_RELENT", sizeof(Elf_Rel));
2648 SET_RELOC_TYPE_RET("DT_RELENT", DT_REL);
2649 SET_INFO_FIELD_RET("DT_RELENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rel), 0, "%u");
2650 break;
2651 case DT_PLTREL:
2652 if (paDynamic[i].d_un.d_val != DT_RELA && paDynamic[i].d_un.d_val != DT_REL)
2653 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/DT_PLTREL: Invalid value %#RX64",
2654 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val);
2655 Log3(("RTLdrELF: DT[%u]: %16s DT_REL%s\n", i, "DT_PLTREL", paDynamic[i].d_un.d_val == DT_RELA ? "A" : ""));
2656 SET_INFO_FIELD_RET("DT_PLTREL", pModElf->DynInfo.uJmpRelocType, (unsigned)paDynamic[i].d_un.d_val, 0, "%u");
2657 break;
2658 case DT_DEBUG:
2659 LOG_VALIDATE_PTR_RET("DT_DEBUG");
2660 break;
2661 case DT_TEXTREL:
2662 LOG_NON_VALUE_ENTRY("DT_TEXTREL");
2663 break;
2664 case DT_JMPREL:
2665 LOG_VALIDATE_PTR_RET("DT_JMPREL");
2666 SET_INFO_FIELD_RET("DT_JMPREL", pModElf->DynInfo.uPtrJmpRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2667 FIND_MATCHING_SECTION_RET("DT_JMPREL", 1, pModElf->DynInfo.idxShJmpRelocs);
2668 break;
2669 case DT_BIND_NOW:
2670 LOG_NON_VALUE_ENTRY("DT_BIND_NOW");
2671 break;
2672 case DT_INIT_ARRAY:
2673 LOG_VALIDATE_PTR_RET("DT_INIT_ARRAY");
2674 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAY");
2675 break;
2676 case DT_FINI_ARRAY:
2677 LOG_VALIDATE_PTR_RET("DT_FINI_ARRAY");
2678 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAY");
2679 break;
2680 case DT_INIT_ARRAYSZ:
2681 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_INIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2682 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAYSZ");
2683 break;
2684 case DT_FINI_ARRAYSZ:
2685 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_FINI_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2686 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAYSZ");
2687 break;
2688 case DT_RUNPATH:
2689 LOG_VALIDATE_STR_RET("DT_RUNPATH");
2690 break;
2691 case DT_FLAGS:
2692 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, "DT_FLAGS", (uint64_t)paDynamic[i].d_un.d_val));
2693 break;
2694 case DT_PREINIT_ARRAY:
2695 LOG_VALIDATE_PTR_RET("DT_PREINIT_ARRAY");
2696 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAY");
2697 break;
2698 case DT_PREINIT_ARRAYSZ:
2699 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PREINIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2700 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAYSZ");
2701 break;
2702 default:
2703 if ( paDynamic[i].d_un.d_val < DT_ENCODING
2704 || (paDynamic[i].d_un.d_val & 1))
2705 Log3(("RTLdrELF: DT[%u]: %#010RX64 %#RX64%s\n", i, (uint64_t)paDynamic[i].d_tag,
2706 (uint64_t)paDynamic[i].d_un.d_val, paDynamic[i].d_un.d_val >= DT_ENCODING ? " (val)" : ""));
2707 else
2708 {
2709 Log3(("RTLdrELF: DT[%u]: %#010RX64 " FMT_ELF_ADDR " (addr)\n",
2710 i, (uint64_t)paDynamic[i].d_tag, paDynamic[i].d_un.d_ptr));
2711 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress >= cbImage)
2712 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2713 "%s: DT[%u]/%#RX64: Invalid address " FMT_ELF_ADDR " (valid range: " FMT_ELF_ADDR " LB " FMT_ELF_ADDR ")",
2714 pszLogName, i, (uint64_t)paDynamic[i].d_tag,
2715 paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage);
2716 }
2717 break;
2718 }
2719#undef LOG_VALIDATE_VAL_RET
2720#undef LOG_VALIDATE_STR_RET
2721#undef LOG_VALIDATE_PTR_VAL_RET
2722#undef LOG_VALIDATE_PTR_RET
2723#undef SET_RELOC_TYPE_RET
2724#undef SET_INFO_FIELD_RET
2725#undef FIND_MATCHING_SECTION_RET
2726#undef ONLY_FOR_DEBUG_OR_VALIDATION_RET
2727 }
2728
2729 /*
2730 * Validate the relocation information we've gathered.
2731 */
2732 Elf_Word uShTypeArch = SHT_RELA; /** @todo generalize architecture specific stuff using its own code template header. */
2733 switch (pModElf->Core.enmArch)
2734 {
2735 case RTLDRARCH_AMD64:
2736 break;
2737 case RTLDRARCH_X86_32:
2738 uShTypeArch = SHT_REL;
2739 break;
2740 default:
2741 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2742
2743 }
2744
2745 if (pModElf->DynInfo.uRelocType != 0)
2746 {
2747 const char * const pszModifier = pModElf->DynInfo.uRelocType == DT_RELA ? "A" : "";
2748 if (pModElf->DynInfo.uPtrRelocs == ~(Elf_Addr)0)
2749 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%s", pszLogName, pszModifier);
2750 if (pModElf->DynInfo.cbRelocs == 0)
2751 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sSZ", pszLogName, pszModifier);
2752 if (pModElf->DynInfo.cbRelocEntry == 0)
2753 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sENT", pszLogName, pszModifier);
2754 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShRelocs];
2755 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2756 if (pShdrRelocs->sh_type != uShType)
2757 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match section type: %u vs %u",
2758 pszLogName, pszModifier, pShdrRelocs->sh_type, uShType);
2759 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbRelocs)
2760 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%sSZ does not match section size: %u vs %u",
2761 pszLogName, pszModifier, pShdrRelocs->sh_size, pModElf->DynInfo.cbRelocs);
2762 if (uShType != uShTypeArch)
2763 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match architecture: %u, arch wants %u",
2764 pszLogName, pszModifier, uShType, uShTypeArch);
2765 }
2766
2767 if ( pModElf->DynInfo.uPtrJmpRelocs != ~(Elf_Addr)0
2768 || pModElf->DynInfo.cbJmpRelocs != 0
2769 || pModElf->DynInfo.uJmpRelocType != 0)
2770 {
2771 if (pModElf->DynInfo.uPtrJmpRelocs == ~(Elf_Addr)0)
2772 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_JMPREL", pszLogName);
2773 if (pModElf->DynInfo.cbJmpRelocs == 0)
2774 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTRELSZ", pszLogName);
2775 if (pModElf->DynInfo.uJmpRelocType == 0)
2776 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTREL", pszLogName);
2777 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShJmpRelocs];
2778 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2779 if (pShdrRelocs->sh_type != uShType)
2780 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match section type: %u vs %u",
2781 pszLogName, pShdrRelocs->sh_type, uShType);
2782 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbJmpRelocs)
2783 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTRELSZ does not match section size: %u vs %u",
2784 pszLogName, pShdrRelocs->sh_size, pModElf->DynInfo.cbJmpRelocs);
2785 if (uShType != uShTypeArch)
2786 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match architecture: %u, arch wants %u",
2787 pszLogName, uShType, uShTypeArch);
2788 }
2789
2790 /*
2791 * Check that there aren't any other relocations hiding in the section table.
2792 */
2793 for (uint32_t i = 1; i < pModElf->Ehdr.e_shnum; i++)
2794 if ( (paShdrs[i].sh_type == SHT_REL || paShdrs[i].sh_type == SHT_RELA)
2795 && pModElf->paShdrExtras[i].uDtTag != DT_REL
2796 && pModElf->paShdrExtras[i].uDtTag != DT_RELA
2797 && pModElf->paShdrExtras[i].uDtTag != DT_JMPREL)
2798 {
2799 char szSecHdrNm[80];
2800 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2801 "%s: section header #%u (%s type=" FMT_ELF_WORD " size=" FMT_ELF_XWORD ") contains relocations not referenced by the dynamic section",
2802 pszLogName, i,
2803 RTLDRELF_NAME(GetSHdrName)(pModElf, paShdrs[i].sh_name, szSecHdrNm, sizeof(szSecHdrNm)),
2804 paShdrs[i].sh_type, paShdrs[i].sh_size);
2805 }
2806
2807 return VINF_SUCCESS;
2808}
2809
2810
2811
2812/**
2813 * Opens an ELF image, fixed bitness.
2814 *
2815 * @returns iprt status code.
2816 * @param pReader The loader reader instance which will provide the raw image bits.
2817 * @param fFlags Reserved, MBZ.
2818 * @param enmArch Architecture specifier.
2819 * @param phLdrMod Where to store the handle.
2820 * @param pErrInfo Where to return extended error info. Optional.
2821 */
2822static int RTLDRELF_NAME(Open)(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
2823{
2824 const char *pszLogName = pReader->pfnLogName(pReader);
2825 uint64_t cbRawImage = pReader->pfnSize(pReader);
2826 RT_NOREF_PV(fFlags);
2827
2828 /*
2829 * Create the loader module instance.
2830 */
2831 PRTLDRMODELF pModElf = (PRTLDRMODELF)RTMemAllocZ(sizeof(*pModElf));
2832 if (!pModElf)
2833 return VERR_NO_MEMORY;
2834
2835 pModElf->Core.u32Magic = RTLDRMOD_MAGIC;
2836 pModElf->Core.eState = LDR_STATE_INVALID;
2837 pModElf->Core.pReader = pReader;
2838 pModElf->Core.enmFormat = RTLDRFMT_ELF;
2839 pModElf->Core.enmType = RTLDRTYPE_OBJECT;
2840 pModElf->Core.enmEndian = RTLDRENDIAN_LITTLE;
2841#if ELF_MODE == 32
2842 pModElf->Core.enmArch = RTLDRARCH_X86_32;
2843#else
2844 pModElf->Core.enmArch = RTLDRARCH_AMD64;
2845#endif
2846 //pModElf->pvBits = NULL;
2847 //pModElf->Ehdr = {0};
2848 //pModElf->paShdrs = NULL;
2849 //pModElf->Rel.paSyms = NULL;
2850 pModElf->Rel.iSymSh = ~0U;
2851 //pModElf->Rel.cSyms = 0;
2852 pModElf->Rel.iStrSh = ~0U;
2853 //pModElf->Rel.cbStr = 0;
2854 //pModElf->Rel.pStr = NULL;
2855 //pModElf->Dyn.paSyms = NULL;
2856 pModElf->Dyn.iSymSh = ~0U;
2857 //pModElf->Dyn.cSyms = 0;
2858 pModElf->Dyn.iStrSh = ~0U;
2859 //pModElf->Dyn.cbStr = 0;
2860 //pModElf->Dyn.pStr = NULL;
2861 pModElf->iFirstSect = 1;
2862 //pModElf->fShdrInOrder = false;
2863 //pModElf->cbImage = 0;
2864 pModElf->LinkAddress = ~(Elf_Addr)0;
2865 //pModElf->cbShStr = 0;
2866 //pModElf->pShStr = NULL;
2867 //pModElf->iShEhFrame = 0;
2868 //pModElf->iShEhFrameHdr= 0;
2869 pModElf->iShDynamic = ~0U;
2870 //pModElf->cDynamic = 0;
2871 //pModElf->paDynamic = NULL;
2872 //pModElf->paPhdrs = NULL;
2873 pModElf->DynInfo.uPtrRelocs = ~(Elf_Addr)0;
2874 //pModElf->DynInfo.cbRelocs = 0;
2875 //pModElf->DynInfo.cbRelocEntry = 0;
2876 //pModElf->DynInfo.uRelocType = 0;
2877 //pModElf->DynInfo.idxShRelocs = 0;
2878 pModElf->DynInfo.uPtrJmpRelocs = ~(Elf_Addr)0;
2879 //pModElf->DynInfo.cbJmpRelocs = 0;
2880 //pModElf->DynInfo.uJmpRelocType = 0;
2881 //pModElf->DynInfo.idxShJmpRelocs = 0;
2882
2883 /*
2884 * Read and validate the ELF header and match up the CPU architecture.
2885 */
2886 int rc = pReader->pfnRead(pReader, &pModElf->Ehdr, sizeof(pModElf->Ehdr), 0);
2887 if (RT_SUCCESS(rc))
2888 {
2889 RTLDRARCH enmArchImage = RTLDRARCH_INVALID; /* shut up gcc */
2890 rc = RTLDRELF_NAME(ValidateElfHeader)(&pModElf->Ehdr, cbRawImage, pszLogName, &enmArchImage, pErrInfo);
2891 if (RT_SUCCESS(rc))
2892 {
2893 if ( enmArch != RTLDRARCH_WHATEVER
2894 && enmArch != enmArchImage)
2895 rc = VERR_LDR_ARCH_MISMATCH;
2896 }
2897 }
2898 if (RT_SUCCESS(rc))
2899 {
2900 /*
2901 * Read the section headers, keeping a prestine copy for the module
2902 * introspection methods.
2903 */
2904 size_t const cbShdrs = pModElf->Ehdr.e_shnum * sizeof(Elf_Shdr);
2905 Elf_Shdr *paShdrs = (Elf_Shdr *)RTMemAlloc(cbShdrs * 2 + sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2906 if (paShdrs)
2907 {
2908 pModElf->paShdrs = paShdrs;
2909 rc = pReader->pfnRead(pReader, paShdrs, cbShdrs, pModElf->Ehdr.e_shoff);
2910 if (RT_SUCCESS(rc))
2911 {
2912 memcpy(&paShdrs[pModElf->Ehdr.e_shnum], paShdrs, cbShdrs);
2913 pModElf->paOrgShdrs = &paShdrs[pModElf->Ehdr.e_shnum];
2914
2915 pModElf->paShdrExtras = (PRTLDRMODELFSHX)&pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
2916 memset(pModElf->paShdrExtras, 0xff, sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2917
2918 pModElf->cbShStr = paShdrs[pModElf->Ehdr.e_shstrndx].sh_size;
2919
2920 /*
2921 * Validate the section headers and find relevant sections.
2922 */
2923 rc = RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(pModElf, paShdrs, cbRawImage, pszLogName, pErrInfo);
2924
2925 /*
2926 * Read validate and process program headers if ET_DYN or ET_EXEC.
2927 */
2928 if (RT_SUCCESS(rc) && (pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC))
2929 rc = RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(pModElf, cbRawImage, fFlags, pszLogName, pErrInfo);
2930
2931 /*
2932 * Massage the section headers.
2933 */
2934 if (RT_SUCCESS(rc))
2935 {
2936 if (pModElf->Ehdr.e_type == ET_REL)
2937 {
2938 /* Do allocations and figure the image size: */
2939 pModElf->LinkAddress = 0;
2940 for (unsigned i = 1; i < pModElf->Ehdr.e_shnum; i++)
2941 if (paShdrs[i].sh_flags & SHF_ALLOC)
2942 {
2943 paShdrs[i].sh_addr = paShdrs[i].sh_addralign
2944 ? RT_ALIGN_T(pModElf->cbImage, paShdrs[i].sh_addralign, Elf_Addr)
2945 : (Elf_Addr)pModElf->cbImage;
2946 Elf_Addr EndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2947 if (pModElf->cbImage < EndAddr)
2948 {
2949 pModElf->cbImage = (size_t)EndAddr;
2950 AssertMsgBreakStmt(pModElf->cbImage == EndAddr, (FMT_ELF_ADDR "\n", EndAddr), rc = VERR_IMAGE_TOO_BIG);
2951 }
2952 Log2(("RTLdrElf: %s: Assigned " FMT_ELF_ADDR " to section #%d\n", pszLogName, paShdrs[i].sh_addr, i));
2953 }
2954 }
2955 else
2956 {
2957 /* Convert sh_addr to RVA: */
2958 Assert(pModElf->LinkAddress != ~(Elf_Addr)0);
2959 for (unsigned i = 0 /*!*/; i < pModElf->Ehdr.e_shnum; i++)
2960 if (paShdrs[i].sh_flags & SHF_ALLOC)
2961 paShdrs[i].sh_addr -= pModElf->LinkAddress;
2962 }
2963 }
2964
2965 /*
2966 * Check if the sections are in order by address, as that will simplify
2967 * enumeration and address translation.
2968 */
2969 pModElf->fShdrInOrder = true;
2970 Elf_Addr uEndAddr = 0;
2971 for (unsigned i = pModElf->iFirstSect; i < pModElf->Ehdr.e_shnum; i++)
2972 if (paShdrs[i].sh_flags & SHF_ALLOC)
2973 {
2974 if (uEndAddr <= paShdrs[i].sh_addr)
2975 uEndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2976 else
2977 {
2978 pModElf->fShdrInOrder = false;
2979 break;
2980 }
2981 }
2982
2983 Log2(("RTLdrElf: iSymSh=%u cSyms=%u iStrSh=%u cbStr=%u rc=%Rrc cbImage=%#zx LinkAddress=" FMT_ELF_ADDR " fShdrInOrder=%RTbool\n",
2984 pModElf->Rel.iSymSh, pModElf->Rel.cSyms, pModElf->Rel.iStrSh, pModElf->Rel.cbStr, rc,
2985 pModElf->cbImage, pModElf->LinkAddress, pModElf->fShdrInOrder));
2986 if (RT_SUCCESS(rc))
2987 {
2988 pModElf->Core.pOps = &RTLDRELF_MID(s_rtldrElf,Ops);
2989 pModElf->Core.eState = LDR_STATE_OPENED;
2990 *phLdrMod = &pModElf->Core;
2991
2992 LogFlow(("%s: %s: returns VINF_SUCCESS *phLdrMod=%p\n", __FUNCTION__, pszLogName, *phLdrMod));
2993 return VINF_SUCCESS;
2994 }
2995 }
2996
2997 RTMemFree(paShdrs);
2998 }
2999 else
3000 rc = VERR_NO_MEMORY;
3001 }
3002
3003 RTMemFree(pModElf);
3004 LogFlow(("%s: returns %Rrc\n", __FUNCTION__, rc));
3005 return rc;
3006}
3007
3008
3009
3010
3011/*******************************************************************************
3012* Cleanup Constants And Macros *
3013*******************************************************************************/
3014#undef RTLDRELF_NAME
3015#undef RTLDRELF_SUFF
3016#undef RTLDRELF_MID
3017
3018#undef FMT_ELF_ADDR
3019#undef FMT_ELF_ADDR7
3020#undef FMT_ELF_HALF
3021#undef FMT_ELF_SHALF
3022#undef FMT_ELF_OFF
3023#undef FMT_ELF_SIZE
3024#undef FMT_ELF_SWORD
3025#undef FMT_ELF_WORD
3026#undef FMT_ELF_XWORD
3027#undef FMT_ELF_SXWORD
3028
3029#undef Elf_Ehdr
3030#undef Elf_Phdr
3031#undef Elf_Shdr
3032#undef Elf_Sym
3033#undef Elf_Rel
3034#undef Elf_Rela
3035#undef Elf_Reloc
3036#undef Elf_Nhdr
3037#undef Elf_Dyn
3038
3039#undef Elf_Addr
3040#undef Elf_Half
3041#undef Elf_Off
3042#undef Elf_Size
3043#undef Elf_Sword
3044#undef Elf_Word
3045#undef Elf_Xword
3046#undef Elf_Sxword
3047
3048#undef RTLDRMODELF
3049#undef PRTLDRMODELF
3050
3051#undef ELF_R_SYM
3052#undef ELF_R_TYPE
3053#undef ELF_R_INFO
3054
3055#undef ELF_ST_BIND
3056
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette