1 
2 /*--------------------------------------------------------------------*/
3 /*--- Header included by every tool C file.      pub_tool_basics.h ---*/
4 /*--------------------------------------------------------------------*/
5 
6 /*
7    This file is part of Valgrind, a dynamic binary instrumentation
8    framework.
9 
10    Copyright (C) 2000-2017 Julian Seward
11       jseward@acm.org
12 
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of the
16    License, or (at your option) any later version.
17 
18    This program is distributed in the hope that it will be useful, but
19    WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    General Public License for more details.
22 
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26    02111-1307, USA.
27 
28    The GNU General Public License is contained in the file COPYING.
29 */
30 
31 #ifndef __PUB_TOOL_BASICS_H
32 #define __PUB_TOOL_BASICS_H
33 
34 //--------------------------------------------------------------------
35 // PURPOSE: This header should be imported by every single C file in
36 // tools.  It contains the basic types and other things needed everywhere.
37 // There is no corresponding C file because this isn't a module
38 // containing executable code, it's all just declarations.
39 //--------------------------------------------------------------------
40 
41 /* ---------------------------------------------------------------------
42    Other headers to include
43    ------------------------------------------------------------------ */
44 
45 // VEX defines Char, UChar, Short, UShort, Int, UInt, Long, ULong, SizeT,
46 // Addr, Addr32, Addr64, HWord, HChar, Bool, False and True.
47 #include "libvex_basictypes.h"
48 
49 // For varargs types
50 #include <stdarg.h>
51 
52 
53 /* ---------------------------------------------------------------------
54    symbol prefixing
55    ------------------------------------------------------------------ */
56 
57 // All symbols externally visible from Valgrind are prefixed
58 // as specified here to avoid namespace conflict problems.
59 //
60 // VG_ is for symbols exported from modules.  ML_ (module-local) is
61 // for symbols which are not intended to be visible outside modules,
62 // but which cannot be declared as C 'static's since they need to be
63 // visible across C files within a given module.  It is a mistake for
64 // a ML_ name to appear in a pub_core_*.h or pub_tool_*.h file.
65 // Likewise it is a mistake for a VG_ name to appear in a priv_*.h
66 // file.
67 
68 #define VGAPPEND(str1,str2) str1##str2
69 
70 #define VG_(str)    VGAPPEND(vgPlain_,          str)
71 #define ML_(str)    VGAPPEND(vgModuleLocal_,    str)
72 
73 
74 /* ---------------------------------------------------------------------
75    builtin types
76    ------------------------------------------------------------------ */
77 
78 // By choosing the right types, we can get these right for 32-bit and 64-bit
79 // platforms without having to do any conditional compilation or anything.
80 // POSIX references:
81 // - http://www.opengroup.org/onlinepubs/009695399/basedefs/sys/types.h.html
82 // - http://www.opengroup.org/onlinepubs/009695399/basedefs/stddef.h.html
83 //
84 // Size in bits on:                          32-bit archs   64-bit archs
85 //                                           ------------   ------------
86 typedef unsigned long          UWord;     // 32             64
87 typedef   signed long           Word;     // 32             64
88 
89 // Our equivalent of POSIX 'ssize_t':
90 // - ssize_t is "used for a count of bytes or an error indication".
91 typedef  Word                 SSizeT;     // 32             64
92 
93 // Our equivalent of POSIX 'ptrdiff_t':
94 // - ptrdiff_t is a "signed integer type of the result of subtracting two
95 //   pointers".
96 // We use it for memory offsets, eg. the offset into a memory block.
97 typedef  Word                 PtrdiffT;   // 32             64
98 
99 // Our equivalent of POSIX 'off_t':
100 // - off_t is "used for file sizes".
101 // At one point we were using it for memory offsets, but PtrdiffT should be
102 // used in those cases.
103 // Nb: on Linux, off_t is a signed word-sized int.  On Darwin it's
104 // always a signed 64-bit int.  So we defined our own Off64T as well.
105 #if defined(VGO_linux) || defined(VGO_solaris)
106 typedef Word                   OffT;      // 32             64
107 #elif defined(VGO_dragonfly)
108 typedef Long                   OffT;      // 64             64
109 #elif defined(VGO_darwin)
110 typedef Long                   OffT;      // 64             64
111 #else
112 #  error Unknown OS
113 #endif
114 typedef Long                 Off64T;      // 64             64
115 
116 #if !defined(NULL)
117 #  define NULL ((void*)0)
118 #endif
119 
120 /* This is just too useful to not have around the place somewhere. */
121 typedef  struct { UWord uw1; UWord uw2; }  UWordPair;
122 
123 
124 /* ---------------------------------------------------------------------
125    non-builtin types
126    ------------------------------------------------------------------ */
127 
128 // These probably shouldn't be here, but moving them to their logical
129 // modules results in a lot more #includes...
130 
131 /* ThreadIds are simply indices into the VG_(threads)[] array. */
132 typedef UInt ThreadId;
133 
134 
135 /* You need a debuginfo epoch in order to convert an address into any source
136    level entity, since that conversion depends on what objects were mapped
137    in at the time.  An epoch is simply a monotonically increasing counter,
138    which we wrap up in a struct so as to enable the C type system to
139    distinguish it from other kinds of numbers.  m_debuginfo holds and
140    maintains the current epoch number. */
141 typedef  struct { UInt n; }  DiEpoch;
142 
DiEpoch_INVALID(void)143 static inline DiEpoch DiEpoch_INVALID ( void ) {
144    DiEpoch dep; dep.n = 0; return dep;
145 }
146 
is_DiEpoch_INVALID(DiEpoch dep)147 static inline Bool is_DiEpoch_INVALID ( DiEpoch dep ) {
148    return dep.n == 0;
149 }
150 
151 
152 /* Many data structures need to allocate and release memory.
153    The allocation/release functions must be provided by the caller.
154    The Alloc_Fn_t function must allocate a chunk of memory of size szB.
155    cc is the Cost Centre for this allocated memory. This constant string
156    is used to provide Valgrind's heap profiling, activated by
157    --profile-heap=no|yes.
158    The corresponding Free_Fn_t frees the memory chunk p. */
159 
160 typedef void* (*Alloc_Fn_t)       ( const HChar* cc, SizeT szB );
161 typedef void  (*Free_Fn_t)        ( void* p );
162 
163 /* An abstraction of syscall return values.
164    Linux/MIPS32 and Linux/MIPS64:
165       When _isError == False,
166          _val and possible _valEx hold the return value.  Whether
167          _valEx actually holds a valid value depends on which syscall
168          this SysRes holds of the result of.
169       When _isError == True,
170          _val holds the error code.
171 
172    Linux/other:
173       When _isError == False,
174          _val holds the return value.
175       When _isError == True,
176          _val holds the error code.
177 
178    Darwin:
179       Interpretation depends on _mode:
180       MACH, MDEP:
181          these can never 'fail' (apparently).  The result of the
182          syscall is a single host word, _wLO.
183       UNIX:
184          Can record a double-word error or a double-word result:
185          When _mode is SysRes_UNIX_OK,  _wHI:_wLO holds the result.
186          When _mode is SysRes_UNIX_ERR, _wHI:_wLO holds the error code.
187          Probably the high word of an error is always ignored by
188          userspace, but we have to record it, so that we can correctly
189          update both {R,E}DX and {R,E}AX (in guest state) given a SysRes,
190          if we're required to.
191 
192    Solaris:
193       When _isError == False,
194          _val and _val2 hold the return value.
195       When _isError == True,
196          _val holds the error code.
197 */
198 #if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
199 typedef
200    struct {
201       Bool  _isError;
202       RegWord _val;
203       UWord _valEx;
204    }
205    SysRes;
206 
207 #elif defined(VGO_linux) \
208       && !defined(VGP_mips32_linux) && !defined(VGP_mips64_linux)
209 typedef
210    struct {
211       Bool  _isError;
212       UWord _val;
213    }
214    SysRes;
215 
216 #elif defined(VGO_darwin)
217 typedef
218    enum {
219       SysRes_MACH=40,  // MACH, result is _wLO
220       SysRes_MDEP,     // MDEP, result is _wLO
221       SysRes_UNIX_OK,  // UNIX, success, result is _wHI:_wLO
222       SysRes_UNIX_ERR  // UNIX, error,   error  is _wHI:_wLO
223    }
224    SysResMode;
225 typedef
226    struct {
227       UWord _wLO;
228       UWord _wHI;
229       SysResMode _mode;
230    }
231    SysRes;
232 #elif defined(VGO_dragonfly)
233 typedef
234    struct {
235       UWord _val;
236       UWord _val2;
237       Bool  _isError;
238    }
239    SysRes;
240 
241 #elif defined(VGO_solaris)
242 typedef
243    struct {
244       UWord _val;
245       UWord _val2;
246       Bool  _isError;
247    }
248    SysRes;
249 
250 #else
251 #  error "Unknown OS"
252 #endif
253 
254 
255 /* ---- And now some basic accessor functions for it. ---- */
256 
257 #if defined(VGP_mips32_linux) || defined(VGP_mips64_linux)
258 
sr_isError(SysRes sr)259 static inline Bool sr_isError ( SysRes sr ) {
260    return sr._isError;
261 }
sr_Res(SysRes sr)262 static inline RegWord sr_Res ( SysRes sr ) {
263    return sr._isError ? 0 : sr._val;
264 }
sr_ResEx(SysRes sr)265 static inline UWord sr_ResEx ( SysRes sr ) {
266    return sr._isError ? 0 : sr._valEx;
267 }
sr_Err(SysRes sr)268 static inline UWord sr_Err ( SysRes sr ) {
269    return sr._isError ? sr._val : 0;
270 }
sr_EQ(UInt sysno,SysRes sr1,SysRes sr2)271 static inline Bool sr_EQ ( UInt sysno, SysRes sr1, SysRes sr2 ) {
272    /* This uglyness of hardcoding syscall numbers is necessary to
273       avoid having this header file be dependent on
274       include/vki/vki-scnums-mips{32,64}-linux.h.  It seems pretty
275       safe given that it is inconceivable that the syscall numbers
276       for such simple syscalls would ever change.  To make it
277       really safe, coregrind/m_vkiscnums.c static-asserts that these
278       syscall numbers haven't changed, so that the build wil simply
279       fail if they ever do. */
280 #  if defined(VGP_mips32_linux)
281    const UInt __nr_Linux = 4000;
282    const UInt __nr_pipe  = __nr_Linux + 42;
283    const UInt __nr_pipe2 = __nr_Linux + 328;
284 #  elif defined(VGP_mips64_linux) && defined(VGABI_N32)
285    const UInt __nr_Linux = 6000;
286    const UInt __nr_pipe  = __nr_Linux + 21;
287    const UInt __nr_pipe2 = __nr_Linux + 291;
288 #  else
289    const UInt __nr_Linux = 5000;
290    const UInt __nr_pipe  = __nr_Linux + 21;
291    const UInt __nr_pipe2 = __nr_Linux + 287;
292 #  endif
293    Bool useEx = sysno == __nr_pipe || sysno == __nr_pipe2;
294    return sr1._val == sr2._val
295           && (useEx ? (sr1._valEx == sr2._valEx) : True)
296           && sr1._isError == sr2._isError;
297 }
298 
299 #elif defined(VGO_linux) \
300       && !defined(VGP_mips32_linux) && !defined(VGP_mips64_linux)
301 
sr_isError(SysRes sr)302 static inline Bool sr_isError ( SysRes sr ) {
303    return sr._isError;
304 }
sr_Res(SysRes sr)305 static inline UWord sr_Res ( SysRes sr ) {
306    return sr._isError ? 0 : sr._val;
307 }
sr_Err(SysRes sr)308 static inline UWord sr_Err ( SysRes sr ) {
309    return sr._isError ? sr._val : 0;
310 }
sr_EQ(UInt sysno,SysRes sr1,SysRes sr2)311 static inline Bool sr_EQ ( UInt sysno, SysRes sr1, SysRes sr2 ) {
312    /* sysno is ignored for Linux/not-MIPS */
313    return sr1._val == sr2._val
314           && sr1._isError == sr2._isError;
315 }
316 
317 #elif defined(VGO_dragonfly)
318 
sr_isError(SysRes sr)319 static inline Bool sr_isError ( SysRes sr ) {
320    return sr._isError;
321 }
sr_Res(SysRes sr)322 static inline UWord sr_Res ( SysRes sr ) {
323    return sr._isError ? 0 : sr._val;
324 }
sr_ResHI(SysRes sr)325 static inline UWord sr_ResHI ( SysRes sr ) {
326    return sr._isError ? 0 : sr._val2;
327 }
sr_Err(SysRes sr)328 static inline UWord sr_Err ( SysRes sr ) {
329    return sr._isError ? sr._val : 0;
330 }
sr_EQ(UInt sysno,SysRes sr1,SysRes sr2)331 static inline Bool sr_EQ ( UInt sysno, SysRes sr1, SysRes sr2 ) {
332    return sr_Res(sr1) == sr_Res(sr2)
333           && sr_ResHI(sr1) == sr_ResHI(sr2)
334           && ((sr_isError(sr1) && sr_isError(sr2))
335               || (!sr_isError(sr1) && !sr_isError(sr2)));
336 }
337 
338 #elif defined(VGO_darwin)
339 
sr_isError(SysRes sr)340 static inline Bool sr_isError ( SysRes sr ) {
341    switch (sr._mode) {
342       case SysRes_UNIX_ERR:
343          return True;
344       /* should check tags properly and assert here, but we can't here */
345       case SysRes_MACH:
346       case SysRes_MDEP:
347       case SysRes_UNIX_OK:
348       default:
349          return False;
350    }
351 }
352 
sr_Res(SysRes sr)353 static inline UWord sr_Res ( SysRes sr ) {
354    switch (sr._mode) {
355       case SysRes_MACH:
356       case SysRes_MDEP:
357       case SysRes_UNIX_OK:
358          return sr._wLO;
359       /* should assert, but we can't here */
360       case SysRes_UNIX_ERR:
361       default:
362          return 0;
363    }
364 }
365 
sr_ResHI(SysRes sr)366 static inline UWord sr_ResHI ( SysRes sr ) {
367    switch (sr._mode) {
368       case SysRes_UNIX_OK:
369          return sr._wHI;
370       /* should assert, but we can't here */
371       case SysRes_MACH:
372       case SysRes_MDEP:
373       case SysRes_UNIX_ERR:
374       default:
375          return 0;
376    }
377 }
378 
sr_Err(SysRes sr)379 static inline UWord sr_Err ( SysRes sr ) {
380    switch (sr._mode) {
381       case SysRes_UNIX_ERR:
382          return sr._wLO;
383       /* should assert, but we can't here */
384       case SysRes_MACH:
385       case SysRes_MDEP:
386       case SysRes_UNIX_OK:
387       default:
388          return 0;
389    }
390 }
391 
sr_EQ(UInt sysno,SysRes sr1,SysRes sr2)392 static inline Bool sr_EQ ( UInt sysno, SysRes sr1, SysRes sr2 ) {
393    /* sysno is ignored for Darwin */
394    return sr1._mode == sr2._mode
395           && sr1._wLO == sr2._wLO && sr1._wHI == sr2._wHI;
396 }
397 
398 #elif defined(VGO_solaris)
399 
sr_isError(SysRes sr)400 static inline Bool sr_isError ( SysRes sr ) {
401    return sr._isError;
402 }
sr_Res(SysRes sr)403 static inline UWord sr_Res ( SysRes sr ) {
404    return sr._isError ? 0 : sr._val;
405 }
sr_ResHI(SysRes sr)406 static inline UWord sr_ResHI ( SysRes sr ) {
407    return sr._isError ? 0 : sr._val2;
408 }
sr_Err(SysRes sr)409 static inline UWord sr_Err ( SysRes sr ) {
410    return sr._isError ? sr._val : 0;
411 }
sr_EQ(UInt sysno,SysRes sr1,SysRes sr2)412 static inline Bool sr_EQ ( UInt sysno, SysRes sr1, SysRes sr2 ) {
413    /* sysno is ignored for Solaris */
414    return sr1._val == sr2._val
415        && sr1._isError == sr2._isError
416        && (!sr1._isError) ? (sr1._val2 == sr2._val2) : True;
417 }
418 
419 #else
420 #  error "Unknown OS"
421 #endif
422 
423 
424 /* ---------------------------------------------------------------------
425    Miscellaneous (word size, endianness, regparmness, stringification)
426    ------------------------------------------------------------------ */
427 
428 /* Word size: this is going to be either 4 or 8. */
429 // It should probably be in m_machine.
430 #define VG_WORDSIZE VEX_HOST_WORDSIZE
431 
432 /* Endianness */
433 #undef VG_BIGENDIAN
434 #undef VG_LITTLEENDIAN
435 
436 #if defined(VGA_x86) || defined(VGA_amd64) || defined (VGA_arm) \
437     || ((defined(VGA_mips32) || defined(VGA_mips64)) && defined (_MIPSEL)) \
438     || defined(VGA_arm64)  || defined(VGA_ppc64le)
439 #  define VG_LITTLEENDIAN 1
440 #elif defined(VGA_ppc32) || defined(VGA_ppc64be) || defined(VGA_s390x) \
441       || ((defined(VGA_mips32) || defined(VGA_mips64)) && defined (_MIPSEB))
442 #  define VG_BIGENDIAN 1
443 #else
444 #  error Unknown arch
445 #endif
446 
447 /* Offsetof */
448 #if !defined(offsetof)
449 #   define offsetof(type,memb) ((SizeT)(HWord)&((type*)0)->memb)
450 #endif
451 
452 #if !defined(container_of)
453 #   define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
454 #endif
455 
456 /* Alignment */
457 /* We use a prefix vg_ for vg_alignof as its behaviour slightly
458    differs from the standard alignof/gcc defined __alignof__
459 
460    vg_alignof returns a "safe" alignement.
461    "safe" is defined as the alignment chosen by the compiler in
462    a struct made of a char followed by this type.
463 
464       Note that this is not necessarily the "preferred" alignment
465       for a platform. This preferred alignment is returned by the gcc
466        __alignof__ and by the standard (in recent standard) alignof.
467       Compared to __alignof__, vg_alignof gives on some platforms (e.g.
468       amd64, ppc32, ppc64) a bigger alignment for long double (16 bytes
469       instead of 8).
470       On some platforms (e.g. x86), vg_alignof gives a smaller alignment
471       than __alignof__ for long long and double (4 bytes instead of 8).
472       If we want to have the "preferred" alignment for the basic types,
473       then either we need to depend on gcc __alignof__, or on a (too)
474       recent standard and compiler (implementing <stdalign.h>).
475 */
476 #define vg_alignof(_type) (sizeof(struct {char c;_type _t;})-sizeof(_type))
477 
478 /* Regparmness */
479 #if defined(VGA_x86)
480 #  define VG_REGPARM(n)            __attribute__((regparm(n)))
481 #elif defined(VGA_amd64) || defined(VGA_ppc32) \
482       || defined(VGA_ppc64be) || defined(VGA_ppc64le) \
483       || defined(VGA_arm) || defined(VGA_s390x) \
484       || defined(VGA_mips32) || defined(VGA_mips64) \
485       || defined(VGA_arm64)
486 #  define VG_REGPARM(n)            /* */
487 #else
488 #  error Unknown arch
489 #endif
490 
491 /* Macro games */
492 #define VG_STRINGIFZ(__str)  #__str
493 #define VG_STRINGIFY(__str)  VG_STRINGIFZ(__str)
494 
495 // Where to send bug reports to.
496 #define VG_BUGS_TO "www.valgrind.org"
497 
498 /* Branch prediction hints. */
499 #if defined(__GNUC__)
500 #  define LIKELY(x)   __builtin_expect(!!(x), 1)
501 #  define UNLIKELY(x) __builtin_expect(!!(x), 0)
502 #else
503 #  define LIKELY(x)   (x)
504 #  define UNLIKELY(x) (x)
505 #endif
506 
507 // printf format string checking for gcc.
508 // This feature has been supported since at least gcc version 2.95.
509 // For more information about the format attribute, see
510 // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html.
511 #if defined(__GNUC__)
512 #define PRINTF_CHECK(x, y) __attribute__((format(__printf__, x, y)))
513 #else
514 #define PRINTF_CHECK(x, y)
515 #endif
516 
517 // Macro to "cast" away constness (from type const T to type T) without
518 // GCC complaining about it. This macro should be used RARELY.
519 // x is expected to have type const T
520 #define CONST_CAST(T,x)    \
521    ({                      \
522       union {              \
523          const T in;      \
524          T out;           \
525       } var = { .in = x }; var.out;  \
526    })
527 
528 /* Some architectures (eg. mips, arm) do not support unaligned memory access
529    by hardware, so GCC warns about suspicious situations. This macro could
530    be used to avoid these warnings but only after careful examination. */
531 #define ASSUME_ALIGNED(D, x)                 \
532    ({                                        \
533       union {                                \
534          void *in;                           \
535          D out;                              \
536       } var;                                 \
537       var.in = (void *) (x); var.out;        \
538    })
539 
540 // Poor man's static assert
541 #define STATIC_ASSERT(x)  extern int VG_(VG_(VG_(unused)))[(x) ? 1 : -1] \
542                                      __attribute__((unused))
543 
544 #define VG_MAX(a,b) ((a) > (b) ? a : b)
545 #define VG_MIN(a,b) ((a) < (b) ? a : b)
546 
547 #endif /* __PUB_TOOL_BASICS_H */
548 
549 /*--------------------------------------------------------------------*/
550 /*--- end                                                          ---*/
551 /*--------------------------------------------------------------------*/
552