We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Incorrect conversion from gdb.Value to python int
<!--
Before reporting a new issue, make sure that we do not have any duplicates already open.
If there is one it might be good to take part in the discussion there.

Please make sure you have checked that the issue persists on LATEST pwndbg version.

Below is a template for BUG REPORTS.
Don't include it if this is a FEATURE REQUEST.
-->


### Description

<!--
Briefly describe the problem you are having in a few paragraphs.
-->

When debugging certain binary, pwndbg may show incorrect register value, missing high 32 bit for 64 bit register.
e.g.

```
pwndbg> regs rax
 RAX  0x555c4160
pwndbg> i r rax
rax            0x5555555c4160   93824992690528
pwndbg> telescope $rax
<Could not read memory at 0x555c4160>
pwndbg> regs rsp
 RSP  0xffffffffffffc2f0
pwndbg> i r rsp
rsp            0x7fffffffc2f0   0x7fffffffc2f0
pwndbg> telescope $rsp
<Could not read memory at 0xffffc2f0>
pwndbg>
```

**If I strip the binary, everything goes well.**

After checking code of pwndbg, I found that the bug happens when trying to convert a `gdb.Value` instance to python `int`.

```
pwndbg> python
>print(hex(pwndbg.regs.rsp))
>rsp = pwndbg.regs.value
>print(type(rsp))
>print(rsp.type)
>print(rsp)
>print(hex(rsp))
>print(int(rsp))
>print(long(rsp))
>print(str(rsp))
>print(hex(pwndbg.arch.ptrmask))
>print(hex(int(rsp) & pwndbg.arch.ptrmask))
>end
0xffffffffffffc2f0
<class 'gdb.Value'>
u64
140737488339696
0x7fffffffc2f0
-15632
-15632
140737488339696
0xffffffffffffffff
0xffffffffffffc2f0
```

Seems the `int(value)` works as converting to 32 bit c type int instead of python type int. Maybe we need to use `int(str(value))` to get the correct value.

### Steps to reproduce

<!--
What do we have to do to reproduce the problem?
If this is connected to particular C/asm code, 
please provide the smallest C code that reproduces the issue.
-->

Here is an example binary which can reproduce the bug.

[babi.zip](https://github.com/pwndbg/pwndbg/files/3508243/babi.zip)

1. Execute `babi` with gdb & break at `0x5555555D0C97`.
1. Execute the attached `test.py`.
1. Breakpoint will hit with the bug.

*PS: stop in `libc` or `main` function won't see the bug.*

### My setup

<!--
Show us your gdb/python/pwndbg/OS/IDA Pro version (depending on your case).

NOTE: We are currently supporting only Ubuntu installations.
It is known that pwndbg is not fully working e.g. on Arch Linux (the heap stuff is not working there).
If you would like to change this situation - help us improving pwndbg and supporting other distros!

This can be displayed in pwndbg through `version` command.

If it is somehow unavailable, use:
* `show version` - for gdb
* `py import sys; print(sys.version)` - for python
* pwndbg version/git commit id
-->

```
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:        18.04
Codename:       bionic
```

```
pwndbg> version
Gdb:      8.1.0.20180409-git
Python:   3.6.8 (default, Jan 14 2019, 11:02:34)  [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]
Pwndbg:   1.1.0 build: 7f5d8e7
Capstone: 4.0.1024
Unicorn:  1.0.1
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pwndbg/inthook.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 This hook is necessary for compatibility with Python2.7 versions of GDB
5 since they cannot directly cast to integer a gdb.Value object that is
6 not already an integer type.
7 """
8 from __future__ import absolute_import
9 from __future__ import division
10 from __future__ import print_function
11 from __future__ import unicode_literals
12 
13 import enum
14 import os
15 
16 import gdb
17 import six
18 from future.utils import with_metaclass
19 
20 import pwndbg.typeinfo
21 
22 if six.PY2:
23     import __builtin__ as builtins
24 else:
25     import builtins
26 
27 _int = builtins.int
28 
29 
30 # We need this class to get isinstance(7, xint) to return True
31 class IsAnInt(type):
32     def __instancecheck__(self, other):
33         return isinstance(other, _int)
34 
35 
36 class xint(with_metaclass(IsAnInt, builtins.int)):
37     def __new__(cls, value, *a, **kw):
38         if isinstance(value, gdb.Value):
39             if pwndbg.typeinfo.is_pointer(value):
40                 value = value.cast(pwndbg.typeinfo.ulong)
41             else:
42                 value = value.cast(pwndbg.typeinfo.long)
43 
44         elif isinstance(value, gdb.Symbol):
45             symbol = value
46             value = symbol.value()
47             if symbol.is_function:
48                 value = value.cast(pwndbg.typeinfo.ulong)
49 
50         elif not isinstance(value, (six.string_types, six.integer_types)) \
51                 or isinstance(cls, enum.EnumMeta):
52             # without check for EnumMeta math operations with enums were failing e.g.:
53             #     pwndbg> py import re; flags = 1 | re.MULTILINE
54             return _int.__new__(cls, value, *a, **kw)
55 
56         return _int(_int(value, *a, **kw))
57 
58 # Do not hook 'int' if we are just generating documentation
59 if os.environ.get('SPHINX', None) is None:
60     builtins.int = xint
61     globals()['int'] = xint
62     if six.PY3:
63         builtins.long = xint
64         globals()['long'] = xint
65
```

Path: `pwndbg/typeinfo.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 Common types, and routines for manually loading types from file
5 via GCC.
6 """
7 from __future__ import absolute_import
8 from __future__ import division
9 from __future__ import print_function
10 from __future__ import unicode_literals
11 
12 import glob
13 import os
14 import subprocess
15 import sys
16 import tempfile
17 
18 import gdb
19 
20 import pwndbg.events
21 import pwndbg.gcc
22 import pwndbg.memoize
23 
24 module = sys.modules[__name__]
25 
26 
27 def is_pointer(value):
28     type = value
29 
30     if isinstance(value, gdb.Value):
31         type = value.type
32 
33     type = type.strip_typedefs()
34     return type.code == gdb.TYPE_CODE_PTR
35 
36 
37 def lookup_types(*types):
38     for type_str in types:
39         try:
40             return gdb.lookup_type(type_str)
41         except Exception as e:
42             exc = e
43     raise exc
44 
45 
46 @pwndbg.events.new_objfile
47 @pwndbg.events.start
48 @pwndbg.events.stop
49 def update():
50 
51     module.char   = gdb.lookup_type('char')
52     module.ulong  = lookup_types('unsigned long', 'uint', 'u32', 'uint32')
53     module.long   = lookup_types('long', 'int', 'i32', 'int32')
54     module.uchar  = lookup_types('unsigned char', 'ubyte', 'u8', 'uint8')
55     module.ushort = lookup_types('unsigned short', 'ushort', 'u16', 'uint16')
56     module.uint   = lookup_types('unsigned int', 'uint', 'u32', 'uint32')
57     module.void   = lookup_types('void', '()')
58     module.uint8  = module.uchar
59     module.uint16 = module.ushort
60     module.uint32 = module.uint
61     module.uint64 = lookup_types('unsigned long long', 'ulong', 'u64', 'uint64')
62 
63     module.int8   = lookup_types('char', 'i8', 'int8')
64     module.int16  = lookup_types('short', 'i16', 'int16')
65     module.int32  = lookup_types('int', 'i32', 'int32')
66     module.int64  = lookup_types('long long', 'long', 'i64', 'int64')
67 
68     module.ssize_t = module.long
69     module.size_t = module.ulong
70 
71     module.pvoid  = void.pointer()
72     module.ppvoid = pvoid.pointer()
73     module.pchar  = char.pointer()
74 
75     module.ptrsize = pvoid.sizeof
76 
77     if pvoid.sizeof == 4: module.ptrdiff = uint32
78     if pvoid.sizeof == 8: module.ptrdiff = uint64
79 
80     module.null = gdb.Value(0).cast(void)
81 
82 # Call it once so we load all of the types
83 update()
84 
85 tempdir = tempfile.gettempdir() + '/pwndbg'
86 if not os.path.exists(tempdir):
87     os.mkdir(tempdir)
88 
89 # Trial and error until things work
90 blacklist = ['regexp.h', 'xf86drm.h', 'libxl_json.h', 'xf86drmMode.h',
91 'caca0.h', 'xenguest.h', '_libxl_types_json.h', 'term_entry.h', 'slcurses.h',
92 'pcreposix.h', 'sudo_plugin.h', 'tic.h', 'sys/elf.h', 'sys/vm86.h',
93 'xenctrlosdep.h', 'xenctrl.h', 'cursesf.h', 'cursesm.h', 'gdbm.h', 'dbm.h',
94 'gcrypt-module.h', 'term.h', 'gmpxx.h', 'pcap/namedb.h', 'pcap-namedb.h',
95 'evr.h', 'mpc.h', 'fdt.h', 'mpfr.h', 'evrpc.h', 'png.h', 'zlib.h', 'pngconf.h',
96 'libelfsh.h', 'libmjollnir.h', 'hwloc.h', 'ares.h', 'revm.h', 'ares_rules.h',
97 'libunwind-ptrace.h', 'libui.h', 'librevm-color.h', 'libedfmt.h','revm-objects.h',
98 'libetrace.h', 'revm-io.h','libasm-mips.h','libstderesi.h','libasm.h','libaspect.h',
99 'libunwind.h','libmjollnir-objects.h','libunwind-coredump.h','libunwind-dynamic.h']
100 
101 def load(name):
102     """Load symbol by name from headers in standard system include directory"""
103     try:
104         return gdb.lookup_type(name)
105     except gdb.error:
106         pass
107 
108     # s, _ = gdb.lookup_symbol(name)
109 
110     # Try to find an architecture-specific include path
111     arch = pwndbg.arch.current.split(':')[0]
112 
113     include_dir = glob.glob('/usr/%s*/include' % arch)
114 
115     if include_dir:
116         include_dir = include_dir[0]
117     else:
118         include_dir = '/usr/include'
119 
120     source = '#include <fstream>\n'
121 
122     for subdir in ['', 'sys', 'netinet']:
123         dirname = os.path.join(include_dir, subdir)
124         for path in glob.glob(os.path.join(dirname, '*.h')):
125             if any(b in path for b in blacklist):
126               continue
127             print(path)
128             source += '#include "%s"\n' % path
129 
130 
131     source += '''
132 {name} foo;
133 '''.format(**locals())
134 
135     filename = '%s/%s_%s.cc' % (tempdir, arch, '-'.join(name.split()))
136 
137     with open(filename, 'w+') as f:
138         f.write(source)
139         f.flush()
140         os.fsync(f.fileno())
141 
142     compile(filename)
143 
144     return gdb.lookup_type(name)
145 
146 def compile(filename=None, address=0):
147     """Compile and extract symbols from specified file"""
148     if filename is None:
149         print("Specify a filename to compile.")
150         return
151 
152     objectname = os.path.splitext(filename)[0] + ".o"
153 
154     if not os.path.exists(objectname):
155         gcc     = pwndbg.gcc.which()
156         gcc    += ['-w', '-c', '-g', filename, '-o', objectname]
157         try:
158             subprocess.check_output(gcc)
159         except subprocess.CalledProcessError as e:
160             return
161 
162     add_symbol_file(objectname, address)
163 
164 def add_symbol_file(filename=None, address=0):
165     """Read additional symbol table information from the object file filename"""
166     if filename is None:
167         print("Specify a symbol file to add.")
168         return
169 
170     with pwndbg.events.Pause():
171         gdb.execute('add-symbol-file %s %s' % (filename, address), from_tty=False, to_string=True)
172 
173 def read_gdbvalue(type_name, addr):
174     """ Read the memory contents at addr and interpret them as a GDB value with the given type """
175     gdb_type = pwndbg.typeinfo.load(type_name)
176     return gdb.Value(addr).cast(gdb_type.pointer()).dereference()
177
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pwndbg/inthook.py b/pwndbg/inthook.py
--- a/pwndbg/inthook.py
+++ b/pwndbg/inthook.py
@@ -37,15 +37,15 @@
     def __new__(cls, value, *a, **kw):
         if isinstance(value, gdb.Value):
             if pwndbg.typeinfo.is_pointer(value):
-                value = value.cast(pwndbg.typeinfo.ulong)
+                value = value.cast(pwndbg.typeinfo.size_t)
             else:
-                value = value.cast(pwndbg.typeinfo.long)
+                value = value.cast(pwndbg.typeinfo.ssize_t)
 
         elif isinstance(value, gdb.Symbol):
             symbol = value
             value = symbol.value()
             if symbol.is_function:
-                value = value.cast(pwndbg.typeinfo.ulong)
+                value = value.cast(pwndbg.typeinfo.size_t)
 
         elif not isinstance(value, (six.string_types, six.integer_types)) \
                 or isinstance(cls, enum.EnumMeta):
diff --git a/pwndbg/typeinfo.py b/pwndbg/typeinfo.py
--- a/pwndbg/typeinfo.py
+++ b/pwndbg/typeinfo.py
@@ -65,18 +65,22 @@
     module.int32  = lookup_types('int', 'i32', 'int32')
     module.int64  = lookup_types('long long', 'long', 'i64', 'int64')
 
-    module.ssize_t = module.long
-    module.size_t = module.ulong
-
     module.pvoid  = void.pointer()
     module.ppvoid = pvoid.pointer()
     module.pchar  = char.pointer()
 
     module.ptrsize = pvoid.sizeof
 
-    if pvoid.sizeof == 4: module.ptrdiff = uint32
-    if pvoid.sizeof == 8: module.ptrdiff = uint64
-
+    if pvoid.sizeof == 4: 
+        module.ptrdiff = module.uint32
+        module.size_t = module.uint32
+        module.ssize_t = module.int32
+    elif pvoid.sizeof == 8: 
+        module.ptrdiff = module.uint64
+        module.size_t = module.uint64
+        module.ssize_t = module.int64
+    else:
+        raise Exception('Pointer size not supported')
     module.null = gdb.Value(0).cast(void)
 
 # Call it once so we load all of the types

{"golden_diff": "diff --git a/pwndbg/inthook.py b/pwndbg/inthook.py\n--- a/pwndbg/inthook.py\n+++ b/pwndbg/inthook.py\n@@ -37,15 +37,15 @@\n     def __new__(cls, value, *a, **kw):\n         if isinstance(value, gdb.Value):\n             if pwndbg.typeinfo.is_pointer(value):\n-                value = value.cast(pwndbg.typeinfo.ulong)\n+                value = value.cast(pwndbg.typeinfo.size_t)\n             else:\n-                value = value.cast(pwndbg.typeinfo.long)\n+                value = value.cast(pwndbg.typeinfo.ssize_t)\n \n         elif isinstance(value, gdb.Symbol):\n             symbol = value\n             value = symbol.value()\n             if symbol.is_function:\n-                value = value.cast(pwndbg.typeinfo.ulong)\n+                value = value.cast(pwndbg.typeinfo.size_t)\n \n         elif not isinstance(value, (six.string_types, six.integer_types)) \\\n                 or isinstance(cls, enum.EnumMeta):\ndiff --git a/pwndbg/typeinfo.py b/pwndbg/typeinfo.py\n--- a/pwndbg/typeinfo.py\n+++ b/pwndbg/typeinfo.py\n@@ -65,18 +65,22 @@\n     module.int32  = lookup_types('int', 'i32', 'int32')\n     module.int64  = lookup_types('long long', 'long', 'i64', 'int64')\n \n-    module.ssize_t = module.long\n-    module.size_t = module.ulong\n-\n     module.pvoid  = void.pointer()\n     module.ppvoid = pvoid.pointer()\n     module.pchar  = char.pointer()\n \n     module.ptrsize = pvoid.sizeof\n \n-    if pvoid.sizeof == 4: module.ptrdiff = uint32\n-    if pvoid.sizeof == 8: module.ptrdiff = uint64\n-\n+    if pvoid.sizeof == 4: \n+        module.ptrdiff = module.uint32\n+        module.size_t = module.uint32\n+        module.ssize_t = module.int32\n+    elif pvoid.sizeof == 8: \n+        module.ptrdiff = module.uint64\n+        module.size_t = module.uint64\n+        module.ssize_t = module.int64\n+    else:\n+        raise Exception('Pointer size not supported')\n     module.null = gdb.Value(0).cast(void)\n \n # Call it once so we load all of the types\n", "issue": "Incorrect conversion from gdb.Value to python int\n<!--\r\nBefore reporting a new issue, make sure that we do not have any duplicates already open.\r\nIf there is one it might be good to take part in the discussion there.\r\n\r\nPlease make sure you have checked that the issue persists on LATEST pwndbg version.\r\n\r\nBelow is a template for BUG REPORTS.\r\nDon't include it if this is a FEATURE REQUEST.\r\n-->\r\n\r\n\r\n### Description\r\n\r\n<!--\r\nBriefly describe the problem you are having in a few paragraphs.\r\n-->\r\n\r\nWhen debugging certain binary, pwndbg may show incorrect register value, missing high 32 bit for 64 bit register.\r\ne.g.\r\n\r\n```\r\npwndbg> regs rax\r\n RAX  0x555c4160\r\npwndbg> i r rax\r\nrax            0x5555555c4160   93824992690528\r\npwndbg> telescope $rax\r\n<Could not read memory at 0x555c4160>\r\npwndbg> regs rsp\r\n RSP  0xffffffffffffc2f0\r\npwndbg> i r rsp\r\nrsp            0x7fffffffc2f0   0x7fffffffc2f0\r\npwndbg> telescope $rsp\r\n<Could not read memory at 0xffffc2f0>\r\npwndbg>\r\n```\r\n\r\n**If I strip the binary, everything goes well.**\r\n\r\nAfter checking code of pwndbg, I found that the bug happens when trying to convert a `gdb.Value` instance to python `int`.\r\n\r\n```\r\npwndbg> python\r\n>print(hex(pwndbg.regs.rsp))\r\n>rsp = pwndbg.regs.value\r\n>print(type(rsp))\r\n>print(rsp.type)\r\n>print(rsp)\r\n>print(hex(rsp))\r\n>print(int(rsp))\r\n>print(long(rsp))\r\n>print(str(rsp))\r\n>print(hex(pwndbg.arch.ptrmask))\r\n>print(hex(int(rsp) & pwndbg.arch.ptrmask))\r\n>end\r\n0xffffffffffffc2f0\r\n<class 'gdb.Value'>\r\nu64\r\n140737488339696\r\n0x7fffffffc2f0\r\n-15632\r\n-15632\r\n140737488339696\r\n0xffffffffffffffff\r\n0xffffffffffffc2f0\r\n```\r\n\r\nSeems the `int(value)` works as converting to 32 bit c type int instead of python type int. Maybe we need to use `int(str(value))` to get the correct value.\r\n\r\n### Steps to reproduce\r\n\r\n<!--\r\nWhat do we have to do to reproduce the problem?\r\nIf this is connected to particular C/asm code, \r\nplease provide the smallest C code that reproduces the issue.\r\n-->\r\n\r\nHere is an example binary which can reproduce the bug.\r\n\r\n[babi.zip](https://github.com/pwndbg/pwndbg/files/3508243/babi.zip)\r\n\r\n1. Execute `babi` with gdb & break at `0x5555555D0C97`.\r\n1. Execute the attached `test.py`.\r\n1. Breakpoint will hit with the bug.\r\n\r\n*PS: stop in `libc` or `main` function won't see the bug.*\r\n\r\n### My setup\r\n\r\n<!--\r\nShow us your gdb/python/pwndbg/OS/IDA Pro version (depending on your case).\r\n\r\nNOTE: We are currently supporting only Ubuntu installations.\r\nIt is known that pwndbg is not fully working e.g. on Arch Linux (the heap stuff is not working there).\r\nIf you would like to change this situation - help us improving pwndbg and supporting other distros!\r\n\r\nThis can be displayed in pwndbg through `version` command.\r\n\r\nIf it is somehow unavailable, use:\r\n* `show version` - for gdb\r\n* `py import sys; print(sys.version)` - for python\r\n* pwndbg version/git commit id\r\n-->\r\n\r\n```\r\n$ lsb_release -a\r\nNo LSB modules are available.\r\nDistributor ID: Ubuntu\r\nDescription:    Ubuntu 18.04.2 LTS\r\nRelease:        18.04\r\nCodename:       bionic\r\n```\r\n\r\n```\r\npwndbg> version\r\nGdb:      8.1.0.20180409-git\r\nPython:   3.6.8 (default, Jan 14 2019, 11:02:34)  [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]\r\nPwndbg:   1.1.0 build: 7f5d8e7\r\nCapstone: 4.0.1024\r\nUnicorn:  1.0.1\r\n```\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis hook is necessary for compatibility with Python2.7 versions of GDB\nsince they cannot directly cast to integer a gdb.Value object that is\nnot already an integer type.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport enum\nimport os\n\nimport gdb\nimport six\nfrom future.utils import with_metaclass\n\nimport pwndbg.typeinfo\n\nif six.PY2:\n    import __builtin__ as builtins\nelse:\n    import builtins\n\n_int = builtins.int\n\n\n# We need this class to get isinstance(7, xint) to return True\nclass IsAnInt(type):\n    def __instancecheck__(self, other):\n        return isinstance(other, _int)\n\n\nclass xint(with_metaclass(IsAnInt, builtins.int)):\n    def __new__(cls, value, *a, **kw):\n        if isinstance(value, gdb.Value):\n            if pwndbg.typeinfo.is_pointer(value):\n                value = value.cast(pwndbg.typeinfo.ulong)\n            else:\n                value = value.cast(pwndbg.typeinfo.long)\n\n        elif isinstance(value, gdb.Symbol):\n            symbol = value\n            value = symbol.value()\n            if symbol.is_function:\n                value = value.cast(pwndbg.typeinfo.ulong)\n\n        elif not isinstance(value, (six.string_types, six.integer_types)) \\\n                or isinstance(cls, enum.EnumMeta):\n            # without check for EnumMeta math operations with enums were failing e.g.:\n            #     pwndbg> py import re; flags = 1 | re.MULTILINE\n            return _int.__new__(cls, value, *a, **kw)\n\n        return _int(_int(value, *a, **kw))\n\n# Do not hook 'int' if we are just generating documentation\nif os.environ.get('SPHINX', None) is None:\n    builtins.int = xint\n    globals()['int'] = xint\n    if six.PY3:\n        builtins.long = xint\n        globals()['long'] = xint\n", "path": "pwndbg/inthook.py"}, {"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCommon types, and routines for manually loading types from file\nvia GCC.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport glob\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nimport gdb\n\nimport pwndbg.events\nimport pwndbg.gcc\nimport pwndbg.memoize\n\nmodule = sys.modules[__name__]\n\n\ndef is_pointer(value):\n    type = value\n\n    if isinstance(value, gdb.Value):\n        type = value.type\n\n    type = type.strip_typedefs()\n    return type.code == gdb.TYPE_CODE_PTR\n\n\ndef lookup_types(*types):\n    for type_str in types:\n        try:\n            return gdb.lookup_type(type_str)\n        except Exception as e:\n            exc = e\n    raise exc\n\n\n@pwndbg.events.new_objfile\n@pwndbg.events.start\n@pwndbg.events.stop\ndef update():\n\n    module.char   = gdb.lookup_type('char')\n    module.ulong  = lookup_types('unsigned long', 'uint', 'u32', 'uint32')\n    module.long   = lookup_types('long', 'int', 'i32', 'int32')\n    module.uchar  = lookup_types('unsigned char', 'ubyte', 'u8', 'uint8')\n    module.ushort = lookup_types('unsigned short', 'ushort', 'u16', 'uint16')\n    module.uint   = lookup_types('unsigned int', 'uint', 'u32', 'uint32')\n    module.void   = lookup_types('void', '()')\n    module.uint8  = module.uchar\n    module.uint16 = module.ushort\n    module.uint32 = module.uint\n    module.uint64 = lookup_types('unsigned long long', 'ulong', 'u64', 'uint64')\n\n    module.int8   = lookup_types('char', 'i8', 'int8')\n    module.int16  = lookup_types('short', 'i16', 'int16')\n    module.int32  = lookup_types('int', 'i32', 'int32')\n    module.int64  = lookup_types('long long', 'long', 'i64', 'int64')\n\n    module.ssize_t = module.long\n    module.size_t = module.ulong\n\n    module.pvoid  = void.pointer()\n    module.ppvoid = pvoid.pointer()\n    module.pchar  = char.pointer()\n\n    module.ptrsize = pvoid.sizeof\n\n    if pvoid.sizeof == 4: module.ptrdiff = uint32\n    if pvoid.sizeof == 8: module.ptrdiff = uint64\n\n    module.null = gdb.Value(0).cast(void)\n\n# Call it once so we load all of the types\nupdate()\n\ntempdir = tempfile.gettempdir() + '/pwndbg'\nif not os.path.exists(tempdir):\n    os.mkdir(tempdir)\n\n# Trial and error until things work\nblacklist = ['regexp.h', 'xf86drm.h', 'libxl_json.h', 'xf86drmMode.h',\n'caca0.h', 'xenguest.h', '_libxl_types_json.h', 'term_entry.h', 'slcurses.h',\n'pcreposix.h', 'sudo_plugin.h', 'tic.h', 'sys/elf.h', 'sys/vm86.h',\n'xenctrlosdep.h', 'xenctrl.h', 'cursesf.h', 'cursesm.h', 'gdbm.h', 'dbm.h',\n'gcrypt-module.h', 'term.h', 'gmpxx.h', 'pcap/namedb.h', 'pcap-namedb.h',\n'evr.h', 'mpc.h', 'fdt.h', 'mpfr.h', 'evrpc.h', 'png.h', 'zlib.h', 'pngconf.h',\n'libelfsh.h', 'libmjollnir.h', 'hwloc.h', 'ares.h', 'revm.h', 'ares_rules.h',\n'libunwind-ptrace.h', 'libui.h', 'librevm-color.h', 'libedfmt.h','revm-objects.h',\n'libetrace.h', 'revm-io.h','libasm-mips.h','libstderesi.h','libasm.h','libaspect.h',\n'libunwind.h','libmjollnir-objects.h','libunwind-coredump.h','libunwind-dynamic.h']\n\ndef load(name):\n    \"\"\"Load symbol by name from headers in standard system include directory\"\"\"\n    try:\n        return gdb.lookup_type(name)\n    except gdb.error:\n        pass\n\n    # s, _ = gdb.lookup_symbol(name)\n\n    # Try to find an architecture-specific include path\n    arch = pwndbg.arch.current.split(':')[0]\n\n    include_dir = glob.glob('/usr/%s*/include' % arch)\n\n    if include_dir:\n        include_dir = include_dir[0]\n    else:\n        include_dir = '/usr/include'\n\n    source = '#include <fstream>\\n'\n\n    for subdir in ['', 'sys', 'netinet']:\n        dirname = os.path.join(include_dir, subdir)\n        for path in glob.glob(os.path.join(dirname, '*.h')):\n            if any(b in path for b in blacklist):\n              continue\n            print(path)\n            source += '#include \"%s\"\\n' % path\n\n\n    source += '''\n{name} foo;\n'''.format(**locals())\n\n    filename = '%s/%s_%s.cc' % (tempdir, arch, '-'.join(name.split()))\n\n    with open(filename, 'w+') as f:\n        f.write(source)\n        f.flush()\n        os.fsync(f.fileno())\n\n    compile(filename)\n\n    return gdb.lookup_type(name)\n\ndef compile(filename=None, address=0):\n    \"\"\"Compile and extract symbols from specified file\"\"\"\n    if filename is None:\n        print(\"Specify a filename to compile.\")\n        return\n\n    objectname = os.path.splitext(filename)[0] + \".o\"\n\n    if not os.path.exists(objectname):\n        gcc     = pwndbg.gcc.which()\n        gcc    += ['-w', '-c', '-g', filename, '-o', objectname]\n        try:\n            subprocess.check_output(gcc)\n        except subprocess.CalledProcessError as e:\n            return\n\n    add_symbol_file(objectname, address)\n\ndef add_symbol_file(filename=None, address=0):\n    \"\"\"Read additional symbol table information from the object file filename\"\"\"\n    if filename is None:\n        print(\"Specify a symbol file to add.\")\n        return\n\n    with pwndbg.events.Pause():\n        gdb.execute('add-symbol-file %s %s' % (filename, address), from_tty=False, to_string=True)\n\ndef read_gdbvalue(type_name, addr):\n    \"\"\" Read the memory contents at addr and interpret them as a GDB value with the given type \"\"\"\n    gdb_type = pwndbg.typeinfo.load(type_name)\n    return gdb.Value(addr).cast(gdb_type.pointer()).dereference()\n", "path": "pwndbg/typeinfo.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis hook is necessary for compatibility with Python2.7 versions of GDB\nsince they cannot directly cast to integer a gdb.Value object that is\nnot already an integer type.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport enum\nimport os\n\nimport gdb\nimport six\nfrom future.utils import with_metaclass\n\nimport pwndbg.typeinfo\n\nif six.PY2:\n    import __builtin__ as builtins\nelse:\n    import builtins\n\n_int = builtins.int\n\n\n# We need this class to get isinstance(7, xint) to return True\nclass IsAnInt(type):\n    def __instancecheck__(self, other):\n        return isinstance(other, _int)\n\n\nclass xint(with_metaclass(IsAnInt, builtins.int)):\n    def __new__(cls, value, *a, **kw):\n        if isinstance(value, gdb.Value):\n            if pwndbg.typeinfo.is_pointer(value):\n                value = value.cast(pwndbg.typeinfo.size_t)\n            else:\n                value = value.cast(pwndbg.typeinfo.ssize_t)\n\n        elif isinstance(value, gdb.Symbol):\n            symbol = value\n            value = symbol.value()\n            if symbol.is_function:\n                value = value.cast(pwndbg.typeinfo.size_t)\n\n        elif not isinstance(value, (six.string_types, six.integer_types)) \\\n                or isinstance(cls, enum.EnumMeta):\n            # without check for EnumMeta math operations with enums were failing e.g.:\n            #     pwndbg> py import re; flags = 1 | re.MULTILINE\n            return _int.__new__(cls, value, *a, **kw)\n\n        return _int(_int(value, *a, **kw))\n\n# Do not hook 'int' if we are just generating documentation\nif os.environ.get('SPHINX', None) is None:\n    builtins.int = xint\n    globals()['int'] = xint\n    if six.PY3:\n        builtins.long = xint\n        globals()['long'] = xint\n", "path": "pwndbg/inthook.py"}, {"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCommon types, and routines for manually loading types from file\nvia GCC.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport glob\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nimport gdb\n\nimport pwndbg.events\nimport pwndbg.gcc\nimport pwndbg.memoize\n\nmodule = sys.modules[__name__]\n\n\ndef is_pointer(value):\n    type = value\n\n    if isinstance(value, gdb.Value):\n        type = value.type\n\n    type = type.strip_typedefs()\n    return type.code == gdb.TYPE_CODE_PTR\n\n\ndef lookup_types(*types):\n    for type_str in types:\n        try:\n            return gdb.lookup_type(type_str)\n        except Exception as e:\n            exc = e\n    raise exc\n\n\n@pwndbg.events.new_objfile\n@pwndbg.events.start\n@pwndbg.events.stop\ndef update():\n\n    module.char   = gdb.lookup_type('char')\n    module.ulong  = lookup_types('unsigned long', 'uint', 'u32', 'uint32')\n    module.long   = lookup_types('long', 'int', 'i32', 'int32')\n    module.uchar  = lookup_types('unsigned char', 'ubyte', 'u8', 'uint8')\n    module.ushort = lookup_types('unsigned short', 'ushort', 'u16', 'uint16')\n    module.uint   = lookup_types('unsigned int', 'uint', 'u32', 'uint32')\n    module.void   = lookup_types('void', '()')\n    module.uint8  = module.uchar\n    module.uint16 = module.ushort\n    module.uint32 = module.uint\n    module.uint64 = lookup_types('unsigned long long', 'ulong', 'u64', 'uint64')\n\n    module.int8   = lookup_types('char', 'i8', 'int8')\n    module.int16  = lookup_types('short', 'i16', 'int16')\n    module.int32  = lookup_types('int', 'i32', 'int32')\n    module.int64  = lookup_types('long long', 'long', 'i64', 'int64')\n\n    module.pvoid  = void.pointer()\n    module.ppvoid = pvoid.pointer()\n    module.pchar  = char.pointer()\n\n    module.ptrsize = pvoid.sizeof\n\n    if pvoid.sizeof == 4: \n        module.ptrdiff = module.uint32\n        module.size_t = module.uint32\n        module.ssize_t = module.int32\n    elif pvoid.sizeof == 8: \n        module.ptrdiff = module.uint64\n        module.size_t = module.uint64\n        module.ssize_t = module.int64\n    else:\n        raise Exception('Pointer size not supported')\n    module.null = gdb.Value(0).cast(void)\n\n# Call it once so we load all of the types\nupdate()\n\ntempdir = tempfile.gettempdir() + '/pwndbg'\nif not os.path.exists(tempdir):\n    os.mkdir(tempdir)\n\n# Trial and error until things work\nblacklist = ['regexp.h', 'xf86drm.h', 'libxl_json.h', 'xf86drmMode.h',\n'caca0.h', 'xenguest.h', '_libxl_types_json.h', 'term_entry.h', 'slcurses.h',\n'pcreposix.h', 'sudo_plugin.h', 'tic.h', 'sys/elf.h', 'sys/vm86.h',\n'xenctrlosdep.h', 'xenctrl.h', 'cursesf.h', 'cursesm.h', 'gdbm.h', 'dbm.h',\n'gcrypt-module.h', 'term.h', 'gmpxx.h', 'pcap/namedb.h', 'pcap-namedb.h',\n'evr.h', 'mpc.h', 'fdt.h', 'mpfr.h', 'evrpc.h', 'png.h', 'zlib.h', 'pngconf.h',\n'libelfsh.h', 'libmjollnir.h', 'hwloc.h', 'ares.h', 'revm.h', 'ares_rules.h',\n'libunwind-ptrace.h', 'libui.h', 'librevm-color.h', 'libedfmt.h','revm-objects.h',\n'libetrace.h', 'revm-io.h','libasm-mips.h','libstderesi.h','libasm.h','libaspect.h',\n'libunwind.h','libmjollnir-objects.h','libunwind-coredump.h','libunwind-dynamic.h']\n\ndef load(name):\n    \"\"\"Load symbol by name from headers in standard system include directory\"\"\"\n    try:\n        return gdb.lookup_type(name)\n    except gdb.error:\n        pass\n\n    # s, _ = gdb.lookup_symbol(name)\n\n    # Try to find an architecture-specific include path\n    arch = pwndbg.arch.current.split(':')[0]\n\n    include_dir = glob.glob('/usr/%s*/include' % arch)\n\n    if include_dir:\n        include_dir = include_dir[0]\n    else:\n        include_dir = '/usr/include'\n\n    source = '#include <fstream>\\n'\n\n    for subdir in ['', 'sys', 'netinet']:\n        dirname = os.path.join(include_dir, subdir)\n        for path in glob.glob(os.path.join(dirname, '*.h')):\n            if any(b in path for b in blacklist):\n              continue\n            print(path)\n            source += '#include \"%s\"\\n' % path\n\n\n    source += '''\n{name} foo;\n'''.format(**locals())\n\n    filename = '%s/%s_%s.cc' % (tempdir, arch, '-'.join(name.split()))\n\n    with open(filename, 'w+') as f:\n        f.write(source)\n        f.flush()\n        os.fsync(f.fileno())\n\n    compile(filename)\n\n    return gdb.lookup_type(name)\n\ndef compile(filename=None, address=0):\n    \"\"\"Compile and extract symbols from specified file\"\"\"\n    if filename is None:\n        print(\"Specify a filename to compile.\")\n        return\n\n    objectname = os.path.splitext(filename)[0] + \".o\"\n\n    if not os.path.exists(objectname):\n        gcc     = pwndbg.gcc.which()\n        gcc    += ['-w', '-c', '-g', filename, '-o', objectname]\n        try:\n            subprocess.check_output(gcc)\n        except subprocess.CalledProcessError as e:\n            return\n\n    add_symbol_file(objectname, address)\n\ndef add_symbol_file(filename=None, address=0):\n    \"\"\"Read additional symbol table information from the object file filename\"\"\"\n    if filename is None:\n        print(\"Specify a symbol file to add.\")\n        return\n\n    with pwndbg.events.Pause():\n        gdb.execute('add-symbol-file %s %s' % (filename, address), from_tty=False, to_string=True)\n\ndef read_gdbvalue(type_name, addr):\n    \"\"\" Read the memory contents at addr and interpret them as a GDB value with the given type \"\"\"\n    gdb_type = pwndbg.typeinfo.load(type_name)\n    return gdb.Value(addr).cast(gdb_type.pointer()).dereference()\n", "path": "pwndbg/typeinfo.py"}]}