forked from vstinner/python-ptrace
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrace.py
More file actions
Latest commit
executable file
·271 lines (236 loc) · 9.99 KB
/
Copy pathstrace.py
File metadata and controls
executable file
·271 lines (236 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env python
from __future__ importprint_function
fromptraceimportPtraceError
fromptrace.debuggerimport (PtraceDebugger, Application,
ProcessExit, ProcessSignal, NewProcessEvent, ProcessExecution)
fromptrace.syscallimport (SYSCALL_NAMES, SYSCALL_PROTOTYPES,
FILENAME_ARGUMENTS, SOCKET_SYSCALL_NAMES)
fromptrace.func_callimportFunctionCallOptions
fromsysimportstderr, exit
fromoptparseimportOptionParser
fromloggingimportgetLogger, error
fromptrace.errorimportPTRACE_ERRORS, writeError
fromptrace.ctypes_toolsimportformatAddress
importre
classSyscallTracer(Application):
def__init__(self):
Application.__init__(self)
# Parse self.options
self.parseOptions()
# Setup output (log)
self.setupLog()
defsetupLog(self):
ifself.options.output:
fd=open(self.options.output, 'w')
self._output=fd
else:
fd=stderr
self._output=None
self._setupLog(fd)
defparseOptions(self):
parser=OptionParser(
usage="%prog [options] -- program [arg1 arg2 ...]")
self.createCommonOptions(parser)
parser.add_option("--enter", help="Show system call enter and exit",
action="store_true", default=False)
parser.add_option("--profiler", help="Use profiler",
action="store_true", default=False)
parser.add_option("--type", help="Display arguments type and result type (default: no)",
action="store_true", default=False)
parser.add_option("--name", help="Display argument name (default: no)",
action="store_true", default=False)
parser.add_option("--string-length", "-s", help="String max length (default: 300)",
type="int", default=300)
parser.add_option("--array-count", help="Maximum number of array items (default: 20)",
type="int", default=20)
parser.add_option("--raw-socketcall", help="Raw socketcall form",
action="store_true", default=False)
parser.add_option("--output", "-o", help="Write output to specified log file",
type="str")
parser.add_option("--ignore-regex", help="Regex used to filter syscall names (e.g. --ignore='^(gettimeofday|futex|f?stat)')",
type="str")
parser.add_option("--address", help="Display structure address",
action="store_true", default=False)
parser.add_option("--syscalls", '-e', help="Comma separated list of shown system calls (other will be skipped)",
type="str", default=None)
parser.add_option("--socket", help="Show only socket functions",
action="store_true", default=False)
parser.add_option("--filename", help="Show only syscall using filename",
action="store_true", default=False)
parser.add_option("--show-pid",
help="Prefix line with process identifier",
action="store_true", default=False)
parser.add_option("--list-syscalls",
help="Display system calls and exit",
action="store_true", default=False)
parser.add_option("-i", "--show-ip",
help="print instruction pointer at time of syscall",
action="store_true", default=False)
self.createLogOptions(parser)
self.options, self.program=parser.parse_args()
ifself.options.list_syscalls:
syscalls=list(SYSCALL_NAMES.items())
syscalls.sort(key=lambdadata: data[0])
fornum, nameinsyscalls:
print("% 3s: %s"% (num, name))
exit(0)
ifself.options.pidisNoneandnotself.program:
parser.print_help()
exit(1)
# Create "only" filter
only=set()
ifself.options.syscalls:
# split by "," and remove spaces
foriteminself.options.syscalls.split(","):
item=item.strip()
ifnotitemoriteminonly:
continue
ok=True
valid_names=list(SYSCALL_NAMES.values())
fornameinonly:
ifnamenotinvalid_names:
print("ERROR: unknown syscall %r"%name, file=stderr)
ok=False
ifnotok:
print(file=stderr)
print(
"Use --list-syscalls options to get system calls list", file=stderr)
exit(1)
# remove duplicates
only.add(item)
ifself.options.filename:
forsyscall, formatinSYSCALL_PROTOTYPES.items():
restype, arguments=format
ifany(argnameinFILENAME_ARGUMENTSforargtype, argnameinarguments):
only.add(syscall)
ifself.options.socket:
only|=SOCKET_SYSCALL_NAMES
self.only=only
ifself.options.ignore_regex:
try:
self.ignore_regex=re.compile(self.options.ignore_regex)
exceptExceptionaserr:
print("Invalid regular expression! %s"%err)
print("(regex: %r)"%self.options.ignore_regex)
exit(1)
else:
self.ignore_regex=None
ifself.options.fork:
self.options.show_pid=True
self.processOptions()
defignoreSyscall(self, syscall):
name=syscall.name
ifself.onlyand (namenotinself.only):
returnTrue
ifself.ignore_regexandself.ignore_regex.match(name):
returnTrue
returnFalse
defdisplaySyscall(self, syscall):
text=syscall.format()
ifsyscall.resultisnotNone:
text="%-40s = %s"% (text, syscall.result_text)
prefix= []
ifself.options.show_pid:
prefix.append("[%s]"%syscall.process.pid)
ifself.options.show_ip:
prefix.append("[%s]"%formatAddress(syscall.instr_pointer))
ifprefix:
text=''.join(prefix) +' '+text
error(text)
defsyscallTrace(self, process):
# First query to break at next syscall
self.prepareProcess(process)
whileTrue:
# No more process? Exit
ifnotself.debugger:
break
# Wait until next syscall enter
try:
event=self.debugger.waitSyscall()
exceptProcessExitasevent:
self.processExited(event)
continue
exceptProcessSignalasevent:
event.display()
event.process.syscall(event.signum)
continue
exceptNewProcessEventasevent:
self.newProcess(event)
continue
exceptProcessExecutionasevent:
self.processExecution(event)
continue
# Process syscall enter or exit
self.syscall(event.process)
defsyscall(self, process):
state=process.syscall_state
syscall=state.event(self.syscall_options)
ifsyscalland (syscall.resultisnotNoneorself.options.enter):
self.displaySyscall(syscall)
# Break at next syscall
process.syscall()
defprocessExited(self, event):
# Display syscall which has not exited
state=event.process.syscall_state
if (state.next_event=="exit") \
and (notself.options.enter) \
andstate.syscall:
self.displaySyscall(state.syscall)
# Display exit message
error("*** %s ***"%event)
defprepareProcess(self, process):
process.syscall()
process.syscall_state.ignore_callback=self.ignoreSyscall
defnewProcess(self, event):
process=event.process
error("*** New process %s ***"%process.pid)
self.prepareProcess(process)
process.parent.syscall()
defprocessExecution(self, event):
process=event.process
error("*** Process %s execution ***"%process.pid)
process.syscall()
defrunDebugger(self):
# Create debugger and traced process
self.setupDebugger()
process=self.createProcess()
ifnotprocess:
return
self.syscall_options=FunctionCallOptions(
write_types=self.options.type,
write_argname=self.options.name,
string_max_length=self.options.string_length,
replace_socketcall=notself.options.raw_socketcall,
write_address=self.options.address,
max_array_count=self.options.array_count,
)
self.syscall_options.instr_pointer=self.options.show_ip
self.syscallTrace(process)
defmain(self):
ifself.options.profiler:
fromptrace.profilerimportrunProfiler
runProfiler(getLogger(), self._main)
else:
self._main()
ifself._outputisnotNone:
self._output.close()
def_main(self):
self.debugger=PtraceDebugger()
try:
self.runDebugger()
exceptProcessExitasevent:
self.processExited(event)
exceptPtraceErroraserr:
error("ptrace() error: %s"%err)
exceptKeyboardInterrupt:
error("Interrupted.")
exceptPTRACE_ERRORSaserr:
writeError(getLogger(), err, "Debugger error")
self.debugger.quit()
defcreateChild(self, program):
pid=Application.createChild(self, program)
error("execve(%s, %s, [/* 40 vars */]) = %s"% (
program[0], program, pid))
returnpid
if__name__=="__main__":
SyscallTracer().main()