VirtualBox

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

Last change on this file since 85525 was 85525, checked in by vboxsync, 5 years ago

IPRT/ldrELF: Fix for bogus cbMapped value returned for the last segment when enumerating segments. bugref:9801

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 131.4 KB
Line 
1/* $Id: ldrELFRelocatable.cpp.h 85525 2020-07-29 14:28:59Z 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 * Helper that locates the first allocated section.
1365 *
1366 * @returns Pointer to the section header if found, NULL if none.
1367 * @param pShdr The section header to start searching at.
1368 * @param cLeft The number of section headers left to search. Can be 0.
1369 */
1370static const Elf_Shdr *RTLDRELF_NAME(GetFirstAllocatedSection)(const Elf_Shdr *pShdr, unsigned cLeft)
1371{
1372 while (cLeft-- > 0)
1373 {
1374 if (pShdr->sh_flags & SHF_ALLOC)
1375 return pShdr;
1376 pShdr++;
1377 }
1378 return NULL;
1379}
1380
1381/**
1382 * Helper that locates the next allocated section logically by RVA (sh_addr).
1383 *
1384 * @returns Pointer to the section header if found, NULL if none.
1385 * @param pModElf The module instance.
1386 * @param iCur The current section header.
1387 */
1388static const Elf_Shdr *RTLDRELF_NAME(GetNextAllocatedSection)(PRTLDRMODELF pModElf, unsigned iCur)
1389{
1390 unsigned const cShdrs = pModElf->Ehdr.e_shnum;
1391 const Elf_Shdr * const paShdrs = pModElf->paShdrs;
1392 if (pModElf->fShdrInOrder)
1393 {
1394 for (; iCur < cShdrs; iCur++)
1395 if (paShdrs[iCur].sh_flags & SHF_ALLOC)
1396 return &paShdrs[iCur];
1397 }
1398 else
1399 {
1400 Elf_Addr const uEndCur = paShdrs[iCur].sh_addr + paShdrs[iCur].sh_size;
1401 Elf_Addr offBest = ~(Elf_Addr)0;
1402 unsigned iBest = cShdrs;
1403 for (iCur = pModElf->iFirstSect; iCur < cShdrs; iCur++)
1404 if (paShdrs[iCur].sh_flags & SHF_ALLOC)
1405 {
1406 Elf_Addr const offDelta = paShdrs[iCur].sh_addr - uEndCur;
1407 if ( offDelta < offBest
1408 && paShdrs[iCur].sh_addr >= uEndCur)
1409 {
1410 offBest = offDelta;
1411 iBest = iCur;
1412 }
1413 }
1414 if (iBest < cShdrs)
1415 return &paShdrs[iBest];
1416 }
1417 return NULL;
1418}
1419
1420/** @copydoc RTLDROPS::pfnEnumSegments. */
1421static DECLCALLBACK(int) RTLDRELF_NAME(EnumSegments)(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
1422{
1423 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1424
1425 /*
1426 * Map the image bits if not already done and setup pointer into it.
1427 */
1428 int rc = RTLDRELF_NAME(MapBits)(pModElf, true);
1429 if (RT_FAILURE(rc))
1430 return rc;
1431
1432 /*
1433 * Do the enumeration.
1434 */
1435 char szName[32];
1436 Elf_Addr uPrevMappedRva = 0;
1437 const Elf_Shdr *paShdrs = pModElf->paShdrs;
1438 const Elf_Shdr *paOrgShdrs = pModElf->paOrgShdrs;
1439 for (unsigned iShdr = pModElf->iFirstSect; iShdr < pModElf->Ehdr.e_shnum; iShdr++)
1440 {
1441 RTLDRSEG Seg;
1442 if (iShdr != 0)
1443 {
1444 Seg.pszName = ELF_SH_STR(pModElf, paShdrs[iShdr].sh_name);
1445 Seg.cchName = (uint32_t)strlen(Seg.pszName);
1446 if (Seg.cchName == 0)
1447 {
1448 Seg.pszName = szName;
1449 Seg.cchName = (uint32_t)RTStrPrintf(szName, sizeof(szName), "UnamedSect%02u", iShdr);
1450 }
1451 }
1452 else
1453 {
1454 Seg.pszName = ".elf.headers";
1455 Seg.cchName = 12;
1456 }
1457 Seg.SelFlat = 0;
1458 Seg.Sel16bit = 0;
1459 Seg.fFlags = 0;
1460 Seg.fProt = RTMEM_PROT_READ;
1461 if (paShdrs[iShdr].sh_flags & SHF_WRITE)
1462 Seg.fProt |= RTMEM_PROT_WRITE;
1463 if (paShdrs[iShdr].sh_flags & SHF_EXECINSTR)
1464 Seg.fProt |= RTMEM_PROT_EXEC;
1465 Seg.cb = paShdrs[iShdr].sh_size;
1466 Seg.Alignment = paShdrs[iShdr].sh_addralign;
1467 if (paShdrs[iShdr].sh_flags & SHF_ALLOC)
1468 {
1469 Seg.LinkAddress = paOrgShdrs[iShdr].sh_addr;
1470 Seg.RVA = paShdrs[iShdr].sh_addr;
1471 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetNextAllocatedSection)(pModElf, iShdr);
1472 if (pShdr2)
1473 Seg.cbMapped = pShdr2->sh_addr - paShdrs[iShdr].sh_addr;
1474 else
1475 Seg.cbMapped = pModElf->cbImage - paShdrs[iShdr].sh_addr;
1476 uPrevMappedRva = Seg.RVA;
1477 }
1478 else
1479 {
1480 Seg.LinkAddress = NIL_RTLDRADDR;
1481 Seg.RVA = NIL_RTLDRADDR;
1482 Seg.cbMapped = NIL_RTLDRADDR;
1483 }
1484 if (paShdrs[iShdr].sh_type != SHT_NOBITS)
1485 {
1486 Seg.offFile = paShdrs[iShdr].sh_offset;
1487 Seg.cbFile = paShdrs[iShdr].sh_size;
1488 }
1489 else
1490 {
1491 Seg.offFile = -1;
1492 Seg.cbFile = 0;
1493 }
1494
1495 rc = pfnCallback(pMod, &Seg, pvUser);
1496 if (rc != VINF_SUCCESS)
1497 return rc;
1498 }
1499
1500 return VINF_SUCCESS;
1501}
1502
1503
1504/** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */
1505static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress,
1506 uint32_t *piSeg, PRTLDRADDR poffSeg)
1507{
1508 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1509
1510 const Elf_Shdr *pShdrEnd = NULL;
1511 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1512 const Elf_Shdr *pShdr = &pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
1513 while (cLeft-- > 0)
1514 {
1515 pShdr--;
1516 if (pShdr->sh_flags & SHF_ALLOC)
1517 {
1518 RTLDRADDR offSeg = LinkAddress - pShdr->sh_addr;
1519 if (offSeg < pShdr->sh_size)
1520 {
1521 *poffSeg = offSeg;
1522 *piSeg = cLeft;
1523 return VINF_SUCCESS;
1524 }
1525 if (offSeg == pShdr->sh_size)
1526 pShdrEnd = pShdr;
1527 }
1528 }
1529
1530 if (pShdrEnd)
1531 {
1532 *poffSeg = pShdrEnd->sh_size;
1533 *piSeg = pShdrEnd - pModElf->paOrgShdrs - pModElf->iFirstSect;
1534 return VINF_SUCCESS;
1535 }
1536
1537 return VERR_LDR_INVALID_LINK_ADDRESS;
1538}
1539
1540
1541/** @copydoc RTLDROPS::pfnLinkAddressToRva. */
1542static DECLCALLBACK(int) RTLDRELF_NAME(LinkAddressToRva)(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva)
1543{
1544 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1545 uint32_t iSeg;
1546 RTLDRADDR offSeg;
1547 int rc = RTLDRELF_NAME(LinkAddressToSegOffset)(pMod, LinkAddress, &iSeg, &offSeg);
1548 if (RT_SUCCESS(rc))
1549 *pRva = pModElf->paShdrs[iSeg + pModElf->iFirstSect].sh_addr + offSeg;
1550 return rc;
1551}
1552
1553
1554/** @copydoc RTLDROPS::pfnSegOffsetToRva. */
1555static DECLCALLBACK(int) RTLDRELF_NAME(SegOffsetToRva)(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg,
1556 PRTLDRADDR pRva)
1557{
1558 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1559 if (iSeg >= pModElf->Ehdr.e_shnum - pModElf->iFirstSect)
1560 return VERR_LDR_INVALID_SEG_OFFSET;
1561
1562 iSeg += pModElf->iFirstSect; /* skip section 0 if not used */
1563 if (offSeg > pModElf->paShdrs[iSeg].sh_size)
1564 {
1565 const Elf_Shdr *pShdr2 = RTLDRELF_NAME(GetFirstAllocatedSection)(&pModElf->paShdrs[iSeg + 1],
1566 pModElf->Ehdr.e_shnum - iSeg - 1);
1567 if ( !pShdr2
1568 || offSeg > (pShdr2->sh_addr - pModElf->paShdrs[iSeg].sh_addr))
1569 return VERR_LDR_INVALID_SEG_OFFSET;
1570 }
1571
1572 if (!(pModElf->paShdrs[iSeg].sh_flags & SHF_ALLOC))
1573 return VERR_LDR_INVALID_SEG_OFFSET;
1574
1575 *pRva = pModElf->paShdrs[iSeg].sh_addr;
1576 return VINF_SUCCESS;
1577}
1578
1579
1580/** @copydoc RTLDROPS::pfnRvaToSegOffset. */
1581static DECLCALLBACK(int) RTLDRELF_NAME(RvaToSegOffset)(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva,
1582 uint32_t *piSeg, PRTLDRADDR poffSeg)
1583{
1584 PRTLDRMODELF pModElf = (PRTLDRMODELF)pMod;
1585 Elf_Addr PrevAddr = 0;
1586 unsigned cLeft = pModElf->Ehdr.e_shnum - pModElf->iFirstSect;
1587 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->Ehdr.e_shnum];
1588 while (cLeft-- > 0)
1589 {
1590 pShdr--;
1591 if (pShdr->sh_flags & SHF_ALLOC)
1592 {
1593 Elf_Addr cbSeg = PrevAddr ? PrevAddr - pShdr->sh_addr : pShdr->sh_size;
1594 RTLDRADDR offSeg = Rva - pShdr->sh_addr;
1595 if (offSeg <= cbSeg)
1596 {
1597 *poffSeg = offSeg;
1598 *piSeg = cLeft;
1599 return VINF_SUCCESS;
1600 }
1601 PrevAddr = pShdr->sh_addr;
1602 }
1603 }
1604
1605 return VERR_LDR_INVALID_RVA;
1606}
1607
1608
1609/** @callback_method_impl{FNRTLDRIMPORT, Stub used by ReadDbgInfo.} */
1610static DECLCALLBACK(int) RTLDRELF_NAME(GetImportStubCallback)(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol,
1611 unsigned uSymbol, PRTLDRADDR pValue, void *pvUser)
1612{
1613 RT_NOREF_PV(hLdrMod); RT_NOREF_PV(pszModule); RT_NOREF_PV(pszSymbol);
1614 RT_NOREF_PV(uSymbol); RT_NOREF_PV(pValue); RT_NOREF_PV(pvUser);
1615 return VERR_SYMBOL_NOT_FOUND;
1616}
1617
1618
1619/** @copydoc RTLDROPS::pfnReadDbgInfo. */
1620static DECLCALLBACK(int) RTLDRELF_NAME(ReadDbgInfo)(PRTLDRMODINTERNAL pMod, uint32_t iDbgInfo, RTFOFF off,
1621 size_t cb, void *pvBuf)
1622{
1623 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1624 LogFlow(("%s: iDbgInfo=%#x off=%RTfoff cb=%#zu\n", __FUNCTION__, iDbgInfo, off, cb));
1625
1626 /*
1627 * Input validation.
1628 */
1629 AssertReturn(iDbgInfo < pThis->Ehdr.e_shnum && iDbgInfo + 1 < pThis->Ehdr.e_shnum, VERR_INVALID_PARAMETER);
1630 iDbgInfo++;
1631 AssertReturn(!(pThis->paShdrs[iDbgInfo].sh_flags & SHF_ALLOC), VERR_INVALID_PARAMETER);
1632 AssertReturn(pThis->paShdrs[iDbgInfo].sh_type == SHT_PROGBITS, VERR_INVALID_PARAMETER);
1633 AssertReturn(pThis->paShdrs[iDbgInfo].sh_offset == (uint64_t)off, VERR_INVALID_PARAMETER);
1634 AssertReturn(pThis->paShdrs[iDbgInfo].sh_size == cb, VERR_INVALID_PARAMETER);
1635 uint64_t cbRawImage = pThis->Core.pReader->pfnSize(pThis->Core.pReader);
1636 AssertReturn(off >= 0 && cb <= cbRawImage && (uint64_t)off + cb <= cbRawImage, VERR_INVALID_PARAMETER);
1637
1638 /*
1639 * Read it from the file and look for fixup sections.
1640 */
1641 int rc;
1642 if (pThis->pvBits)
1643 memcpy(pvBuf, (const uint8_t *)pThis->pvBits + (size_t)off, cb);
1644 else
1645 {
1646 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pvBuf, cb, off);
1647 if (RT_FAILURE(rc))
1648 return rc;
1649 }
1650
1651 uint32_t iRelocs = iDbgInfo + 1;
1652 if ( iRelocs >= pThis->Ehdr.e_shnum
1653 || pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1654 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1655 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA) )
1656 {
1657 iRelocs = 0;
1658 while ( iRelocs < pThis->Ehdr.e_shnum
1659 && ( pThis->paShdrs[iRelocs].sh_info != iDbgInfo
1660 || ( pThis->paShdrs[iRelocs].sh_type != SHT_REL
1661 && pThis->paShdrs[iRelocs].sh_type != SHT_RELA)) )
1662 iRelocs++;
1663 }
1664 if ( iRelocs < pThis->Ehdr.e_shnum
1665 && pThis->paShdrs[iRelocs].sh_size > 0)
1666 {
1667 /*
1668 * Load the relocations.
1669 */
1670 uint8_t *pbRelocsBuf = NULL;
1671 const uint8_t *pbRelocs;
1672 if (pThis->pvBits)
1673 pbRelocs = (const uint8_t *)pThis->pvBits + pThis->paShdrs[iRelocs].sh_offset;
1674 else
1675 {
1676 pbRelocs = pbRelocsBuf = (uint8_t *)RTMemTmpAlloc(pThis->paShdrs[iRelocs].sh_size);
1677 if (!pbRelocsBuf)
1678 return VERR_NO_TMP_MEMORY;
1679 rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pbRelocsBuf,
1680 pThis->paShdrs[iRelocs].sh_size,
1681 pThis->paShdrs[iRelocs].sh_offset);
1682 if (RT_FAILURE(rc))
1683 {
1684 RTMemTmpFree(pbRelocsBuf);
1685 return rc;
1686 }
1687 }
1688
1689 /*
1690 * Apply the relocations.
1691 */
1692 if (pThis->Ehdr.e_type == ET_REL)
1693 rc = RTLDRELF_NAME(RelocateSectionRel)(pThis, pThis->LinkAddress,
1694 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1695 pThis->paShdrs[iDbgInfo].sh_addr,
1696 pThis->paShdrs[iDbgInfo].sh_size,
1697 (const uint8_t *)pvBuf,
1698 (uint8_t *)pvBuf,
1699 pbRelocs,
1700 pThis->paShdrs[iRelocs].sh_size);
1701 else
1702 rc = RTLDRELF_NAME(RelocateSectionExecDyn)(pThis, pThis->LinkAddress,
1703 RTLDRELF_NAME(GetImportStubCallback), NULL /*pvUser*/,
1704 pThis->paShdrs[iDbgInfo].sh_addr,
1705 pThis->paShdrs[iDbgInfo].sh_size,
1706 (const uint8_t *)pvBuf,
1707 (uint8_t *)pvBuf,
1708 pbRelocs,
1709 pThis->paShdrs[iRelocs].sh_size);
1710
1711 RTMemTmpFree(pbRelocsBuf);
1712 }
1713 else
1714 rc = VINF_SUCCESS;
1715 return rc;
1716}
1717
1718
1719/**
1720 * @interface_method_impl{RTLDROPS,pfnUnwindFrame}
1721 */
1722static DECLCALLBACK(int)
1723RTLDRELF_NAME(UnwindFrame)(PRTLDRMODINTERNAL pMod, void const *pvBits, uint32_t iSeg, RTUINTPTR off, PRTDBGUNWINDSTATE pState)
1724{
1725 PRTLDRMODELF pThis = (PRTLDRMODELF)pMod;
1726 LogFlow(("%s: iSeg=%#x off=%RTptr\n", __FUNCTION__, iSeg, off));
1727
1728 /*
1729 * Process the input address, making us both RVA and proper seg:offset out of it.
1730 */
1731 int rc;
1732 RTLDRADDR uRva = off;
1733 if (iSeg == UINT32_MAX)
1734 rc = RTLDRELF_NAME(RvaToSegOffset)(pMod, uRva, &iSeg, &off);
1735 else
1736 rc = RTLDRELF_NAME(SegOffsetToRva)(pMod, iSeg, off, &uRva);
1737 AssertRCReturn(rc, rc);
1738
1739 /*
1740 * Map the image bits if not already done and setup pointer into it.
1741 */
1742 RT_NOREF(pvBits); /** @todo Try use passed in pvBits? */
1743 rc = RTLDRELF_NAME(MapBits)(pThis, true);
1744 if (RT_FAILURE(rc))
1745 return rc;
1746
1747 /*
1748 * Do we need to search for .eh_frame and .eh_frame_hdr?
1749 */
1750 if (pThis->iShEhFrame == 0)
1751 {
1752 pThis->iShEhFrame = ~0U;
1753 pThis->iShEhFrameHdr = ~0U;
1754 unsigned cLeft = 2;
1755 for (unsigned iShdr = 1; iShdr < pThis->Ehdr.e_shnum; iShdr++)
1756 {
1757 const char *pszName = ELF_SH_STR(pThis, pThis->paShdrs[iShdr].sh_name);
1758 if ( pszName[0] == '.'
1759 && pszName[1] == 'e'
1760 && pszName[2] == 'h'
1761 && pszName[3] == '_'
1762 && pszName[4] == 'f'
1763 && pszName[5] == 'r'
1764 && pszName[6] == 'a'
1765 && pszName[7] == 'm'
1766 && pszName[8] == 'e')
1767 {
1768 if (pszName[9] == '\0')
1769 pThis->iShEhFrame = iShdr;
1770 else if ( pszName[9] == '_'
1771 && pszName[10] == 'h'
1772 && pszName[11] == 'd'
1773 && pszName[12] == 'r'
1774 && pszName[13] == '\0')
1775 pThis->iShEhFrameHdr = iShdr;
1776 else
1777 continue;
1778 if (--cLeft == 0)
1779 break;
1780 }
1781 }
1782 }
1783
1784 /*
1785 * Any info present?
1786 */
1787 unsigned iShdr = pThis->iShEhFrame;
1788 if ( iShdr != ~0U
1789 && pThis->paShdrs[iShdr].sh_size > 0)
1790 {
1791 if (pThis->paShdrs[iShdr].sh_flags & SHF_ALLOC)
1792 return rtDwarfUnwind_EhData((uint8_t const *)pThis->pvBits + pThis->paShdrs[iShdr].sh_addr,
1793 pThis->paShdrs[iShdr].sh_size, pThis->paShdrs[iShdr].sh_addr,
1794 iSeg, off, uRva, pState, pThis->Core.enmArch);
1795 }
1796 return VERR_DBG_NO_UNWIND_INFO;
1797}
1798
1799
1800/**
1801 * The ELF module operations.
1802 */
1803static RTLDROPS RTLDRELF_MID(s_rtldrElf,Ops) =
1804{
1805#if ELF_MODE == 32
1806 "elf32",
1807#elif ELF_MODE == 64
1808 "elf64",
1809#endif
1810 RTLDRELF_NAME(Close),
1811 NULL, /* Get Symbol */
1812 RTLDRELF_NAME(Done),
1813 RTLDRELF_NAME(EnumSymbols),
1814 /* ext: */
1815 RTLDRELF_NAME(GetImageSize),
1816 RTLDRELF_NAME(GetBits),
1817 RTLDRELF_NAME(Relocate),
1818 RTLDRELF_NAME(GetSymbolEx),
1819 NULL /*pfnQueryForwarderInfo*/,
1820 RTLDRELF_NAME(EnumDbgInfo),
1821 RTLDRELF_NAME(EnumSegments),
1822 RTLDRELF_NAME(LinkAddressToSegOffset),
1823 RTLDRELF_NAME(LinkAddressToRva),
1824 RTLDRELF_NAME(SegOffsetToRva),
1825 RTLDRELF_NAME(RvaToSegOffset),
1826 RTLDRELF_NAME(ReadDbgInfo),
1827 NULL /*pfnQueryProp*/,
1828 NULL /*pfnVerifySignature*/,
1829 NULL /*pfnHashImage*/,
1830 RTLDRELF_NAME(UnwindFrame),
1831 42
1832};
1833
1834
1835
1836/**
1837 * Validates the ELF header.
1838 *
1839 * @returns iprt status code.
1840 * @param pEhdr Pointer to the ELF header.
1841 * @param cbRawImage The size of the raw image.
1842 * @param pszLogName The log name.
1843 * @param penmArch Where to return the architecture.
1844 * @param pErrInfo Where to return extended error info. Optional.
1845 */
1846static int RTLDRELF_NAME(ValidateElfHeader)(const Elf_Ehdr *pEhdr, uint64_t cbRawImage, const char *pszLogName,
1847 PRTLDRARCH penmArch, PRTERRINFO pErrInfo)
1848{
1849 Log3(("RTLdrELF: e_ident: %.*Rhxs\n"
1850 "RTLdrELF: e_type: " FMT_ELF_HALF "\n"
1851 "RTLdrELF: e_version: " FMT_ELF_HALF "\n"
1852 "RTLdrELF: e_entry: " FMT_ELF_ADDR "\n"
1853 "RTLdrELF: e_phoff: " FMT_ELF_OFF "\n"
1854 "RTLdrELF: e_shoff: " FMT_ELF_OFF "\n"
1855 "RTLdrELF: e_flags: " FMT_ELF_WORD "\n"
1856 "RTLdrELF: e_ehsize: " FMT_ELF_HALF "\n"
1857 "RTLdrELF: e_phentsize: " FMT_ELF_HALF "\n"
1858 "RTLdrELF: e_phnum: " FMT_ELF_HALF "\n"
1859 "RTLdrELF: e_shentsize: " FMT_ELF_HALF "\n"
1860 "RTLdrELF: e_shnum: " FMT_ELF_HALF "\n"
1861 "RTLdrELF: e_shstrndx: " FMT_ELF_HALF "\n",
1862 RT_ELEMENTS(pEhdr->e_ident), &pEhdr->e_ident[0], pEhdr->e_type, pEhdr->e_version,
1863 pEhdr->e_entry, pEhdr->e_phoff, pEhdr->e_shoff,pEhdr->e_flags, pEhdr->e_ehsize, pEhdr->e_phentsize,
1864 pEhdr->e_phnum, pEhdr->e_shentsize, pEhdr->e_shnum, pEhdr->e_shstrndx));
1865
1866 if ( pEhdr->e_ident[EI_MAG0] != ELFMAG0
1867 || pEhdr->e_ident[EI_MAG1] != ELFMAG1
1868 || pEhdr->e_ident[EI_MAG2] != ELFMAG2
1869 || pEhdr->e_ident[EI_MAG3] != ELFMAG3)
1870 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1871 "%s: Invalid ELF magic (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1872 if (pEhdr->e_ident[EI_CLASS] != RTLDRELF_SUFF(ELFCLASS))
1873 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1874 "%s: Invalid ELF class (%.*Rhxs)", pszLogName, sizeof(pEhdr->e_ident), pEhdr->e_ident);
1875 if (pEhdr->e_ident[EI_DATA] != ELFDATA2LSB)
1876 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_ODD_ENDIAN,
1877 "%s: ELF endian %x is unsupported", pszLogName, pEhdr->e_ident[EI_DATA]);
1878 if (pEhdr->e_version != EV_CURRENT)
1879 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_VERSION,
1880 "%s: ELF version %x is unsupported", pszLogName, pEhdr->e_version);
1881
1882 if (sizeof(Elf_Ehdr) != pEhdr->e_ehsize)
1883 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1884 "%s: Elf header e_ehsize is %d expected %d!", pszLogName, pEhdr->e_ehsize, sizeof(Elf_Ehdr));
1885 if ( sizeof(Elf_Phdr) != pEhdr->e_phentsize
1886 && ( pEhdr->e_phnum != 0
1887 || pEhdr->e_type == ET_DYN
1888 || pEhdr->e_type == ET_EXEC))
1889 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_phentsize is %d expected %d!",
1890 pszLogName, pEhdr->e_phentsize, sizeof(Elf_Phdr));
1891 if (sizeof(Elf_Shdr) != pEhdr->e_shentsize)
1892 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Elf header e_shentsize is %d expected %d!",
1893 pszLogName, pEhdr->e_shentsize, sizeof(Elf_Shdr));
1894
1895 switch (pEhdr->e_type)
1896 {
1897 case ET_REL:
1898 case ET_EXEC:
1899 case ET_DYN:
1900 break;
1901 default:
1902 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: image type %#x is not supported!",
1903 pszLogName, pEhdr->e_type);
1904 }
1905
1906 switch (pEhdr->e_machine)
1907 {
1908#if ELF_MODE == 32
1909 case EM_386:
1910 case EM_486:
1911 *penmArch = RTLDRARCH_X86_32;
1912 break;
1913#elif ELF_MODE == 64
1914 case EM_X86_64:
1915 *penmArch = RTLDRARCH_AMD64;
1916 break;
1917#endif
1918 default:
1919 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MACHINE,
1920 "%s: machine type %u is not supported!", pszLogName, pEhdr->e_machine);
1921 }
1922
1923 if ( pEhdr->e_phoff < pEhdr->e_ehsize
1924 && !(pEhdr->e_phoff && pEhdr->e_phnum)
1925 && pEhdr->e_phnum)
1926 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1927 "%s: The program headers overlap with the ELF header! e_phoff=" FMT_ELF_OFF,
1928 pszLogName, pEhdr->e_phoff);
1929 if ( pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize > cbRawImage
1930 || pEhdr->e_phoff + pEhdr->e_phnum * pEhdr->e_phentsize < pEhdr->e_phoff)
1931 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1932 "%s: The program headers extends beyond the file! e_phoff=" FMT_ELF_OFF " e_phnum=" FMT_ELF_HALF,
1933 pszLogName, pEhdr->e_phoff, pEhdr->e_phnum);
1934
1935
1936 if ( pEhdr->e_shoff < pEhdr->e_ehsize
1937 && !(pEhdr->e_shoff && pEhdr->e_shnum))
1938 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1939 "%s: The section headers overlap with the ELF header! e_shoff=" FMT_ELF_OFF,
1940 pszLogName, pEhdr->e_shoff);
1941 if ( pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize > cbRawImage
1942 || pEhdr->e_shoff + pEhdr->e_shnum * pEhdr->e_shentsize < pEhdr->e_shoff)
1943 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1944 "%s: The section headers extends beyond the file! e_shoff=" FMT_ELF_OFF " e_shnum=" FMT_ELF_HALF,
1945 pszLogName, pEhdr->e_shoff, pEhdr->e_shnum);
1946
1947 if (pEhdr->e_shstrndx == 0 || pEhdr->e_shstrndx > pEhdr->e_shnum)
1948 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
1949 "%s: The section headers string table is out of bounds! e_shstrndx=" FMT_ELF_HALF " e_shnum=" FMT_ELF_HALF,
1950 pszLogName, pEhdr->e_shstrndx, pEhdr->e_shnum);
1951
1952 return VINF_SUCCESS;
1953}
1954
1955
1956/**
1957 * Gets the section header name.
1958 *
1959 * @returns pszName.
1960 * @param pEhdr The elf header.
1961 * @param offName The offset of the section header name.
1962 * @param pszName Where to store the name.
1963 * @param cbName The size of the buffer pointed to by pszName.
1964 */
1965const char *RTLDRELF_NAME(GetSHdrName)(PRTLDRMODELF pModElf, Elf_Word offName, char *pszName, size_t cbName)
1966{
1967 RTFOFF off = pModElf->paShdrs[pModElf->Ehdr.e_shstrndx].sh_offset + offName;
1968 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName, cbName - 1, off);
1969 if (RT_FAILURE(rc))
1970 {
1971 /* read by for byte. */
1972 for (unsigned i = 0; i < cbName; i++, off++)
1973 {
1974 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, pszName + i, 1, off);
1975 if (RT_FAILURE(rc))
1976 {
1977 pszName[i] = '\0';
1978 break;
1979 }
1980 }
1981 }
1982
1983 pszName[cbName - 1] = '\0';
1984 return pszName;
1985}
1986
1987
1988/**
1989 * Validates a section header.
1990 *
1991 * @returns iprt status code.
1992 * @param pModElf Pointer to the module structure.
1993 * @param iShdr The index of section header which should be validated.
1994 * The section headers are found in the pModElf->paShdrs array.
1995 * @param cbRawImage The size of the raw image.
1996 * @param pszLogName The log name.
1997 * @param pErrInfo Where to return extended error info. Optional.
1998 */
1999static int RTLDRELF_NAME(ValidateSectionHeader)(PRTLDRMODELF pModElf, unsigned iShdr, uint64_t cbRawImage,
2000 const char *pszLogName, PRTERRINFO pErrInfo)
2001{
2002 const Elf_Shdr *pShdr = &pModElf->paShdrs[iShdr];
2003 char szSectionName[80]; NOREF(szSectionName);
2004 Log3(("RTLdrELF: Section Header #%d:\n"
2005 "RTLdrELF: sh_name: " FMT_ELF_WORD " - %s\n"
2006 "RTLdrELF: sh_type: " FMT_ELF_WORD " (%s)\n"
2007 "RTLdrELF: sh_flags: " FMT_ELF_XWORD "\n"
2008 "RTLdrELF: sh_addr: " FMT_ELF_ADDR "\n"
2009 "RTLdrELF: sh_offset: " FMT_ELF_OFF "\n"
2010 "RTLdrELF: sh_size: " FMT_ELF_XWORD "\n"
2011 "RTLdrELF: sh_link: " FMT_ELF_WORD "\n"
2012 "RTLdrELF: sh_info: " FMT_ELF_WORD "\n"
2013 "RTLdrELF: sh_addralign: " FMT_ELF_XWORD "\n"
2014 "RTLdrELF: sh_entsize: " FMT_ELF_XWORD "\n",
2015 iShdr,
2016 pShdr->sh_name, RTLDRELF_NAME(GetSHdrName)(pModElf, pShdr->sh_name, szSectionName, sizeof(szSectionName)),
2017 pShdr->sh_type, rtldrElfGetShdrType(pShdr->sh_type), pShdr->sh_flags, pShdr->sh_addr,
2018 pShdr->sh_offset, pShdr->sh_size, pShdr->sh_link, pShdr->sh_info, pShdr->sh_addralign,
2019 pShdr->sh_entsize));
2020
2021 if (iShdr == 0)
2022 {
2023 if ( pShdr->sh_name != 0
2024 || pShdr->sh_type != SHT_NULL
2025 || pShdr->sh_flags != 0
2026 || pShdr->sh_addr != 0
2027 || pShdr->sh_size != 0
2028 || pShdr->sh_offset != 0
2029 || pShdr->sh_link != SHN_UNDEF
2030 || pShdr->sh_addralign != 0
2031 || pShdr->sh_entsize != 0 )
2032 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2033 "%s: Bad #0 section: %.*Rhxs", pszLogName, sizeof(*pShdr), pShdr);
2034 return VINF_SUCCESS;
2035 }
2036
2037 if (pShdr->sh_name >= pModElf->cbShStr)
2038 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2039 "%s: Shdr #%d: sh_name (%d) is beyond the end of the section header string table (%d)!",
2040 pszLogName, iShdr, pShdr->sh_name, pModElf->cbShStr);
2041
2042 if (pShdr->sh_link >= pModElf->Ehdr.e_shnum)
2043 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2044 "%s: Shdr #%d: sh_link (%d) is beyond the end of the section table (%d)!",
2045 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2046
2047 switch (pShdr->sh_type)
2048 {
2049 /** @todo find specs and check up which sh_info fields indicates section table entries */
2050 case 12301230:
2051 if (pShdr->sh_info >= pModElf->Ehdr.e_shnum)
2052 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2053 "%s: Shdr #%d: sh_info (%d) is beyond the end of the section table (%d)!",
2054 pszLogName, iShdr, pShdr->sh_link, pModElf->Ehdr.e_shnum);
2055 break;
2056
2057 case SHT_NULL:
2058 break;
2059 case SHT_PROGBITS:
2060 case SHT_SYMTAB:
2061 case SHT_STRTAB:
2062 case SHT_RELA:
2063 case SHT_HASH:
2064 case SHT_DYNAMIC:
2065 case SHT_NOTE:
2066 case SHT_NOBITS:
2067 case SHT_REL:
2068 case SHT_SHLIB:
2069 case SHT_DYNSYM:
2070 /*
2071 * For these types sh_info doesn't have any special meaning, or anything which
2072 * we need/can validate now.
2073 */
2074 break;
2075
2076
2077 default:
2078 Log(("RTLdrELF: %s: Warning, unknown type %d!\n", pszLogName, pShdr->sh_type));
2079 break;
2080 }
2081
2082 if ( pShdr->sh_type != SHT_NOBITS
2083 && pShdr->sh_size)
2084 {
2085 uint64_t offEnd = pShdr->sh_offset + pShdr->sh_size;
2086 if ( offEnd > cbRawImage
2087 || offEnd < (uint64_t)pShdr->sh_offset)
2088 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2089 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD " = %RX64) is beyond the end of the file (%RX64)!",
2090 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size, offEnd, cbRawImage);
2091 if (pShdr->sh_offset < sizeof(Elf_Ehdr))
2092 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2093 "%s: Shdr #%d: sh_offset (" FMT_ELF_OFF ") + sh_size (" FMT_ELF_XWORD ") is starting in the ELF header!",
2094 pszLogName, iShdr, pShdr->sh_offset, pShdr->sh_size);
2095 }
2096
2097 return VINF_SUCCESS;
2098}
2099
2100
2101/**
2102 * Process the section headers.
2103 *
2104 * @returns iprt status code.
2105 * @param pModElf Pointer to the module structure.
2106 * @param paShdrs The section headers.
2107 * @param cbRawImage The size of the raw image.
2108 * @param pszLogName The log name.
2109 * @param pErrInfo Where to return extended error info. Optional.
2110 */
2111static int RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(PRTLDRMODELF pModElf, Elf_Shdr *paShdrs, uint64_t cbRawImage,
2112 const char *pszLogName, PRTERRINFO pErrInfo)
2113{
2114 Elf_Addr uNextAddr = 0;
2115 for (unsigned i = 0; i < pModElf->Ehdr.e_shnum; i++)
2116 {
2117 int rc = RTLDRELF_NAME(ValidateSectionHeader)(pModElf, i, cbRawImage, pszLogName, pErrInfo);
2118 if (RT_FAILURE(rc))
2119 return rc;
2120
2121 /*
2122 * We're looking for symbol tables.
2123 */
2124 if (paShdrs[i].sh_type == SHT_SYMTAB)
2125 {
2126 if (pModElf->Rel.iSymSh != ~0U)
2127 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2128 "%s: Multiple symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Rel.iSymSh, i);
2129 pModElf->Rel.iSymSh = i;
2130 pModElf->Rel.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2131 AssertBreakStmt(pModElf->Rel.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2132 pModElf->Rel.iStrSh = paShdrs[i].sh_link;
2133 pModElf->Rel.cbStr = (unsigned)paShdrs[pModElf->Rel.iStrSh].sh_size;
2134 AssertBreakStmt(pModElf->Rel.cbStr == paShdrs[pModElf->Rel.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2135 }
2136 else if (paShdrs[i].sh_type == SHT_DYNSYM)
2137 {
2138 if (pModElf->Dyn.iSymSh != ~0U)
2139 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDRELF_MULTIPLE_SYMTABS,
2140 "%s: Multiple dynamic symbol tabs! iSymSh=%d i=%d", pszLogName, pModElf->Dyn.iSymSh, i);
2141 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2142 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2143 "%s: Unexpected SHT_DYNSYM (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2144 pModElf->Dyn.iSymSh = i;
2145 pModElf->Dyn.cSyms = (unsigned)(paShdrs[i].sh_size / sizeof(Elf_Sym));
2146 AssertBreakStmt(pModElf->Dyn.cSyms == paShdrs[i].sh_size / sizeof(Elf_Sym), rc = VERR_IMAGE_TOO_BIG);
2147 pModElf->Dyn.iStrSh = paShdrs[i].sh_link;
2148 pModElf->Dyn.cbStr = (unsigned)paShdrs[pModElf->Dyn.iStrSh].sh_size;
2149 AssertBreakStmt(pModElf->Dyn.cbStr == paShdrs[pModElf->Dyn.iStrSh].sh_size, rc = VERR_IMAGE_TOO_BIG);
2150 }
2151 /*
2152 * We're also look for the dynamic section.
2153 */
2154 else if (paShdrs[i].sh_type == SHT_DYNAMIC)
2155 {
2156 if (pModElf->iShDynamic != ~0U)
2157 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2158 "%s: Multiple dynamic sections! iShDynamic=%d i=%d",
2159 pszLogName, pModElf->iShDynamic, i);
2160 if (pModElf->Ehdr.e_type != ET_DYN && pModElf->Ehdr.e_type != ET_EXEC)
2161 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2162 "%s: Unexpected SHT_DYNAMIC (i=%d) for e_type=%d", pszLogName, i, pModElf->Ehdr.e_type);
2163 if (paShdrs[i].sh_entsize != sizeof(Elf_Dyn))
2164 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2165 "%s: SHT_DYNAMIC (i=%d) sh_entsize=" FMT_ELF_XWORD ", expected %#zx",
2166 pszLogName, i, paShdrs[i].sh_entsize, sizeof(Elf_Dyn));
2167 pModElf->iShDynamic = i;
2168 Elf_Xword const cDynamic = paShdrs[i].sh_size / sizeof(Elf_Dyn);
2169 if (cDynamic > _64K || cDynamic < 2)
2170 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2171 "%s: SHT_DYNAMIC (i=%d) sh_size=" FMT_ELF_XWORD " is out of range (2..64K)",
2172 pszLogName, i, paShdrs[i].sh_size);
2173 pModElf->cDynamic = (unsigned)cDynamic;
2174 }
2175
2176 /*
2177 * Special checks for the section string table.
2178 */
2179 if (i == pModElf->Ehdr.e_shstrndx)
2180 {
2181 if (paShdrs[i].sh_type != SHT_STRTAB)
2182 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2183 "%s: Section header string table is not a SHT_STRTAB: %#x",
2184 pszLogName, paShdrs[i].sh_type);
2185 if (paShdrs[i].sh_size == 0)
2186 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Section header string table is empty", pszLogName);
2187 }
2188
2189 /*
2190 * Kluge for the .data..percpu segment in 64-bit linux kernels.
2191 */
2192 if (paShdrs[i].sh_flags & SHF_ALLOC)
2193 {
2194 if ( paShdrs[i].sh_addr == 0
2195 && paShdrs[i].sh_addr < uNextAddr)
2196 {
2197 Elf_Addr uAddr = RT_ALIGN_T(uNextAddr, paShdrs[i].sh_addralign, Elf_Addr);
2198 Log(("RTLdrElf: Out of order section #%d; adjusting sh_addr from " FMT_ELF_ADDR " to " FMT_ELF_ADDR "\n",
2199 i, paShdrs[i].sh_addr, uAddr));
2200 paShdrs[i].sh_addr = uAddr;
2201 }
2202 uNextAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2203 }
2204 } /* for each section header */
2205
2206 return VINF_SUCCESS;
2207}
2208
2209
2210/**
2211 * Process the section headers.
2212 *
2213 * @returns iprt status code.
2214 * @param pModElf Pointer to the module structure.
2215 * @param paShdrs The section headers.
2216 * @param cbRawImage The size of the raw image.
2217 * @param pszLogName The log name.
2218 * @param pErrInfo Where to return extended error info. Optional.
2219 */
2220static int RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(PRTLDRMODELF pModElf, uint64_t cbRawImage, uint32_t fFlags,
2221 const char *pszLogName, PRTERRINFO pErrInfo)
2222{
2223 /*
2224 * Check preconditions.
2225 */
2226 AssertReturn(pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC, VERR_INTERNAL_ERROR_2);
2227 if (pModElf->Ehdr.e_phnum <= 1 || pModElf->Ehdr.e_phnum >= _32K)
2228 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2229 "%s: e_phnum=%u is out of bounds (2..32K)", pszLogName, pModElf->Ehdr.e_phnum);
2230 if (pModElf->iShDynamic == ~0U)
2231 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: no .dynamic section", pszLogName);
2232 AssertReturn(pModElf->cDynamic > 1 && pModElf->cDynamic <= _64K, VERR_INTERNAL_ERROR_3);
2233
2234 /* ASSUME that the sections are ordered by address. That simplifies
2235 validation code further down. */
2236 AssertReturn(pModElf->Ehdr.e_shnum >= 2, VERR_INTERNAL_ERROR_4);
2237 Elf_Shdr const *paShdrs = pModElf->paShdrs;
2238 Elf_Addr uPrevEnd = paShdrs[1].sh_addr + paShdrs[1].sh_size;
2239 for (unsigned i = 2; i < pModElf->Ehdr.e_shnum; i++)
2240 if (paShdrs[i].sh_flags & SHF_ALLOC)
2241 {
2242 if (uPrevEnd > paShdrs[i].sh_addr)
2243 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2244 "%s: section %u is out of order: uPrevEnd=" FMT_ELF_ADDR " sh_addr=" FMT_ELF_ADDR,
2245 pszLogName, i, uPrevEnd, paShdrs[i].sh_addr);
2246 uPrevEnd = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2247 }
2248
2249 /* Must have string and symbol tables. */
2250 if (pModElf->Dyn.iStrSh == ~0U)
2251 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic string table section", pszLogName);
2252 if (pModElf->Dyn.iSymSh == ~0U)
2253 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: No dynamic symbol table section", pszLogName);
2254
2255 /*
2256 * Load the program headers.
2257 */
2258 size_t const cbPhdrs = sizeof(pModElf->paPhdrs[0]) * pModElf->Ehdr.e_phnum;
2259 Elf_Phdr *paPhdrs = (Elf_Phdr *)RTMemAllocZ(cbPhdrs);
2260 pModElf->paPhdrs = paPhdrs;
2261 AssertReturn(paPhdrs, VERR_NO_MEMORY);
2262
2263 int rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paPhdrs, cbPhdrs, pModElf->Ehdr.e_phoff);
2264 if (RT_FAILURE(rc))
2265 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2266 pszLogName, cbPhdrs, pModElf->Ehdr.e_phoff, rc);
2267
2268 /*
2269 * Validate them.
2270 */
2271 unsigned cbPage = _4K; /** @todo generalize architecture specific stuff using its own code template header. */
2272 switch (pModElf->Core.enmArch)
2273 {
2274 case RTLDRARCH_AMD64:
2275 case RTLDRARCH_X86_32:
2276 break;
2277 default:
2278 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2279 }
2280 unsigned iLoad = 0;
2281 unsigned iLoadShdr = 1; /* ASSUMES ordered (checked above). */
2282 unsigned cDynamic = 0;
2283 Elf_Addr cbImage = 0;
2284 Elf_Addr uLinkAddress = ~(Elf_Addr)0;
2285 for (unsigned i = 0; i < pModElf->Ehdr.e_phnum; i++)
2286 {
2287 const Elf_Phdr * const pPhdr = &paPhdrs[i];
2288 Log3(("RTLdrELF: Program Header #%d:\n"
2289 "RTLdrELF: p_type: " FMT_ELF_WORD " (%s)\n"
2290 "RTLdrELF: p_flags: " FMT_ELF_WORD "\n"
2291 "RTLdrELF: p_offset: " FMT_ELF_OFF "\n"
2292 "RTLdrELF: p_vaddr: " FMT_ELF_ADDR "\n"
2293 "RTLdrELF: p_paddr: " FMT_ELF_ADDR "\n"
2294 "RTLdrELF: p_filesz: " FMT_ELF_XWORD "\n"
2295 "RTLdrELF: p_memsz: " FMT_ELF_XWORD "\n"
2296 "RTLdrELF: p_align: " FMT_ELF_XWORD "\n",
2297 i,
2298 pPhdr->p_type, rtldrElfGetPhdrType(pPhdr->p_type), pPhdr->p_flags, pPhdr->p_offset,
2299 pPhdr->p_vaddr, pPhdr->p_paddr, pPhdr->p_filesz, pPhdr->p_memsz, pPhdr->p_align));
2300
2301 if (pPhdr->p_type == DT_NULL)
2302 continue;
2303
2304 if ( pPhdr->p_filesz != 0
2305 && ( pPhdr->p_offset >= cbRawImage
2306 || pPhdr->p_filesz > cbRawImage
2307 || pPhdr->p_offset + pPhdr->p_filesz > cbRawImage))
2308 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2309 "%s: Prog Hdr #%u: bogus p_offset=" FMT_ELF_OFF " & p_filesz=" FMT_ELF_XWORD " (file size %#RX64)",
2310 pszLogName, i, pPhdr->p_offset, pPhdr->p_filesz, cbRawImage);
2311
2312 if (pPhdr->p_flags & ~(Elf64_Word)(PF_X | PF_R | PF_W))
2313 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_flags=" FMT_ELF_WORD,
2314 pszLogName, i, pPhdr->p_flags);
2315
2316 if (!RT_IS_POWER_OF_TWO(pPhdr->p_align))
2317 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Prog Hdr #%u: bogus p_align=" FMT_ELF_XWORD,
2318 pszLogName, i, pPhdr->p_align);
2319
2320 if ( pPhdr->p_align > 1
2321 && pPhdr->p_memsz > 0
2322 && pPhdr->p_filesz > 0
2323 && (pPhdr->p_offset & (pPhdr->p_align - 1)) != (pPhdr->p_vaddr & (pPhdr->p_align - 1)))
2324 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2325 "%s: Prog Hdr #%u: misaligned p_offset=" FMT_ELF_OFF " p_vaddr=" FMT_ELF_ADDR " p_align=" FMT_ELF_XWORD,
2326 pszLogName, i, pPhdr->p_offset, pPhdr->p_vaddr, pPhdr->p_align);
2327
2328 /* Do some type specfic checks: */
2329 switch (pPhdr->p_type)
2330 {
2331 case PT_LOAD:
2332 {
2333 if (pPhdr->p_memsz < pPhdr->p_filesz)
2334 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2335 "%s: Prog Hdr #%u/LOAD#%u: bogus p_memsz=" FMT_ELF_XWORD " or p_filesz=" FMT_ELF_XWORD,
2336 pszLogName, i, iLoad, pPhdr->p_memsz, pPhdr->p_filesz);
2337 cbImage = pPhdr->p_vaddr + pPhdr->p_memsz;
2338 if (iLoad == 0)
2339 uLinkAddress = pPhdr->p_vaddr;
2340
2341 /* Find the corresponding sections, checking their addresses and
2342 file offsets since the rest of the code is still section based
2343 rather than using program headers as it should... */
2344 Elf_Off off = pPhdr->p_offset;
2345 Elf_Addr uAddr = pPhdr->p_vaddr;
2346 Elf_Xword cbMem = pPhdr->p_memsz;
2347 Elf_Xword cbFile = pPhdr->p_filesz;
2348 while (cbMem > 0)
2349 {
2350 if (iLoadShdr < pModElf->Ehdr.e_shnum)
2351 { /* likely */ }
2352 else if (iLoadShdr == pModElf->Ehdr.e_shnum)
2353 {
2354 /** @todo anything else to check here? */
2355 iLoadShdr++;
2356 break;
2357 }
2358 else
2359 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2360 "%s: Prog Hdr #%u/LOAD#%u: Out of sections at " FMT_ELF_ADDR " LB " FMT_ELF_XWORD,
2361 pszLogName, i, iLoad, uAddr, cbMem);
2362 if (!(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC))
2363 {
2364 if ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2365 && paShdrs[iLoadShdr].sh_size > 0
2366 && off < paShdrs[iLoadShdr].sh_offset + paShdrs[iLoadShdr].sh_size
2367 && paShdrs[iLoadShdr].sh_offset < off + cbMem)
2368 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2369 "%s: Prog Hdr #%u/LOAD#%u: Overlaps with !SHF_ALLOC section at " FMT_ELF_OFF " LB " FMT_ELF_XWORD,
2370 pszLogName, i, iLoad, paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_size);
2371 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2372 iLoadShdr++;
2373 continue;
2374 }
2375
2376 if (uAddr != paShdrs[iLoadShdr].sh_addr)
2377 {
2378 /* Before the first section we expect headers to be loaded, so
2379 that the file is simply mapped from file offset zero. */
2380 if ( iLoadShdr == 1
2381 && iLoad == 0
2382 && paShdrs[1].sh_addr == paShdrs[1].sh_offset
2383 && cbFile >= paShdrs[1].sh_offset
2384 && cbMem >= paShdrs[1].sh_offset)
2385 {
2386 /* Modify paShdrs[0] to describe the gap. ".elf.headers" */
2387 pModElf->iFirstSect = 0;
2388 pModElf->paShdrs[0].sh_name = 0;
2389 pModElf->paShdrs[0].sh_type = SHT_PROGBITS;
2390 pModElf->paShdrs[0].sh_flags = SHF_ALLOC
2391 | (pPhdr->p_flags & PF_W ? SHF_WRITE : 0)
2392 | (pPhdr->p_flags & PF_X ? SHF_EXECINSTR : 0);
2393 pModElf->paShdrs[0].sh_addr = uAddr;
2394 pModElf->paShdrs[0].sh_offset = off;
2395 pModElf->paShdrs[0].sh_size = paShdrs[1].sh_offset;
2396 pModElf->paShdrs[0].sh_link = 0;
2397 pModElf->paShdrs[0].sh_info = 0;
2398 pModElf->paShdrs[0].sh_addralign = pPhdr->p_align;
2399 pModElf->paShdrs[0].sh_entsize = 0;
2400 *(Elf_Shdr *)pModElf->paOrgShdrs = pModElf->paShdrs[0]; /* (necessary for segment enumeration) */
2401
2402 uAddr += paShdrs[1].sh_offset;
2403 cbMem -= paShdrs[1].sh_offset;
2404 cbFile -= paShdrs[1].sh_offset;
2405 off = paShdrs[1].sh_offset;
2406 }
2407 /* Alignment padding? Allow up to a page size. */
2408 else if ( paShdrs[iLoadShdr].sh_addr > uAddr
2409 && paShdrs[iLoadShdr].sh_addr - uAddr
2410 < RT_MAX(paShdrs[iLoadShdr].sh_addralign, cbPage /*got.plt hack*/))
2411 {
2412 Elf_Xword cbAlignPadding = paShdrs[iLoadShdr].sh_addr - uAddr;
2413 if (cbAlignPadding >= cbMem)
2414 break;
2415 cbMem -= cbAlignPadding;
2416 uAddr += cbAlignPadding;
2417 if (cbFile > cbAlignPadding)
2418 {
2419 off += cbAlignPadding;
2420 cbFile -= cbAlignPadding;
2421 }
2422 else
2423 {
2424 off += cbFile;
2425 cbFile = 0;
2426 }
2427 }
2428 }
2429
2430 if ( uAddr == paShdrs[iLoadShdr].sh_addr
2431 && cbMem >= paShdrs[iLoadShdr].sh_size
2432 && ( paShdrs[iLoadShdr].sh_type != SHT_NOBITS
2433 ? off == paShdrs[iLoadShdr].sh_offset
2434 && cbFile >= paShdrs[iLoadShdr].sh_size /* this might be too strict... */
2435 : cbFile == 0) )
2436 {
2437 if (paShdrs[iLoadShdr].sh_type != SHT_NOBITS)
2438 {
2439 off += paShdrs[iLoadShdr].sh_size;
2440 cbFile -= paShdrs[iLoadShdr].sh_size;
2441 }
2442 uAddr += paShdrs[iLoadShdr].sh_size;
2443 cbMem -= paShdrs[iLoadShdr].sh_size;
2444 }
2445 else
2446 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2447 "%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 ")",
2448 pszLogName, i, iLoad, uAddr, cbMem, off, cbFile,
2449 iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2450 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2451
2452 pModElf->paShdrExtras[iLoadShdr].idxPhdr = iLoad;
2453 iLoadShdr++;
2454 } /* section loop */
2455
2456 iLoad++;
2457 break;
2458 }
2459
2460 case PT_DYNAMIC:
2461 {
2462 const Elf_Shdr *pShdr = &pModElf->paShdrs[pModElf->iShDynamic];
2463 if (pPhdr->p_offset != pShdr->sh_offset)
2464 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2465 "%s: Prog Hdr #%u/DYNAMIC: p_offset=" FMT_ELF_OFF " expected " FMT_ELF_OFF,
2466 pszLogName, i, pPhdr->p_offset, pShdr->sh_offset);
2467 if (RT_MAX(pPhdr->p_memsz, pPhdr->p_filesz) != pShdr->sh_size)
2468 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2469 "%s: Prog Hdr #%u/DYNAMIC: expected " FMT_ELF_XWORD " for RT_MAX(p_memsz=" FMT_ELF_XWORD ", p_filesz=" FMT_ELF_XWORD ")",
2470 pszLogName, i, pShdr->sh_size, pPhdr->p_memsz, pPhdr->p_filesz);
2471 cDynamic++;
2472 break;
2473 }
2474 }
2475 }
2476
2477 if (iLoad == 0)
2478 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No PT_LOAD program headers", pszLogName);
2479 if (cDynamic != 1)
2480 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: No program header for the DYNAMIC section", pszLogName);
2481
2482 cbImage -= uLinkAddress;
2483 pModElf->cbImage = (uint64_t)cbImage;
2484 pModElf->LinkAddress = uLinkAddress;
2485 AssertReturn(pModElf->cbImage == cbImage, VERR_INTERNAL_ERROR_5);
2486 Log3(("RTLdrELF: LinkAddress=" FMT_ELF_ADDR " cbImage=" FMT_ELF_ADDR " (from PT_LOAD)\n", uLinkAddress, cbImage));
2487
2488 for (; iLoadShdr < pModElf->Ehdr.e_shnum; iLoadShdr++)
2489 if ( !(paShdrs[iLoadShdr].sh_flags & SHF_ALLOC)
2490 || paShdrs[iLoadShdr].sh_size == 0)
2491 pModElf->paShdrExtras[iLoadShdr].idxPhdr = UINT16_MAX;
2492 else
2493 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2494 "%s: No PT_LOAD for section #%u " FMT_ELF_ADDR " LB " FMT_ELF_XWORD " (file " FMT_ELF_OFF " sh_type=" FMT_ELF_WORD ")",
2495 pszLogName, iLoadShdr, paShdrs[iLoadShdr].sh_addr, paShdrs[iLoadShdr].sh_size,
2496 paShdrs[iLoadShdr].sh_offset, paShdrs[iLoadShdr].sh_type);
2497
2498 /*
2499 * Load and validate the dynamic table. We have got / will get most of the
2500 * info we need from the section table, so we must make sure this matches up.
2501 */
2502 Log3(("RTLdrELF: Dynamic section - %u entries\n", pModElf->cDynamic));
2503 size_t const cbDynamic = pModElf->cDynamic * sizeof(pModElf->paDynamic[0]);
2504 Elf_Dyn * const paDynamic = (Elf_Dyn *)RTMemAlloc(cbDynamic);
2505 AssertReturn(paDynamic, VERR_NO_MEMORY);
2506 pModElf->paDynamic = paDynamic;
2507
2508 rc = pModElf->Core.pReader->pfnRead(pModElf->Core.pReader, paDynamic, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset);
2509 if (RT_FAILURE(rc))
2510 return RTERRINFO_LOG_SET_F(pErrInfo, rc, "%s: pfnRead(,,%#zx, " FMT_ELF_OFF ") -> %Rrc",
2511 pszLogName, cbDynamic, paShdrs[pModElf->iShDynamic].sh_offset, rc);
2512
2513 for (uint32_t i = 0; i < pModElf->cDynamic; i++)
2514 {
2515#define LOG_VALIDATE_PTR_RET(szName) do { \
2516 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, paDynamic[i].d_un.d_ptr)); \
2517 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress < cbImage) { /* likely */ } \
2518 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 ")", \
2519 pszLogName, i, paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage); \
2520 } while (0)
2521#define LOG_VALIDATE_PTR_VAL_RET(szName, uExpected) do { \
2522 Log3(("RTLdrELF: DT[%u]: %16s " FMT_ELF_ADDR "\n", i, szName, (uint64_t)paDynamic[i].d_un.d_ptr)); \
2523 if (paDynamic[i].d_un.d_ptr == (Elf_Addr)(uExpected)) { /* likely */ } \
2524 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": " FMT_ELF_ADDR ", expected " FMT_ELF_ADDR, \
2525 pszLogName, i, paDynamic[i].d_un.d_ptr, (Elf_Addr)(uExpected)); \
2526 } while (0)
2527#define LOG_VALIDATE_STR_RET(szName) do { \
2528 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2529 if ((uint64_t)paDynamic[i].d_un.d_val < pModElf->Dyn.cbStr) { /* likely */ } \
2530 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": Invalid string table offset %#RX64 (max %#x)", \
2531 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, pModElf->Dyn.cbStr); \
2532 } while (0)
2533#define LOG_VALIDATE_VAL_RET(szName, uExpected) do { \
2534 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, szName, (uint64_t)paDynamic[i].d_un.d_val)); \
2535 if ((uint64_t)paDynamic[i].d_un.d_val == (uint64_t)(uExpected)) { /* likely */ } \
2536 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" szName ": %#RX64, expected %#RX64", \
2537 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val, (uint64_t)(uExpected)); \
2538 } while (0)
2539#define SET_RELOC_TYPE_RET(a_szName, a_uType) do { \
2540 if (pModElf->DynInfo.uRelocType == 0 || pModElf->DynInfo.uRelocType == (a_uType)) \
2541 pModElf->DynInfo.uRelocType = (a_uType); \
2542 else return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Mixing DT_RELA and DT_REL", pszLogName, i); \
2543 } while (0)
2544#define SET_INFO_FIELD_RET(a_szName, a_Field, a_Value, a_UnsetValue, a_szFmt) do { \
2545 if ((a_Field) == (a_UnsetValue) && (a_Value) != (a_UnsetValue)) \
2546 (a_Field) = (a_Value); /* likely */ \
2547 else if ((a_Field) != (a_UnsetValue)) \
2548 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)); \
2549 else if ((a_Value) != (a_UnsetValue)) \
2550 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/" a_szName ": Unexpected value " a_szFmt, pszLogName, i, (a_Value)); \
2551 } while (0)
2552#define FIND_MATCHING_SECTION_RET(a_szName, a_ExtraMatchExpr, a_idxShFieldToSet) do { \
2553 unsigned iSh; \
2554 for (iSh = 1; iSh < pModElf->Ehdr.e_shnum; iSh++) \
2555 if ( paShdrs[iSh].sh_addr == paDynamic[i].d_un.d_ptr \
2556 && (a_ExtraMatchExpr)) \
2557 { \
2558 (a_idxShFieldToSet) = iSh; \
2559 if (pModElf->paShdrExtras[iSh].idxDt != UINT16_MAX) \
2560 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, \
2561 "%s: DT[%u]/" a_szName ": section #%u (" FMT_ELF_ADDR ") already referenced by DT[%u]", \
2562 pszLogName, i, iSh, paShdrs[iSh].sh_addr, pModElf->paShdrExtras[iSh].idxDt); \
2563 pModElf->paShdrExtras[iSh].idxDt = i; \
2564 pModElf->paShdrExtras[iSh].uDtTag = (uint32_t)paDynamic[i].d_tag; \
2565 break; \
2566 } \
2567 if (iSh < pModElf->Ehdr.e_shnum) { /* likely */ } \
2568 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); \
2569 } while (0)
2570#define ONLY_FOR_DEBUG_OR_VALIDATION_RET(a_szName) do { \
2571 if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)) { /* likely */ } \
2572 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); \
2573 } while (0)
2574#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))
2575
2576 switch (paDynamic[i].d_tag)
2577 {
2578 case DT_NULL:
2579 LOG_NON_VALUE_ENTRY("DT_NULL");
2580 for (unsigned iNull = i + 1; iNull < pModElf->cDynamic; iNull++)
2581 if (paDynamic[i].d_tag == DT_NULL) /* Not technically a bug, but let's try being extremely strict for now */
2582 LOG_NON_VALUE_ENTRY("DT_NULL");
2583 else if (!(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
2584 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2585 "%s: DT[%u]/DT_NULL: Dynamic section isn't zero padded (extra #%u of #%u)",
2586 pszLogName, i, iNull - i, pModElf->cDynamic - i);
2587 i = pModElf->cDynamic;
2588 break;
2589 case DT_NEEDED:
2590 LOG_VALIDATE_STR_RET("DT_NEEDED");
2591 break;
2592 case DT_PLTRELSZ:
2593 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PLTRELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2594 SET_INFO_FIELD_RET("DT_PLTRELSZ", pModElf->DynInfo.cbJmpRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2595 break;
2596 case DT_PLTGOT:
2597 LOG_VALIDATE_PTR_RET("DT_PLTGOT");
2598 break;
2599 case DT_HASH:
2600 LOG_VALIDATE_PTR_RET("DT_HASH");
2601 break;
2602 case DT_STRTAB:
2603 LOG_VALIDATE_PTR_VAL_RET("DT_STRTAB", paShdrs[pModElf->Dyn.iStrSh].sh_addr);
2604 pModElf->paShdrExtras[pModElf->Dyn.iStrSh].idxDt = i;
2605 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_STRTAB;
2606 break;
2607 case DT_SYMTAB:
2608 LOG_VALIDATE_PTR_VAL_RET("DT_SYMTAB", paShdrs[pModElf->Dyn.iSymSh].sh_addr);
2609 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].idxDt = i;
2610 pModElf->paShdrExtras[pModElf->Dyn.iSymSh].uDtTag = DT_SYMTAB;
2611 break;
2612 case DT_RELA:
2613 LOG_VALIDATE_PTR_RET("DT_RELA");
2614 SET_RELOC_TYPE_RET("DT_RELA", DT_RELA);
2615 SET_INFO_FIELD_RET("DT_RELA", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2616 FIND_MATCHING_SECTION_RET("DT_RELA", paShdrs[iSh].sh_type == SHT_RELA, pModElf->DynInfo.idxShRelocs);
2617 break;
2618 case DT_RELASZ:
2619 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELASZ", (uint64_t)paDynamic[i].d_un.d_val));
2620 SET_RELOC_TYPE_RET("DT_RELASZ", DT_RELA);
2621 SET_INFO_FIELD_RET("DT_RELASZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2622 break;
2623 case DT_RELAENT:
2624 LOG_VALIDATE_VAL_RET("DT_RELAENT", sizeof(Elf_Rela));
2625 SET_RELOC_TYPE_RET("DT_RELAENT", DT_RELA);
2626 SET_INFO_FIELD_RET("DT_RELAENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rela), 0, "%u");
2627 break;
2628 case DT_STRSZ:
2629 LOG_VALIDATE_VAL_RET("DT_STRSZ", pModElf->Dyn.cbStr);
2630 break;
2631 case DT_SYMENT:
2632 LOG_VALIDATE_VAL_RET("DT_SYMENT", sizeof(Elf_Sym));
2633 break;
2634 case DT_INIT:
2635 LOG_VALIDATE_PTR_RET("DT_INIT");
2636 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT");
2637 break;
2638 case DT_FINI:
2639 LOG_VALIDATE_PTR_RET("DT_FINI");
2640 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI");
2641 break;
2642 case DT_SONAME:
2643 LOG_VALIDATE_STR_RET("DT_SONAME");
2644 break;
2645 case DT_RPATH:
2646 LOG_VALIDATE_STR_RET("DT_RPATH");
2647 break;
2648 case DT_SYMBOLIC:
2649 LOG_NON_VALUE_ENTRY("DT_SYMBOLIC");
2650 break;
2651 case DT_REL:
2652 LOG_VALIDATE_PTR_RET("DT_REL");
2653 SET_RELOC_TYPE_RET("DT_REL", DT_REL);
2654 SET_INFO_FIELD_RET("DT_REL", pModElf->DynInfo.uPtrRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2655 FIND_MATCHING_SECTION_RET("DT_REL", paShdrs[iSh].sh_type == SHT_REL, pModElf->DynInfo.idxShRelocs);
2656 break;
2657 case DT_RELSZ:
2658 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_RELSZ", (uint64_t)paDynamic[i].d_un.d_val));
2659 SET_RELOC_TYPE_RET("DT_RELSZ", DT_REL);
2660 SET_INFO_FIELD_RET("DT_RELSZ", pModElf->DynInfo.cbRelocs, (Elf_Xword)paDynamic[i].d_un.d_val, 0, FMT_ELF_XWORD);
2661 break;
2662 case DT_RELENT:
2663 LOG_VALIDATE_VAL_RET("DT_RELENT", sizeof(Elf_Rel));
2664 SET_RELOC_TYPE_RET("DT_RELENT", DT_REL);
2665 SET_INFO_FIELD_RET("DT_RELENT", pModElf->DynInfo.cbRelocEntry, (unsigned)sizeof(Elf_Rel), 0, "%u");
2666 break;
2667 case DT_PLTREL:
2668 if (paDynamic[i].d_un.d_val != DT_RELA && paDynamic[i].d_un.d_val != DT_REL)
2669 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT[%u]/DT_PLTREL: Invalid value %#RX64",
2670 pszLogName, i, (uint64_t)paDynamic[i].d_un.d_val);
2671 Log3(("RTLdrELF: DT[%u]: %16s DT_REL%s\n", i, "DT_PLTREL", paDynamic[i].d_un.d_val == DT_RELA ? "A" : ""));
2672 SET_INFO_FIELD_RET("DT_PLTREL", pModElf->DynInfo.uJmpRelocType, (unsigned)paDynamic[i].d_un.d_val, 0, "%u");
2673 break;
2674 case DT_DEBUG:
2675 LOG_VALIDATE_PTR_RET("DT_DEBUG");
2676 break;
2677 case DT_TEXTREL:
2678 LOG_NON_VALUE_ENTRY("DT_TEXTREL");
2679 break;
2680 case DT_JMPREL:
2681 LOG_VALIDATE_PTR_RET("DT_JMPREL");
2682 SET_INFO_FIELD_RET("DT_JMPREL", pModElf->DynInfo.uPtrJmpRelocs, paDynamic[i].d_un.d_ptr, ~(Elf_Addr)0, FMT_ELF_ADDR);
2683 FIND_MATCHING_SECTION_RET("DT_JMPREL", 1, pModElf->DynInfo.idxShJmpRelocs);
2684 break;
2685 case DT_BIND_NOW:
2686 LOG_NON_VALUE_ENTRY("DT_BIND_NOW");
2687 break;
2688 case DT_INIT_ARRAY:
2689 LOG_VALIDATE_PTR_RET("DT_INIT_ARRAY");
2690 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAY");
2691 break;
2692 case DT_FINI_ARRAY:
2693 LOG_VALIDATE_PTR_RET("DT_FINI_ARRAY");
2694 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAY");
2695 break;
2696 case DT_INIT_ARRAYSZ:
2697 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_INIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2698 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_INIT_ARRAYSZ");
2699 break;
2700 case DT_FINI_ARRAYSZ:
2701 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_FINI_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2702 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_FINI_ARRAYSZ");
2703 break;
2704 case DT_RUNPATH:
2705 LOG_VALIDATE_STR_RET("DT_RUNPATH");
2706 break;
2707 case DT_FLAGS:
2708 Log3(("RTLdrELF: DT[%u]: %16s %#RX64\n", i, "DT_FLAGS", (uint64_t)paDynamic[i].d_un.d_val));
2709 break;
2710 case DT_PREINIT_ARRAY:
2711 LOG_VALIDATE_PTR_RET("DT_PREINIT_ARRAY");
2712 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAY");
2713 break;
2714 case DT_PREINIT_ARRAYSZ:
2715 Log3(("RTLdrELF: DT[%u]: %16s %#RX64 bytes\n", i, "DT_PREINIT_ARRAYSZ", (uint64_t)paDynamic[i].d_un.d_val));
2716 ONLY_FOR_DEBUG_OR_VALIDATION_RET("DT_PREINIT_ARRAYSZ");
2717 break;
2718 default:
2719 if ( paDynamic[i].d_un.d_val < DT_ENCODING
2720 || (paDynamic[i].d_un.d_val & 1))
2721 Log3(("RTLdrELF: DT[%u]: %#010RX64 %#RX64%s\n", i, (uint64_t)paDynamic[i].d_tag,
2722 (uint64_t)paDynamic[i].d_un.d_val, paDynamic[i].d_un.d_val >= DT_ENCODING ? " (val)" : ""));
2723 else
2724 {
2725 Log3(("RTLdrELF: DT[%u]: %#010RX64 " FMT_ELF_ADDR " (addr)\n",
2726 i, (uint64_t)paDynamic[i].d_tag, paDynamic[i].d_un.d_ptr));
2727 if ((uint64_t)paDynamic[i].d_un.d_ptr - uLinkAddress >= cbImage)
2728 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2729 "%s: DT[%u]/%#RX64: Invalid address " FMT_ELF_ADDR " (valid range: " FMT_ELF_ADDR " LB " FMT_ELF_ADDR ")",
2730 pszLogName, i, (uint64_t)paDynamic[i].d_tag,
2731 paDynamic[i].d_un.d_ptr, uLinkAddress, cbImage);
2732 }
2733 break;
2734 }
2735#undef LOG_VALIDATE_VAL_RET
2736#undef LOG_VALIDATE_STR_RET
2737#undef LOG_VALIDATE_PTR_VAL_RET
2738#undef LOG_VALIDATE_PTR_RET
2739#undef SET_RELOC_TYPE_RET
2740#undef SET_INFO_FIELD_RET
2741#undef FIND_MATCHING_SECTION_RET
2742#undef ONLY_FOR_DEBUG_OR_VALIDATION_RET
2743 }
2744
2745 /*
2746 * Validate the relocation information we've gathered.
2747 */
2748 Elf_Word uShTypeArch = SHT_RELA; /** @todo generalize architecture specific stuff using its own code template header. */
2749 switch (pModElf->Core.enmArch)
2750 {
2751 case RTLDRARCH_AMD64:
2752 break;
2753 case RTLDRARCH_X86_32:
2754 uShTypeArch = SHT_REL;
2755 break;
2756 default:
2757 AssertFailedBreak(/** @todo page size for got.plt hacks */);
2758
2759 }
2760
2761 if (pModElf->DynInfo.uRelocType != 0)
2762 {
2763 const char * const pszModifier = pModElf->DynInfo.uRelocType == DT_RELA ? "A" : "";
2764 if (pModElf->DynInfo.uPtrRelocs == ~(Elf_Addr)0)
2765 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%s", pszLogName, pszModifier);
2766 if (pModElf->DynInfo.cbRelocs == 0)
2767 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sSZ", pszLogName, pszModifier);
2768 if (pModElf->DynInfo.cbRelocEntry == 0)
2769 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_REL%sENT", pszLogName, pszModifier);
2770 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShRelocs];
2771 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2772 if (pShdrRelocs->sh_type != uShType)
2773 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match section type: %u vs %u",
2774 pszLogName, pszModifier, pShdrRelocs->sh_type, uShType);
2775 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbRelocs)
2776 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%sSZ does not match section size: %u vs %u",
2777 pszLogName, pszModifier, pShdrRelocs->sh_size, pModElf->DynInfo.cbRelocs);
2778 if (uShType != uShTypeArch)
2779 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_REL%s* does not match architecture: %u, arch wants %u",
2780 pszLogName, pszModifier, uShType, uShTypeArch);
2781 }
2782
2783 if ( pModElf->DynInfo.uPtrJmpRelocs != ~(Elf_Addr)0
2784 || pModElf->DynInfo.cbJmpRelocs != 0
2785 || pModElf->DynInfo.uJmpRelocType != 0)
2786 {
2787 if (pModElf->DynInfo.uPtrJmpRelocs == ~(Elf_Addr)0)
2788 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_JMPREL", pszLogName);
2789 if (pModElf->DynInfo.cbJmpRelocs == 0)
2790 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTRELSZ", pszLogName);
2791 if (pModElf->DynInfo.uJmpRelocType == 0)
2792 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: Missing DT_PLTREL", pszLogName);
2793 Elf_Shdr const *pShdrRelocs = &paShdrs[pModElf->DynInfo.idxShJmpRelocs];
2794 Elf_Word const uShType = pModElf->DynInfo.uJmpRelocType == DT_RELA ? SHT_RELA : SHT_REL;
2795 if (pShdrRelocs->sh_type != uShType)
2796 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match section type: %u vs %u",
2797 pszLogName, pShdrRelocs->sh_type, uShType);
2798 if (pShdrRelocs->sh_size != pModElf->DynInfo.cbJmpRelocs)
2799 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTRELSZ does not match section size: %u vs %u",
2800 pszLogName, pShdrRelocs->sh_size, pModElf->DynInfo.cbJmpRelocs);
2801 if (uShType != uShTypeArch)
2802 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "%s: DT_PLTREL does not match architecture: %u, arch wants %u",
2803 pszLogName, uShType, uShTypeArch);
2804 }
2805
2806 /*
2807 * Check that there aren't any other relocations hiding in the section table.
2808 */
2809 for (uint32_t i = 1; i < pModElf->Ehdr.e_shnum; i++)
2810 if ( (paShdrs[i].sh_type == SHT_REL || paShdrs[i].sh_type == SHT_RELA)
2811 && pModElf->paShdrExtras[i].uDtTag != DT_REL
2812 && pModElf->paShdrExtras[i].uDtTag != DT_RELA
2813 && pModElf->paShdrExtras[i].uDtTag != DT_JMPREL)
2814 {
2815 char szSecHdrNm[80];
2816 return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
2817 "%s: section header #%u (%s type=" FMT_ELF_WORD " size=" FMT_ELF_XWORD ") contains relocations not referenced by the dynamic section",
2818 pszLogName, i,
2819 RTLDRELF_NAME(GetSHdrName)(pModElf, paShdrs[i].sh_name, szSecHdrNm, sizeof(szSecHdrNm)),
2820 paShdrs[i].sh_type, paShdrs[i].sh_size);
2821 }
2822
2823 return VINF_SUCCESS;
2824}
2825
2826
2827
2828/**
2829 * Opens an ELF image, fixed bitness.
2830 *
2831 * @returns iprt status code.
2832 * @param pReader The loader reader instance which will provide the raw image bits.
2833 * @param fFlags Reserved, MBZ.
2834 * @param enmArch Architecture specifier.
2835 * @param phLdrMod Where to store the handle.
2836 * @param pErrInfo Where to return extended error info. Optional.
2837 */
2838static int RTLDRELF_NAME(Open)(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
2839{
2840 const char *pszLogName = pReader->pfnLogName(pReader);
2841 uint64_t cbRawImage = pReader->pfnSize(pReader);
2842 RT_NOREF_PV(fFlags);
2843
2844 /*
2845 * Create the loader module instance.
2846 */
2847 PRTLDRMODELF pModElf = (PRTLDRMODELF)RTMemAllocZ(sizeof(*pModElf));
2848 if (!pModElf)
2849 return VERR_NO_MEMORY;
2850
2851 pModElf->Core.u32Magic = RTLDRMOD_MAGIC;
2852 pModElf->Core.eState = LDR_STATE_INVALID;
2853 pModElf->Core.pReader = pReader;
2854 pModElf->Core.enmFormat = RTLDRFMT_ELF;
2855 pModElf->Core.enmType = RTLDRTYPE_OBJECT;
2856 pModElf->Core.enmEndian = RTLDRENDIAN_LITTLE;
2857#if ELF_MODE == 32
2858 pModElf->Core.enmArch = RTLDRARCH_X86_32;
2859#else
2860 pModElf->Core.enmArch = RTLDRARCH_AMD64;
2861#endif
2862 //pModElf->pvBits = NULL;
2863 //pModElf->Ehdr = {0};
2864 //pModElf->paShdrs = NULL;
2865 //pModElf->Rel.paSyms = NULL;
2866 pModElf->Rel.iSymSh = ~0U;
2867 //pModElf->Rel.cSyms = 0;
2868 pModElf->Rel.iStrSh = ~0U;
2869 //pModElf->Rel.cbStr = 0;
2870 //pModElf->Rel.pStr = NULL;
2871 //pModElf->Dyn.paSyms = NULL;
2872 pModElf->Dyn.iSymSh = ~0U;
2873 //pModElf->Dyn.cSyms = 0;
2874 pModElf->Dyn.iStrSh = ~0U;
2875 //pModElf->Dyn.cbStr = 0;
2876 //pModElf->Dyn.pStr = NULL;
2877 //pModElf->iFirstSect = 0;
2878 //pModElf->fShdrInOrder = false;
2879 //pModElf->cbImage = 0;
2880 pModElf->LinkAddress = ~(Elf_Addr)0;
2881 //pModElf->cbShStr = 0;
2882 //pModElf->pShStr = NULL;
2883 //pModElf->iShEhFrame = 0;
2884 //pModElf->iShEhFrameHdr= 0;
2885 pModElf->iShDynamic = ~0U;
2886 //pModElf->cDynamic = 0;
2887 //pModElf->paDynamic = NULL;
2888 //pModElf->paPhdrs = NULL;
2889 pModElf->DynInfo.uPtrRelocs = ~(Elf_Addr)0;
2890 //pModElf->DynInfo.cbRelocs = 0;
2891 //pModElf->DynInfo.cbRelocEntry = 0;
2892 //pModElf->DynInfo.uRelocType = 0;
2893 //pModElf->DynInfo.idxShRelocs = 0;
2894 pModElf->DynInfo.uPtrJmpRelocs = ~(Elf_Addr)0;
2895 //pModElf->DynInfo.cbJmpRelocs = 0;
2896 //pModElf->DynInfo.uJmpRelocType = 0;
2897 //pModElf->DynInfo.idxShJmpRelocs = 0;
2898
2899 /*
2900 * Read and validate the ELF header and match up the CPU architecture.
2901 */
2902 int rc = pReader->pfnRead(pReader, &pModElf->Ehdr, sizeof(pModElf->Ehdr), 0);
2903 if (RT_SUCCESS(rc))
2904 {
2905 RTLDRARCH enmArchImage = RTLDRARCH_INVALID; /* shut up gcc */
2906 rc = RTLDRELF_NAME(ValidateElfHeader)(&pModElf->Ehdr, cbRawImage, pszLogName, &enmArchImage, pErrInfo);
2907 if (RT_SUCCESS(rc))
2908 {
2909 if ( enmArch != RTLDRARCH_WHATEVER
2910 && enmArch != enmArchImage)
2911 rc = VERR_LDR_ARCH_MISMATCH;
2912 }
2913 }
2914 if (RT_SUCCESS(rc))
2915 {
2916 /*
2917 * Read the section headers, keeping a prestine copy for the module
2918 * introspection methods.
2919 */
2920 size_t const cbShdrs = pModElf->Ehdr.e_shnum * sizeof(Elf_Shdr);
2921 Elf_Shdr *paShdrs = (Elf_Shdr *)RTMemAlloc(cbShdrs * 2 + sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2922 if (paShdrs)
2923 {
2924 pModElf->paShdrs = paShdrs;
2925 rc = pReader->pfnRead(pReader, paShdrs, cbShdrs, pModElf->Ehdr.e_shoff);
2926 if (RT_SUCCESS(rc))
2927 {
2928 memcpy(&paShdrs[pModElf->Ehdr.e_shnum], paShdrs, cbShdrs);
2929 pModElf->paOrgShdrs = &paShdrs[pModElf->Ehdr.e_shnum];
2930
2931 pModElf->paShdrExtras = (PRTLDRMODELFSHX)&pModElf->paOrgShdrs[pModElf->Ehdr.e_shnum];
2932 memset(pModElf->paShdrExtras, 0xff, sizeof(RTLDRMODELFSHX) * pModElf->Ehdr.e_shnum);
2933
2934 pModElf->cbShStr = paShdrs[pModElf->Ehdr.e_shstrndx].sh_size;
2935
2936 /*
2937 * Validate the section headers and find relevant sections.
2938 */
2939 rc = RTLDRELF_NAME(ValidateAndProcessSectionHeaders)(pModElf, paShdrs, cbRawImage, pszLogName, pErrInfo);
2940
2941 /*
2942 * Read validate and process program headers if ET_DYN or ET_EXEC.
2943 */
2944 if (RT_SUCCESS(rc) && (pModElf->Ehdr.e_type == ET_DYN || pModElf->Ehdr.e_type == ET_EXEC))
2945 rc = RTLDRELF_NAME(ValidateAndProcessDynamicInfo)(pModElf, cbRawImage, fFlags, pszLogName, pErrInfo);
2946
2947 /*
2948 * Massage the section headers.
2949 */
2950 if (RT_SUCCESS(rc))
2951 {
2952 if (pModElf->Ehdr.e_type == ET_REL)
2953 {
2954 /* Do allocations and figure the image size: */
2955 pModElf->LinkAddress = 0;
2956 for (unsigned i = 1; i < pModElf->Ehdr.e_shnum; i++)
2957 if (paShdrs[i].sh_flags & SHF_ALLOC)
2958 {
2959 paShdrs[i].sh_addr = paShdrs[i].sh_addralign
2960 ? RT_ALIGN_T(pModElf->cbImage, paShdrs[i].sh_addralign, Elf_Addr)
2961 : (Elf_Addr)pModElf->cbImage;
2962 Elf_Addr EndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2963 if (pModElf->cbImage < EndAddr)
2964 {
2965 pModElf->cbImage = (size_t)EndAddr;
2966 AssertMsgBreakStmt(pModElf->cbImage == EndAddr, (FMT_ELF_ADDR "\n", EndAddr), rc = VERR_IMAGE_TOO_BIG);
2967 }
2968 Log2(("RTLdrElf: %s: Assigned " FMT_ELF_ADDR " to section #%d\n", pszLogName, paShdrs[i].sh_addr, i));
2969 }
2970 }
2971 else
2972 {
2973 /* Convert sh_addr to RVA: */
2974 Assert(pModElf->LinkAddress != ~(Elf_Addr)0);
2975 for (unsigned i = 0 /*!*/; i < pModElf->Ehdr.e_shnum; i++)
2976 if (paShdrs[i].sh_flags & SHF_ALLOC)
2977 paShdrs[i].sh_addr -= pModElf->LinkAddress;
2978 }
2979 }
2980
2981 /*
2982 * Check if the sections are in order by address, as that will simplify
2983 * enumeration and address translation.
2984 */
2985 pModElf->fShdrInOrder = true;
2986 Elf_Addr uEndAddr = 0;
2987 for (unsigned i = pModElf->iFirstSect; i < pModElf->Ehdr.e_shnum; i++)
2988 if (paShdrs[i].sh_flags & SHF_ALLOC)
2989 {
2990 if (uEndAddr <= paShdrs[i].sh_addr)
2991 uEndAddr = paShdrs[i].sh_addr + paShdrs[i].sh_size;
2992 else
2993 {
2994 pModElf->fShdrInOrder = false;
2995 break;
2996 }
2997 }
2998
2999 Log2(("RTLdrElf: iSymSh=%u cSyms=%u iStrSh=%u cbStr=%u rc=%Rrc cbImage=%#zx LinkAddress=" FMT_ELF_ADDR " fShdrInOrder=%RTbool\n",
3000 pModElf->Rel.iSymSh, pModElf->Rel.cSyms, pModElf->Rel.iStrSh, pModElf->Rel.cbStr, rc,
3001 pModElf->cbImage, pModElf->LinkAddress, pModElf->fShdrInOrder));
3002 if (RT_SUCCESS(rc))
3003 {
3004 pModElf->Core.pOps = &RTLDRELF_MID(s_rtldrElf,Ops);
3005 pModElf->Core.eState = LDR_STATE_OPENED;
3006 *phLdrMod = &pModElf->Core;
3007
3008 LogFlow(("%s: %s: returns VINF_SUCCESS *phLdrMod=%p\n", __FUNCTION__, pszLogName, *phLdrMod));
3009 return VINF_SUCCESS;
3010 }
3011 }
3012
3013 RTMemFree(paShdrs);
3014 }
3015 else
3016 rc = VERR_NO_MEMORY;
3017 }
3018
3019 RTMemFree(pModElf);
3020 LogFlow(("%s: returns %Rrc\n", __FUNCTION__, rc));
3021 return rc;
3022}
3023
3024
3025
3026
3027/*******************************************************************************
3028* Cleanup Constants And Macros *
3029*******************************************************************************/
3030#undef RTLDRELF_NAME
3031#undef RTLDRELF_SUFF
3032#undef RTLDRELF_MID
3033
3034#undef FMT_ELF_ADDR
3035#undef FMT_ELF_ADDR7
3036#undef FMT_ELF_HALF
3037#undef FMT_ELF_SHALF
3038#undef FMT_ELF_OFF
3039#undef FMT_ELF_SIZE
3040#undef FMT_ELF_SWORD
3041#undef FMT_ELF_WORD
3042#undef FMT_ELF_XWORD
3043#undef FMT_ELF_SXWORD
3044
3045#undef Elf_Ehdr
3046#undef Elf_Phdr
3047#undef Elf_Shdr
3048#undef Elf_Sym
3049#undef Elf_Rel
3050#undef Elf_Rela
3051#undef Elf_Reloc
3052#undef Elf_Nhdr
3053#undef Elf_Dyn
3054
3055#undef Elf_Addr
3056#undef Elf_Half
3057#undef Elf_Off
3058#undef Elf_Size
3059#undef Elf_Sword
3060#undef Elf_Word
3061#undef Elf_Xword
3062#undef Elf_Sxword
3063
3064#undef RTLDRMODELF
3065#undef PRTLDRMODELF
3066
3067#undef ELF_R_SYM
3068#undef ELF_R_TYPE
3069#undef ELF_R_INFO
3070
3071#undef ELF_ST_BIND
3072
Note: See TracBrowser for help on using the repository browser.

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