blob: feb1561f95d6dcb962e923e157d335e606ea8bc9 [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
108def find_kernel_headers():
109 """try to find the directory containing the kernel headers for this machine"""
110 status, version = commands.getstatusoutput( "uname -r" ) # get Linux kernel version
111 if status != 0:
112 D("could not execute 'uname -r' command properly")
113 return None
114
115 # get rid of the "-xenU" suffix that is found in Xen virtual machines
116 if len(version) > 5 and version[-5:] == "-xenU":
117 version = version[:-5]
118
119 path = "/usr/src/linux-headers-" + version
120 D("probing %s for kernel headers" % (path+"/include"))
121 ret = os.path.isdir( path )
122 if ret:
123 D("found kernel headers in: %s" % (path + "/include"))
124 return path
125 return None
126
127
128# parser for the SYSCALLS.TXT file
129#
130class SysCallsTxtParser:
131 def __init__(self):
132 self.syscalls = []
133 self.lineno = 0
134
135 def E(msg):
136 print "%d: %s" % (self.lineno, msg)
137
138 def parse_line(self, line):
139 pos_lparen = line.find('(')
140 E = self.E
141 if pos_lparen < 0:
142 E("missing left parenthesis in '%s'" % line)
143 return
144
145 pos_rparen = line.rfind(')')
146 if pos_rparen < 0 or pos_rparen <= pos_lparen:
147 E("missing or misplaced right parenthesis in '%s'" % line)
148 return
149
150 return_type = line[:pos_lparen].strip().split()
151 if len(return_type) < 2:
152 E("missing return type in '%s'" % line)
153 return
154
155 syscall_func = return_type[-1]
156 return_type = string.join(return_type[:-1],' ')
157
158 pos_colon = syscall_func.find(':')
159 if pos_colon < 0:
160 syscall_name = syscall_func
161 else:
162 if pos_colon == 0 or pos_colon+1 >= len(syscall_func):
163 E("misplaced colon in '%s'" % line)
164 return
165 syscall_name = syscall_func[pos_colon+1:]
166 syscall_func = syscall_func[:pos_colon]
167
168 if pos_rparen > pos_lparen+1:
169 syscall_params = line[pos_lparen+1:pos_rparen].split(',')
170 params = string.join(syscall_params,',')
171 else:
172 syscall_params = []
173 params = "void"
174
175 number = line[pos_rparen+1:].strip()
176 if number == "stub":
177 syscall_id = -1
178 syscall_id2 = -1
179 else:
180 try:
181 if number[0] == '#':
182 number = number[1:].strip()
183 numbers = string.split(number,',')
184 syscall_id = int(numbers[0])
185 syscall_id2 = syscall_id
186 if len(numbers) > 1:
187 syscall_id2 = int(numbers[1])
188 except:
189 E("invalid syscall number in '%s'" % line)
190 return
191
192 t = { "id" : syscall_id,
193 "id2" : syscall_id2,
194 "name" : syscall_name,
195 "func" : syscall_func,
196 "params" : syscall_params,
197 "decl" : "%-15s %s (%s);" % (return_type, syscall_func, params) }
198
199 self.syscalls.append(t)
200
201 def parse_file(self, file_path):
202 D2("parse_file: %s" % file_path)
203 fp = open(file_path)
204 for line in fp.xreadlines():
205 self.lineno += 1
206 line = line.strip()
207 if not line: continue
208 if line[0] == '#': continue
209 self.parse_line(line)
210
211 fp.close()
212
213
214class Output:
215 def __init__(self,out=sys.stdout):
216 self.out = out
217
218 def write(self,msg):
219 self.out.write(msg)
220
221 def writeln(self,msg):
222 self.out.write(msg)
223 self.out.write("\n")
224
225class StringOutput:
226 def __init__(self):
227 self.line = ""
228
229 def write(self,msg):
230 self.line += msg
231 D2("write '%s'" % msg)
232
233 def writeln(self,msg):
234 self.line += msg + '\n'
235 D2("write '%s\\n'"% msg)
236
237 def get(self):
238 return self.line
239
240
241def create_file_path(path):
242 dirs = []
243 while 1:
244 parent = os.path.dirname(path)
245 if parent == "/":
246 break
247 dirs.append(parent)
248 path = parent
249
250 dirs.reverse()
251 for dir in dirs:
252 #print "dir %s" % dir
253 if os.path.isdir(dir):
254 continue
255 os.mkdir(dir)
256
257def walk_source_files(paths,callback,args,excludes=[]):
258 """recursively walk a list of paths and files, only keeping the source files in directories"""
259 for path in paths:
260 if not os.path.isdir(path):
261 callback(path,args)
262 else:
263 for root, dirs, files in os.walk(path):
264 #print "w-- %s (ex: %s)" % (repr((root,dirs)), repr(excludes))
265 if len(excludes):
266 for d in dirs[:]:
267 if d in excludes:
268 dirs.remove(d)
269 for f in files:
270 r, ext = os.path.splitext(f)
271 if ext in [ ".h", ".c", ".cpp", ".S" ]:
272 callback( "%s/%s" % (root,f), args )
273
274def cleanup_dir(path):
275 """create a directory if needed, and ensure that it is totally empty
276 by removing any existing content in it"""
277 if not os.path.exists(path):
278 os.mkdir(path)
279 else:
280 for root, dirs, files in os.walk(path, topdown=False):
281 if root.endswith("kernel_headers/"):
282 # skip 'kernel_headers'
283 continue
284 for name in files:
285 os.remove(os.path.join(root, name))
286 for name in dirs:
287 os.rmdir(os.path.join(root, name))