/
symbolscanner.py
267 lines (245 loc) · 8.73 KB
/
symbolscanner.py
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
from PyQt4 import QtCore
import sys
import os
#import re
import utils
from system import listAllPackages, libraryDirs
#from globals import is_src_ext
def baseLibName(f):
if f.startswith("lib"):
f=f[3:]
p=f.find('.')
if p>0:
f=f[0:p]
return f
def isLibraryDir(dir):
try:
path=os.path.join(dir,'Makefile')
for line in open(path):
s=line.strip()
if s=='TYPE=LIB':
return True
except IOError:
pass
return False
class Scanner:
instance=None
def __init__(self,ws,libSyms=None,wsSyms=None,wsLibs=None):
self.ws=ws
self.libraryMap={}
if libSyms and wsSyms and wsLibs:
self.librarySymbols=libSyms
self.workspaceSymbols=wsSyms
self.workspaceLibSyms=wsLibs
else:
self.packages=listAllPackages()
if self.isPackageListChanged():
self.libraryMap=self.mapLibrariesToPackages()
self.librarySymbols=self.querySymbols()
self.saveLists()
self.libraryMap={}
else:
utils.timestamp('load library lists')
self.loadLists()
utils.timestamp('Done load')
self.workspaceLibSyms={}
self.workspaceSymbols={}
self.scanWorkspaceSymbols()
def isPackageListChanged(self):
s=QtCore.QSettings()
if s.contains('all_packages'):
old_packages=s.value('all_packages').toString().split(',')
return old_packages != self.packages
return True
def saveLists(self):
s=QtCore.QSettings()
s.setValue('all_packages',','.join(self.packages))
index={}
for i in xrange(0,len(self.packages)):
index[self.packages[i]]=i
all=[]
for sym in self.librarySymbols:
refsIdx=[]
refs=self.librarySymbols.get(sym)
for r in refs:
if r in index:
refsIdx.append(str(index.get(r)))
else:
refsIdx.append(r)
all.append(sym+"."+','.join(refsIdx))
s.setValue('library_symbols',';'.join(all))
s.sync()
def loadLists(self):
s=QtCore.QSettings()
utils.timestamp('load from settings')
ls=s.value('library_symbols').toString()
utils.timestamp('deserialize')
self.librarySymbols={}
all=ls.split(';')
for s in all:
if s:
pos=s.find('.')
if pos>0:
sym=s[0:pos]
refs=s[pos+1:].split(',')
rset=set()
self.librarySymbols[sym]=rset
for r in refs:
try:
rset.add(self.packages[int(r)])
except ValueError:
rset.add(r)
def mapLibrariesToPackages(self):
libmap={}
try:
for package in self.packages:
out,err=utils.call('.','pkg-config','--libs',package)
for token in out.split():
if token.startswith('-l'):
libname='lib{}'.format(token[2:])
static=libname+'.a'
dynamic=libname+'.so'
if not static in libmap:
libmap[static]=set()
libmap.get(static).add(package)
if not dynamic in libmap:
libmap[dynamic]=set()
libmap.get(dynamic).add(package)
except OSError:
pass
return libmap
def parseStatic(self,path,symbols,f):
(out,err)=utils.call('.','objdump','-t','-C',path)
refs=set()
if not f in self.libraryMap:
refs.add(baseLibName(f))
else:
refs=self.libraryMap.get(f)
dump=out.split('\n')
for line in dump:
parts=line.split('\t')
if len(parts)!=2:
continue
left=parts[0].split()
right=parts[1].split()
if (left[-1]=='.text' or left[-1]=='.bss') and not right[-1].startswith('.'):
sym=right[-1]
par=sym.find('(')
if par>0:
sym=sym[0:par]
if not sym in symbols:
s=set()
s.update(refs)
symbols[sym]=s
else:
s=symbols.get(sym)
s.update(refs)
def parseDynamic(self,path,symbols,f):
(out,err)=utils.call('.','objdump','-T','-C',path)
refs=set()
if not f in self.libraryMap:
refs.add(baseLibName(f))
else:
refs=self.libraryMap.get(f)
dump=out.split('\n')
for line in dump:
parts=line.split()
if len(parts)>=7:
sym=parts[-1]
par=sym.find('(')
if par>0:
sym=sym[0:par]
if not sym in symbols:
s=set()
s.update(refs)
symbols[sym]=s
else:
s=symbols.get(sym)
s.update(refs)
def querySymbols(self,printout=False):
symbols={}
dirs=libraryDirs()
for dir in dirs:
try:
files=os.listdir(dir)
files=[f for f in files if f.endswith('.a') or f.endswith('.so')]
for f in files:
path=os.path.join(dir,f)
if f.endswith('.a'):
self.parseStatic(path,symbols,f)
else:
self.parseDynamic(path,symbols,f)
except OSError:
pass
if printout:
for sym in symbols:
print sym
s=symbols.get(sym)
for l in s:
sys.stdout.write(" "+l)
sys.stdout.write('\n')
return symbols
# def scanWorkspaceDirectory(self,dir,files=[]):
# libname=(dir.split('/'))[-1]
# self.removeLibRefs(libname)
# if len(files)==0:
# files=os.listdir(dir)
# files=[f for f in files if is_src_ext(f)]
# for f in files:
# path=os.path.join(dir,f)
# for line in open(path,'r').readlines():
# words=re.split('\W+',line.strip())
# for word in words:
# if not word in self.workspaceSymbols:
# self.workspaceSymbols[word]=set()
# if not libname in self.workspaceLibSyms:
# self.workspaceLibSyms[libname]=set()
# self.workspaceSymbols.get(word).add(libname)
# self.workspaceLibSyms.get(libname).add(word)
def scanWorkspaceSymbols(self,printOut=False):
self.workspaceSymbols.clear()
for dir,subdirs,files in os.walk(os.path.join(self.ws,'out')):
for f in files:
if f.startswith('lib') and f.endswith('.a'):
path=os.path.join(dir,f)
self.parseStatic(path,self.workspaceSymbols,f)
if printOut:
f=open('ws_syms.txt','w')
for s in self.workspaceSymbols:
print>>f, s
dirs=self.workspaceSymbols.get(s)
for d in dirs:
print>>f, ' '+d
f.close()
def setWorkspacePath(self,ws):
self.ws=ws
self.scanWorkspaceSymbols()
def removeLibRefs(self,libname):
if libname.count('/')>0:
libname=(libname.split('/'))[-1]
if libname in self.workspaceLibSyms:
words=self.workspaceLibSyms.get(libname)
for word in words:
self.workspaceSymbols.get(word).remove(libname)
del self.workspaceLibSyms[libname]
def getLibrarySymbols(ws):
if Scanner.instance is None:
Scanner.instance=Scanner(ws)
return (Scanner.instance.librarySymbols,
Scanner.instance.workspaceSymbols,
Scanner.instance.workspaceLibSyms
)
def setInitialResults(ws,libSyms,wsSyms,wsLibs):
Scanner.instance=Scanner(ws,libSyms,wsSyms,wsLibs)
def rescanOnFileSave(filepath):
dir=os.path.dirname(filepath)
if Scanner.instance and isLibraryDir(dir):
Scanner.instance.scanWorkspaceDirectory(dir)
def setWorkspacePath(ws):
if Scanner.instance:
Scanner.instance.setWorkspacePath(ws)
return True
return False
if __name__=='__main__':
s=Scanner('/home/amir/workspace')
s.queryWorkspaceSymbols(True)