blob: 0bc947b882530398d6b463510a53d9405ff9212a [file] [log] [blame]
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -07001# common python utility routines for the Bionic tool scripts
2
3import sys, os, commands, string
4
5# support Bionic architectures, add new ones as appropriate
6#
7bionic_archs = [ "arm", "x86" ]
8
9# basic debugging trace support
10# call D_setlevel to set the verbosity level
11# and D(), D2(), D3(), D4() to add traces
12#
13verbose = 1
14
15def D(msg):
16 global verbose
17 if verbose > 0:
18 print msg
19
20def D2(msg):
21 global verbose
22 if verbose >= 2:
23 print msg
24
25def D3(msg):
26 global verbose
27 if verbose >= 3:
28 print msg
29
30def D4(msg):
31 global verbose
32 if verbose >= 4:
33 print msg
34
35def D_setlevel(level):
36 global verbose
37 verbose = level
38
39
40def find_dir_of(path):
41 '''return the directory name of 'path', or "." if there is none'''
42 # remove trailing slash
43 if len(path) > 1 and path[-1] == '/':
44 path = path[:-1]
45
46 # find parent directory name
47 d = os.path.dirname(path)
48 if d == "":
49 return "."
50 else:
51 return d
52
53# other stuff
54#
55#
56def find_file_from_upwards(from_path,target_file):
57 """find a file in the current directory or its parents. if 'from_path' is None,
58 seach from the current program's directory"""
59 path = from_path
60 if path == None:
61 path = find_dir_of(sys.argv[0])
62 D("this script seems to be located in: %s" % path)
63
64 while 1:
65 if path == "":
66 path = "."
67
68 file = path + "/" + target_file
69 D("probing "+file)
70
71 if os.path.isfile(file):
72 D("found %s in %s" % (target_file, path))
73 return file
74
75 if path == ".":
76 break
77
78 path = os.path.dirname(path)
79
80 path = ""
81 while 1:
82 path = "../" + path
83 file = path + target_file
84 D("probing "+file)
85
86 if os.path.isfile(file):
87 D("found %s in %s" % (target_file, path))
88 return file
89
90
91 return None
92
93def find_bionic_root():
94 '''find the root of the Bionic source tree. we check for the SYSCALLS.TXT file
95 from the location of the current program's directory.'''
96
97 # note that we can't use find_file_from_upwards() since we can't use os.path.abspath
98 # that's because in some cases the p4 client is in a symlinked directory, and this
99 # function will return the real path instead, which later creates problems when
100 # p4 commands are issued
101 #
102 file = find_file_from_upwards(None, "SYSCALLS.TXT")
103 if file:
104 return os.path.dirname(file)
105 else:
106 return None
107
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200108def find_original_kernel_headers():
109 """try to find the directory containing the original kernel headers"""
110 bionic_root = find_bionic_root()
111 if not bionic_root:
112 D("Could not find Bionic root !!")
113 return None
114
115 path = os.path.normpath(bionic_root + "/../../external/kernel-headers/original")
116 if not os.path.isdir(path):
117 D("Could not find %s" % (path))
118 return None
119
120 return path
121
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700122def find_kernel_headers():
123 """try to find the directory containing the kernel headers for this machine"""
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200124
125 # First try to find the original kernel headers.
126 ret = find_original_kernel_headers()
127 if ret:
128 D("found original kernel headers in: %s" % (ret))
129 return ret
130
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700131 status, version = commands.getstatusoutput( "uname -r" ) # get Linux kernel version
132 if status != 0:
133 D("could not execute 'uname -r' command properly")
134 return None
135
136 # get rid of the "-xenU" suffix that is found in Xen virtual machines
137 if len(version) > 5 and version[-5:] == "-xenU":
138 version = version[:-5]
139
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200140 path = "/usr/src/linux-headers-" + version + "/include"
141 D("probing %s for kernel headers" % (path))
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700142 ret = os.path.isdir( path )
143 if ret:
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200144 D("found kernel headers in: %s" % (path))
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700145 return path
146 return None
147
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200148def find_arch_header(kernel_headers,arch,header):
149 # First, try in <root>/arch/<arm>/include/<header>
150 # corresponding to the location in the kernel source tree for
151 # certain architectures (e.g. arm).
152 path = "%s/arch/%s/include/asm/%s" % (kernel_headers, arch, header)
153 D("Probing for %s" % path)
154 if os.path.exists(path):
155 return path
156
157 # Try <root>/asm-<arch>/include/<header> corresponding to the location
158 # in the kernel source tree for other architectures (e.g. x86).
159 path = "%s/include/asm-%s/%s" % (kernel_headers, arch, header)
160 D("Probing for %s" % path)
161 if os.path.exists(path):
162 return path
163
164 # Otherwise, look under <root>/asm-<arch>/<header> corresponding
165 # the original kernel headers directory
166 path = "%s/asm-%s/%s" % (kernel_headers, arch, header)
167 D("Probing for %s" % path)
168 if os.path.exists(path):
169 return path
170
171
172 return None
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700173
174# parser for the SYSCALLS.TXT file
175#
176class SysCallsTxtParser:
177 def __init__(self):
178 self.syscalls = []
179 self.lineno = 0
180
181 def E(msg):
182 print "%d: %s" % (self.lineno, msg)
183
184 def parse_line(self, line):
The Android Open Source Project4e468ed2008-12-17 18:03:48 -0800185 """ parse a syscall spec line.
186
187 line processing, format is
188 return type func_name[:syscall_name[:call_id]] ( [paramlist] ) (syscall_number[,syscall_number_x86])|stub
189 """
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700190 pos_lparen = line.find('(')
191 E = self.E
192 if pos_lparen < 0:
193 E("missing left parenthesis in '%s'" % line)
194 return
195
196 pos_rparen = line.rfind(')')
197 if pos_rparen < 0 or pos_rparen <= pos_lparen:
198 E("missing or misplaced right parenthesis in '%s'" % line)
199 return
200
201 return_type = line[:pos_lparen].strip().split()
202 if len(return_type) < 2:
203 E("missing return type in '%s'" % line)
204 return
205
206 syscall_func = return_type[-1]
207 return_type = string.join(return_type[:-1],' ')
The Android Open Source Project4e468ed2008-12-17 18:03:48 -0800208 call_id = -1
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700209
210 pos_colon = syscall_func.find(':')
211 if pos_colon < 0:
212 syscall_name = syscall_func
213 else:
214 if pos_colon == 0 or pos_colon+1 >= len(syscall_func):
215 E("misplaced colon in '%s'" % line)
216 return
The Android Open Source Project4e468ed2008-12-17 18:03:48 -0800217
218 # now find if there is a call_id for a dispatch-type syscall
219 # after the optional 2nd colon
220 pos_colon2 = syscall_func.find(':', pos_colon + 1)
221 if pos_colon2 < 0:
222 syscall_name = syscall_func[pos_colon+1:]
223 syscall_func = syscall_func[:pos_colon]
224 else:
225 if pos_colon2+1 >= len(syscall_func):
226 E("misplaced colon2 in '%s'" % line)
227 return
228 syscall_name = syscall_func[(pos_colon+1):pos_colon2]
229 call_id = int(syscall_func[pos_colon2+1:])
230 syscall_func = syscall_func[:pos_colon]
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700231
232 if pos_rparen > pos_lparen+1:
233 syscall_params = line[pos_lparen+1:pos_rparen].split(',')
234 params = string.join(syscall_params,',')
235 else:
236 syscall_params = []
237 params = "void"
238
239 number = line[pos_rparen+1:].strip()
240 if number == "stub":
241 syscall_id = -1
242 syscall_id2 = -1
243 else:
244 try:
245 if number[0] == '#':
246 number = number[1:].strip()
247 numbers = string.split(number,',')
248 syscall_id = int(numbers[0])
249 syscall_id2 = syscall_id
250 if len(numbers) > 1:
251 syscall_id2 = int(numbers[1])
252 except:
253 E("invalid syscall number in '%s'" % line)
254 return
255
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200256 global verbose
257 if verbose >= 2:
258 if call_id < 0:
David 'Digit' Turner70b16682012-01-30 17:17:58 +0100259 print "%s: %d,%d" % (syscall_name, syscall_id, syscall_id2)
David 'Digit' Turnerfc269312010-10-11 22:11:06 +0200260 else:
David 'Digit' Turner70b16682012-01-30 17:17:58 +0100261 print "%s(%d): %d,%d" % (syscall_name, call_id, syscall_id, syscall_id2)
Shin-ichiro KAWASAKIce0595d2009-09-01 19:03:06 +0900262
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700263 t = { "id" : syscall_id,
264 "id2" : syscall_id2,
The Android Open Source Project4e468ed2008-12-17 18:03:48 -0800265 "cid" : call_id,
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -0700266 "name" : syscall_name,
267 "func" : syscall_func,
268 "params" : syscall_params,
269 "decl" : "%-15s %s (%s);" % (return_type, syscall_func, params) }
270
271 self.syscalls.append(t)
272
273 def parse_file(self, file_path):
274 D2("parse_file: %s" % file_path)
275 fp = open(file_path)
276 for line in fp.xreadlines():
277 self.lineno += 1
278 line = line.strip()
279 if not line: continue
280 if line[0] == '#': continue
281 self.parse_line(line)
282
283 fp.close()
284
285
286class Output:
287 def __init__(self,out=sys.stdout):
288 self.out = out
289
290 def write(self,msg):
291 self.out.write(msg)
292
293 def writeln(self,msg):
294 self.out.write(msg)
295 self.out.write("\n")
296
297class StringOutput:
298 def __init__(self):
299 self.line = ""
300
301 def write(self,msg):
302 self.line += msg
303 D2("write '%s'" % msg)
304
305 def writeln(self,msg):
306 self.line += msg + '\n'
307 D2("write '%s\\n'"% msg)
308
309 def get(self):
310 return self.line
311
312
313def create_file_path(path):
314 dirs = []
315 while 1:
316 parent = os.path.dirname(path)
317 if parent == "/":
318 break
319 dirs.append(parent)
320 path = parent
321
322 dirs.reverse()
323 for dir in dirs:
324 #print "dir %s" % dir
325 if os.path.isdir(dir):
326 continue
327 os.mkdir(dir)
328
329def walk_source_files(paths,callback,args,excludes=[]):
330 """recursively walk a list of paths and files, only keeping the source files in directories"""
331 for path in paths:
332 if not os.path.isdir(path):
333 callback(path,args)
334 else:
335 for root, dirs, files in os.walk(path):
336 #print "w-- %s (ex: %s)" % (repr((root,dirs)), repr(excludes))
337 if len(excludes):
338 for d in dirs[:]:
339 if d in excludes:
340 dirs.remove(d)
341 for f in files:
342 r, ext = os.path.splitext(f)
343 if ext in [ ".h", ".c", ".cpp", ".S" ]:
344 callback( "%s/%s" % (root,f), args )
345
346def cleanup_dir(path):
347 """create a directory if needed, and ensure that it is totally empty
348 by removing any existing content in it"""
349 if not os.path.exists(path):
350 os.mkdir(path)
351 else:
352 for root, dirs, files in os.walk(path, topdown=False):
353 if root.endswith("kernel_headers/"):
354 # skip 'kernel_headers'
355 continue
356 for name in files:
357 os.remove(os.path.join(root, name))
358 for name in dirs:
359 os.rmdir(os.path.join(root, name))