-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsearch.py
More file actions
executable file
·187 lines (149 loc) · 5.25 KB
/
csearch.py
File metadata and controls
executable file
·187 lines (149 loc) · 5.25 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
#!/usr/bin/env python3
import os, re
import subprocess as sub
import argparse
# Bash colors
RED = '\033[0;31m'
GREEN = '\033[0;32m'
NC = '\033[0m'
def clean(string):
'''
prepares string for insertion into catsearch regex.
'''
escape_chars = ".^$*+?{}[]|()"
replace_chars = ['.', '^', '$', '*', '+', '?',
'{', '}', '[', ']', '|', '(', ')']
out = string
for og, replace in zip(escape_chars, replace_chars):
out = out.replace(og, replace)
return(out)
def search(fname, token, search_string, display_func):
try:
out = sub.check_output(search_string, shell=1)
out = out.decode('utf-8')
display_func(out)
except sub.CalledProcessError:
# grep errors if it doesn't find anything
pass
def nm_display_func(fname, token, string):
split = string.split('\n')
for word in split:
if token in word:
print("{}{}{}: {}".format(RED, fname, NC, word))
def nmsearch(fname, token):
display_func = lambda string: nm_display_func(fname, token, string)
for flag in ("-D", ""):
search_string = (f"nm {flag} --defined-only -C -l {fname} 2> "
f"/dev/null | grep -n \"{token}\"")
search(fname, token, search_string, display_func)
def cat_display_func(fname, token, string, cat_re):
lines = string.split('\n')
for line in lines:
m = cat_re.search(line)
if m:
line_no = m.group('line_no')
stuff1 = m.group('stuff1')
stuff2 = m.group('stuff2')
print("{}{}{}: {}{}{}: {}{}{}{}{}".format(RED, fname, NC,
GREEN, line_no, NC, stuff1, RED, token, NC, stuff2))
def catsearch(fname, token):
cat_re = re.compile(r"""
^(?P<line_no>(\d*)):
(?P<stuff1>(.*))
(?P<token>({}))
(?P<stuff2>(.*))
""".format(clean(token)),
re.VERBOSE)
display_func = lambda string: cat_display_func(fname, token, string,
cat_re)
search_string = 'cat {} | grep -n \"{}\"'.format(fname, token)
search(fname, token, search_string, display_func)
def check_regex(string, regex):
m = regex.search(string)
if m:
return(True)
return(False)
def is_c_header(fname):
r = re.compile(r'\.(?P<extension>((h)|(hpp)))$')
return(check_regex(fname, r))
def is_c_source(fname):
r = re.compile(r'\.(?P<extension>((c)|(cu)|(cpp)))$')
return(check_regex(fname, r))
def is_object_file(fname):
r = re.compile(r'\.(?P<extension>((so)|(a)|(o)))(\.|$)')
return(check_regex(fname, r))
def search_directory(dname, token, type_check_fun, search_fun, r):
contents = os.listdir(dname)
for thing in contents:
thing = os.path.join(dname, thing)
if os.path.isfile(thing):
if type_check_fun(thing):
search_fun(thing, token)
elif (r and os.path.isdir(thing)):
search_directory(thing, token, type_check_fun, search_fun, r)
def search_main(name, token, type_check_fun, search_fun, r):
if os.path.isfile(name):
if type_check_fun(name):
search_fun(name, token)
else:
raise TypeError("Incorrect file type.")
elif os.path.isdir(name):
search_directory(name, token, type_check_fun, search_fun, r)
else:
raise TypeError("Must be a directory or file.")
def object_main(name, token, r):
search_main(name, token, is_object_file, nmsearch, r)
def source_main(name, token, r):
search_main(name, token, is_c_source, catsearch, r)
def header_main(name, token, r):
search_main(name, token, is_c_header, catsearch, r)
def main():
descr = '''
Utility for locating symbols in C/C++ object files (on Linux).
'''
parser = argparse.ArgumentParser(
allow_abbrev=True,
description=descr)
parser.add_argument('--recursive', '-r', '-R',
action='store_true',
default=False,
help="Recursive mode. Causes subdirectories to be searched.")
parser.add_argument('--object', '-o',
action='store_true',
default=False,
help='Object mode. Searches object files for a symbol.')
parser.add_argument('--source', '-s',
action='store_true',
default=False,
help='Source mode. Searches C/C++/Cuda source files for a symbol.')
parser.add_argument('--header', '-he',
action='store_true',
default=False,
help='Header mode. Searches C/C++/Cuda header files for a symbol.')
parser.add_argument('--target', '-t',
action='store',
type=str,
default='.',
help='Directory or file to search.')
parser.add_argument('symbol',
metavar='symbol',
type=str,
nargs='+',
help='symbol to find')
args = parser.parse_args()
target = os.path.abspath(args.target)
symbol = args.symbol[0]
o_mode = args.object
s_mode = args.source
h_mode = args.header
r = args.recursive
if not (o_mode or s_mode or h_mode):
raise Exception("Must select a mode of operation (-s, -o, -h, etc)")
if o_mode:
object_main(target, symbol, r)
if s_mode:
source_main(target, symbol, r)
if h_mode:
header_main(target, symbol, r)
if __name__ == '__main__':
main()