1 /******************************************************************************
2  * libelf.h
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to
6  * deal in the Software without restriction, including without limitation the
7  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8  * sell copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  */
22 
23 #ifndef __XEN_LIBELF_H__
24 #define __XEN_LIBELF_H__
25 
26 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
27 #define XEN_ELF_LITTLE_ENDIAN
28 #else
29 #error define architectural endianness
30 #endif
31 
32 typedef int elf_errorstatus; /* 0: ok; -ve (normally -1): error */
33 typedef int elf_negerrnoval; /* 0: ok; -EFOO: error */
34 
35 #undef ELFSIZE
36 #include "elfstructs.h"
37 #ifdef __XEN__
38 #include <public/elfnote.h>
39 #include <public/features.h>
40 #include <xen/stdbool.h>
41 #include <xen/string.h>
42 #else
43 #include <xen/elfnote.h>
44 #include <xen/features.h>
45 
46 #include <stdarg.h>
47 #include <stdbool.h>
48 #include <string.h>
49 
50 struct elf_binary;
51 typedef void elf_log_callback(struct elf_binary*, void *caller_data,
52                               bool iserr, const char *fmt, va_list al);
53 
54 #endif
55 
56 #define ELF_MAX_STRING_LENGTH 4096
57 #define ELF_MAX_TOTAL_NOTE_COUNT 65536
58 
59 /* ------------------------------------------------------------------------ */
60 
61 /* Macros for accessing the input image and output area. */
62 
63 /*
64  * We abstract away the pointerness of these pointers, replacing
65  * various void*, char* and struct* with the following:
66  *   elf_ptrval  A pointer to a byte; one can do pointer arithmetic
67  *               on this.
68  *   HANDLE      A pointer to a struct.  There is one of these types
69  *               for each pointer type - that is, for each "structname".
70  *               In the arguments to the various HANDLE macros, structname
71  *               must be a single identifier which is a typedef.
72  *               It is not permitted to do arithmetic on these
73  *               pointers.  In the current code attempts to do so will
74  *               compile, but in the next patch this will become a
75  *               compile error.
76  */
77 
78 typedef uintptr_t elf_ptrval;
79 
80 #define ELF_REALPTR2PTRVAL(realpointer) ((elf_ptrval)(realpointer))
81   /* Converts an actual C pointer into a PTRVAL */
82 
83 #define ELF_HANDLE_DECL(structname)          structname##_handle
84   /* Provides a type declaration for a HANDLE. */
85 
86 #define ELF_PRPTRVAL PRIxPTR
87   /* printf format a la PRId... for a PTRVAL */
88 
89 #define ELF_DEFINE_HANDLE(structname)                                   \
90     typedef union {                                                     \
91         elf_ptrval ptrval;                                              \
92         const structname *typeonly; /* for sizeof, offsetof, &c only */ \
93     } structname##_handle;
94   /*
95    * This must be invoked for each HANDLE type to define
96    * the actual C type used for that kind of HANDLE.
97    */
98 
99 #define ELF_MAKE_HANDLE(structname, ptrval)    ((structname##_handle){ ptrval })
100   /* Converts a PTRVAL to a HANDLE */
101 
102 #define ELF_IMAGE_BASE(elf)    ((elf_ptrval)(elf)->image_base)
103   /* Returns the base of the image as a PTRVAL. */
104 
105 #define ELF_HANDLE_PTRVAL(handleval)      ((handleval).ptrval)
106   /* Converts a HANDLE to a PTRVAL. */
107 
108 #define ELF_UNSAFE_PTR(ptrval) ((void*)(elf_ptrval)(ptrval))
109   /*
110    * Turns a PTRVAL into an actual C pointer.  Before this is done
111    * the caller must have ensured that the PTRVAL does in fact point
112    * to a permissible location.
113    */
114 
115 /* PTRVALs can be INVALID (ie, NULL). */
116 #define ELF_INVALID_PTRVAL    ((elf_ptrval)0)       /* returns NULL PTRVAL */
117 #define ELF_INVALID_HANDLE(structname)		    /* returns NULL handle */ \
118     ELF_MAKE_HANDLE(structname, ELF_INVALID_PTRVAL)
119 #define ELF_PTRVAL_VALID(ptrval)    (!!(ptrval))            /* }            */
120 #define ELF_HANDLE_VALID(handleval) (!!(handleval).ptrval)  /* } predicates */
121 #define ELF_PTRVAL_INVALID(ptrval)  (!ELF_PTRVAL_VALID((ptrval))) /* }      */
122 
123 #define ELF_MAX_PTRVAL        (~(elf_ptrval)0)
124   /* PTRVAL value guaranteed to compare > to any valid PTRVAL */
125 
126 /* For internal use by other macros here */
127 #define ELF__HANDLE_FIELD_TYPE(handleval, elm) \
128   typeof((handleval).typeonly->elm)
129 #define ELF__HANDLE_FIELD_OFFSET(handleval, elm) \
130   offsetof(typeof(*(handleval).typeonly),elm)
131 
132 
133 /* ------------------------------------------------------------------------ */
134 
135 
136 typedef union {
137     Elf32_Ehdr e32;
138     Elf64_Ehdr e64;
139 } elf_ehdr;
140 
141 typedef union {
142     Elf32_Phdr e32;
143     Elf64_Phdr e64;
144 } elf_phdr;
145 
146 typedef union {
147     Elf32_Shdr e32;
148     Elf64_Shdr e64;
149 } elf_shdr;
150 
151 typedef union {
152     Elf32_Sym e32;
153     Elf64_Sym e64;
154 } elf_sym;
155 
156 typedef union {
157     Elf32_Rel e32;
158     Elf64_Rel e64;
159 } elf_rel;
160 
161 typedef union {
162     Elf32_Rela e32;
163     Elf64_Rela e64;
164 } elf_rela;
165 
166 typedef union {
167     Elf32_Note e32;
168     Elf64_Note e64;
169 } elf_note;
170 
171 ELF_DEFINE_HANDLE(elf_ehdr)
172 ELF_DEFINE_HANDLE(elf_shdr)
173 ELF_DEFINE_HANDLE(elf_phdr)
174 ELF_DEFINE_HANDLE(elf_sym)
175 ELF_DEFINE_HANDLE(elf_note)
176 
177 struct elf_binary {
178     /* elf binary */
179     const void *image_base;
180     size_t size;
181     char class;
182     char data;
183 
184     ELF_HANDLE_DECL(elf_ehdr) ehdr;
185     elf_ptrval sec_strtab;
186     ELF_HANDLE_DECL(elf_shdr) sym_tab;
187     uint64_t sym_strtab;
188 
189     /* loaded to */
190     /*
191      * dest_base and dest_size are trusted and must be correct;
192      * whenever dest_size is not 0, both of these must be valid
193      * so long as the struct elf_binary is in use.
194      */
195     char *dest_base;
196     size_t dest_size;
197     uint64_t pstart;
198     uint64_t pend;
199     uint64_t reloc_offset;
200 
201     uint64_t bsd_symtab_pstart;
202     uint64_t bsd_symtab_pend;
203 
204     /*
205      * caller's other acceptable destination.
206      * Set by elf_set_xdest.  Do not set these directly.
207      */
208     void *xdest_base;
209     uint64_t xdest_size;
210 
211 #ifndef __XEN__
212     /* misc */
213     elf_log_callback *log_callback;
214     void *log_caller_data;
215 #else
216     struct vcpu *vcpu;
217 #endif
218     bool verbose;
219     const char *broken;
220 };
221 
222 /* ------------------------------------------------------------------------ */
223 /* accessing elf header fields                                              */
224 
225 #ifdef XEN_ELF_BIG_ENDIAN
226 # define NATIVE_ELFDATA ELFDATA2MSB
227 #else
228 # define NATIVE_ELFDATA ELFDATA2LSB
229 #endif
230 
231 #define elf_32bit(elf) (ELFCLASS32 == (elf)->class)
232 #define elf_64bit(elf) (ELFCLASS64 == (elf)->class)
233 #define elf_msb(elf)   (ELFDATA2MSB == (elf)->data)
234 #define elf_lsb(elf)   (ELFDATA2LSB == (elf)->data)
235 #define elf_swap(elf)  (NATIVE_ELFDATA != (elf)->data)
236 
237 #define elf_uval_3264(elf, handle, elem)                                \
238     elf_access_unsigned((elf), (handle).ptrval,                         \
239                            offsetof(typeof(*(handle).typeonly),elem),    \
240                            sizeof((handle).typeonly->elem))
241 
242 #define elf_uval(elf, handle, elem)             \
243     ((ELFCLASS64 == (elf)->class)               \
244      ? elf_uval_3264(elf, handle, e64.elem)     \
245      : elf_uval_3264(elf, handle, e32.elem))
246   /*
247    * Reads an unsigned field in a header structure in the ELF.
248    * str is a HANDLE, and elem is the field name in it.
249    */
250 
251 
252 #define elf_size(elf, handle_or_handletype) ({          \
253     typeof(handle_or_handletype) elf_size__dummy;       \
254     ((ELFCLASS64 == (elf)->class)                       \
255      ? sizeof(elf_size__dummy.typeonly->e64)             \
256      : sizeof(elf_size__dummy.typeonly->e32));           \
257 })
258   /*
259    * Returns the size of the substructure for the appropriate 32/64-bitness.
260    * str should be a HANDLE.
261    */
262 
263 uint64_t elf_access_unsigned(struct elf_binary *elf, elf_ptrval ptr,
264                              uint64_t offset, size_t size);
265   /* Reads a field at arbitrary offset and alignemnt */
266 
267 uint64_t elf_round_up(struct elf_binary *elf, uint64_t addr);
268 
269 const char *elf_strval(struct elf_binary *elf, elf_ptrval start);
270   /* may return NULL if the string is out of range etc. */
271 
272 const char *elf_strfmt(struct elf_binary *elf, elf_ptrval start);
273   /* like elf_strval but returns "(invalid)" instead of NULL */
274 
275 void elf_memcpy_safe(struct elf_binary*, elf_ptrval dst, elf_ptrval src, size_t);
276 void elf_memset_safe(struct elf_binary*, elf_ptrval dst, int c, size_t);
277   /*
278    * Versions of memcpy and memset which arrange never to write
279    * outside permitted areas.
280    */
281 
282 bool elf_access_ok(struct elf_binary * elf,
283                    uint64_t ptrval, size_t size);
284 
285 #define elf_store_val(elf, type, ptr, val)                              \
286     ({                                                                  \
287         typeof(type) elf_store__val = (val);                            \
288         elf_ptrval elf_store__targ = ptr;                               \
289         if (elf_access_ok((elf), elf_store__targ,                       \
290                           sizeof(elf_store__val))) {			\
291             elf_memcpy_unchecked((void*)elf_store__targ, &elf_store__val, \
292                              sizeof(elf_store__val));                   \
293         }                                                               \
294     })									\
295   /* Stores a value at a particular PTRVAL. */
296 
297 #define elf_store_field(elf, hdr, elm, val)                             \
298     (elf_store_val((elf), ELF__HANDLE_FIELD_TYPE(hdr, elm),                   \
299                    ELF_HANDLE_PTRVAL(hdr) + ELF__HANDLE_FIELD_OFFSET(hdr, elm), \
300                    (val)))
301   /* Stores a 32/64-bit field.  hdr is a HANDLE and elm is the field name. */
302 
303 
304 /* ------------------------------------------------------------------------ */
305 /* xc_libelf_tools.c                                                        */
306 
307 unsigned elf_shdr_count(struct elf_binary *elf);
308 unsigned elf_phdr_count(struct elf_binary *elf);
309 
310 ELF_HANDLE_DECL(elf_shdr) elf_shdr_by_name(struct elf_binary *elf, const char *name);
311 ELF_HANDLE_DECL(elf_shdr) elf_shdr_by_index(struct elf_binary *elf, unsigned index);
312 ELF_HANDLE_DECL(elf_phdr) elf_phdr_by_index(struct elf_binary *elf, unsigned index);
313 
314 const char *elf_section_name(struct elf_binary *elf, ELF_HANDLE_DECL(elf_shdr) shdr); /* might return NULL if inputs are invalid */
315 elf_ptrval elf_section_start(struct elf_binary *elf, ELF_HANDLE_DECL(elf_shdr) shdr);
316 elf_ptrval elf_section_end(struct elf_binary *elf, ELF_HANDLE_DECL(elf_shdr) shdr);
317 
318 elf_ptrval elf_segment_start(struct elf_binary *elf, ELF_HANDLE_DECL(elf_phdr) phdr);
319 elf_ptrval elf_segment_end(struct elf_binary *elf, ELF_HANDLE_DECL(elf_phdr) phdr);
320 
321 ELF_HANDLE_DECL(elf_sym) elf_sym_by_name(struct elf_binary *elf, const char *symbol);
322 ELF_HANDLE_DECL(elf_sym) elf_sym_by_index(struct elf_binary *elf, unsigned index);
323 
324 const char *elf_note_name(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note); /* may return NULL */
325 elf_ptrval elf_note_desc(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note);
326 uint64_t elf_note_numeric(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note);
327 uint64_t elf_note_numeric_array(struct elf_binary *, ELF_HANDLE_DECL(elf_note),
328                                 unsigned int unitsz, unsigned int idx);
329 
330 /*
331  * If you use elf_note_next in a loop, you must put a nontrivial upper
332  * bound on the returned value as part of your loop condition.  In
333  * some cases elf_note_next will substitute ELF_PTRVAL_MAX as return
334  * value to indicate that the iteration isn't going well (for example,
335  * the putative "next" value would be earlier in memory).  In this
336  * case the caller's loop must terminate.  Checking against the
337  * end of the notes segment with a strict inequality is sufficient.
338  */
339 ELF_HANDLE_DECL(elf_note) elf_note_next(struct elf_binary *elf, ELF_HANDLE_DECL(elf_note) note);
340 
341 /* (Only) checks that the image has the right magic number. */
342 bool elf_is_elfbinary(const void *image_start, size_t image_size);
343 
344 bool elf_phdr_is_loadable(struct elf_binary *elf, ELF_HANDLE_DECL(elf_phdr) phdr);
345 
346 /* ------------------------------------------------------------------------ */
347 /* xc_libelf_loader.c                                                       */
348 
349 elf_errorstatus elf_init(struct elf_binary *elf, const char *image, size_t size);
350   /*
351    * image and size must be correct.  They will be recorded in
352    * *elf, and must remain valid while the elf is in use.
353    */
354 #ifdef __XEN__
355 void elf_set_verbose(struct elf_binary *elf);
elf_set_vcpu(struct elf_binary * elf,struct vcpu * v)356 static inline void elf_set_vcpu(struct elf_binary *elf, struct vcpu *v)
357 {
358     elf->vcpu = v;
359 }
360 #else
361 void elf_set_log(struct elf_binary *elf, elf_log_callback*,
362                  void *log_caller_pointer, bool verbose);
363 #endif
364 
365 void elf_parse_binary(struct elf_binary *elf);
366 elf_errorstatus elf_load_binary(struct elf_binary *elf);
367 
368 elf_ptrval elf_get_ptr(struct elf_binary *elf, unsigned long addr);
369 uint64_t elf_lookup_addr(struct elf_binary *elf, const char *symbol);
370 
371 void elf_parse_bsdsyms(struct elf_binary *elf, uint64_t pstart); /* private */
372 
373 void elf_mark_broken(struct elf_binary *elf, const char *msg);
374 const char *elf_check_broken(const struct elf_binary *elf); /* NULL means OK */
375 
376 /* ------------------------------------------------------------------------ */
377 /* xc_libelf_relocate.c                                                     */
378 
379 elf_errorstatus elf_reloc(struct elf_binary *elf);
380 
381 /* ------------------------------------------------------------------------ */
382 /* xc_libelf_dominfo.c                                                      */
383 
384 #define UNSET_ADDR          ((uint64_t)-1)
385 #define UNSET_ADDR32        ((uint32_t)-1)
386 
387 enum xen_elfnote_type {
388     XEN_ENT_NONE = 0,
389     XEN_ENT_LONG = 1,
390     XEN_ENT_STR  = 2
391 };
392 
393 enum xen_pae_type {
394     XEN_PAE_NO      = 0,
395     XEN_PAE_YES     = 1,
396     XEN_PAE_EXTCR3  = 2,
397     XEN_PAE_BIMODAL = 3
398 };
399 
400 struct xen_elfnote {
401     enum xen_elfnote_type type;
402     const char *name;
403     union {
404         const char *str;
405         uint64_t num;
406     } data;
407 };
408 
409 struct elf_dom_parms {
410     /* raw */
411     elf_ptrval guest_info;
412     elf_ptrval elf_note_start;
413     elf_ptrval elf_note_end;
414     struct xen_elfnote elf_notes[XEN_ELFNOTE_MAX + 1];
415 
416     /* parsed */
417     char guest_os[16];
418     char guest_ver[16];
419     char xen_ver[16];
420     char loader[16];
421     enum xen_pae_type pae;
422     bool bsd_symtab;
423     bool unmapped_initrd;
424     uint64_t virt_base;
425     uint64_t virt_entry;
426     uint64_t virt_hypercall;
427     uint64_t virt_hv_start_low;
428     uint64_t p2m_base;
429     uint64_t elf_paddr_offset;
430     uint32_t f_supported[XENFEAT_NR_SUBMAPS];
431     uint32_t f_required[XENFEAT_NR_SUBMAPS];
432     uint32_t phys_entry;
433 
434     /* calculated */
435     uint64_t virt_kstart;
436     uint64_t virt_kend;
437 };
438 
elf_xen_feature_set(int nr,uint32_t * addr)439 static inline void elf_xen_feature_set(int nr, uint32_t * addr)
440 {
441     addr[nr >> 5] |= 1 << (nr & 31);
442 }
elf_xen_feature_get(int nr,uint32_t * addr)443 static inline int elf_xen_feature_get(int nr, uint32_t * addr)
444 {
445     return !!(addr[nr >> 5] & (1 << (nr & 31)));
446 }
447 
448 int elf_xen_parse_features(const char *features,
449                            uint32_t *supported,
450                            uint32_t *required);
451 int elf_xen_parse_note(struct elf_binary *elf,
452                        struct elf_dom_parms *parms,
453                        ELF_HANDLE_DECL(elf_note) note);
454 int elf_xen_parse_guest_info(struct elf_binary *elf,
455                              struct elf_dom_parms *parms);
456 int elf_xen_parse(struct elf_binary *elf,
457                   struct elf_dom_parms *parms);
458 
elf_memcpy_unchecked(void * dest,const void * src,size_t n)459 static inline void *elf_memcpy_unchecked(void *dest, const void *src, size_t n)
460     { return memcpy(dest, src, n); }
elf_memmove_unchecked(void * dest,const void * src,size_t n)461 static inline void *elf_memmove_unchecked(void *dest, const void *src, size_t n)
462     { return memmove(dest, src, n); }
elf_memset_unchecked(void * s,int c,size_t n)463 static inline void *elf_memset_unchecked(void *s, int c, size_t n)
464     { return memset(s, c, n); }
465   /*
466    * Unsafe versions of memcpy, memmove memset which take actual C
467    * pointers.  These are just like the real functions.
468    * We provide these so that in libelf-private.h we can #define
469    * memcpy, memset and memmove to undefined MISTAKE things.
470    */
471 
472 
473 /* Advances past amount bytes of the current destination area. */
ELF_ADVANCE_DEST(struct elf_binary * elf,uint64_t amount)474 static inline void ELF_ADVANCE_DEST(struct elf_binary *elf, uint64_t amount)
475 {
476     if ( elf->dest_base == NULL )
477     {
478         elf_mark_broken(elf, "advancing in null image");
479     }
480     else if ( elf->dest_size >= amount )
481     {
482         elf->dest_base += amount;
483         elf->dest_size -= amount;
484     }
485     else
486     {
487         elf->dest_size = 0;
488         elf_mark_broken(elf, "advancing past end (image very short?)");
489     }
490 }
491 
492 /* Specify a (single) additional destination, to which the image may
493  * cause writes.  As with dest_base and dest_size, the values provided
494  * are trusted and must be valid so long as the struct elf_binary
495  * is in use or until elf_set_xdest(,0,0) is called. */
496 void elf_set_xdest(struct elf_binary *elf, void *addr, uint64_t size);
497 
498 #endif /* __XEN_LIBELF_H__ */
499