1 # common python utility routines for the Bionic tool scripts
3 import sys, os, commands, string, commands
5 # basic debugging trace support
6 # call D_setlevel to set the verbosity level
7 # and D(), D2(), D3(), D4() to add traces
12 sys.stderr.write( find_program_name() + ": error: " )
13 sys.stderr.write( msg )
36 def D_setlevel(level):
44 def find_program_name():
45 return os.path.basename(sys.argv[0])
47 def find_program_dir():
48 return os.path.dirname(sys.argv[0])
50 def find_file_from_upwards(from_path,target_file):
51 """find a file in the current directory or its parents. if 'from_path' is None,
52 seach from the current program's directory"""
55 path = os.path.realpath(sys.argv[0])
56 path = os.path.dirname(path)
57 D("this script seems to be located in: %s" % path)
64 file = path + "/" + target_file
66 if os.path.isfile(file):
67 D("found %s in %s" % (target_file, path))
73 path = os.path.dirname(path)
75 def find_bionic_root():
76 file = find_file_from_upwards(None, "SYSCALLS.TXT")
78 return os.path.dirname(file)
82 def find_kernel_headers():
83 """try to find the directory containing the kernel headers for this machine"""
84 status, version = commands.getstatusoutput( "uname -r" ) # get Linux kernel version
86 D("could not execute 'uname -r' command properly")
89 # get rid of the "-xenU" suffix that is found in Xen virtual machines
90 if len(version) > 5 and version[-5:] == "-xenU":
91 version = version[:-5]
93 path = "/usr/src/linux-headers-" + version
94 D("probing %s for kernel headers" % (path+"/include"))
95 ret = os.path.isdir( path )
97 D("found kernel headers in: %s" % (path + "/include"))
102 # parser for the SYSCALLS.TXT file
104 class SysCallsTxtParser:
110 print "%d: %s" % (self.lineno, msg)
112 def parse_line(self, line):
113 pos_lparen = line.find('(')
116 E("missing left parenthesis in '%s'" % line)
119 pos_rparen = line.rfind(')')
120 if pos_rparen < 0 or pos_rparen <= pos_lparen:
121 E("missing or misplaced right parenthesis in '%s'" % line)
124 return_type = line[:pos_lparen].strip().split()
125 if len(return_type) < 2:
126 E("missing return type in '%s'" % line)
129 syscall_func = return_type[-1]
130 return_type = string.join(return_type[:-1],' ')
132 pos_colon = syscall_func.find(':')
134 syscall_name = syscall_func
136 if pos_colon == 0 or pos_colon+1 >= len(syscall_func):
137 E("misplaced colon in '%s'" % line)
139 syscall_name = syscall_func[pos_colon+1:]
140 syscall_func = syscall_func[:pos_colon]
142 if pos_rparen > pos_lparen+1:
143 syscall_params = line[pos_lparen+1:pos_rparen].split(',')
144 params = string.join(syscall_params,',')
149 number = line[pos_rparen+1:].strip()
156 number = number[1:].strip()
157 numbers = string.split(number,',')
158 syscall_id = int(numbers[0])
159 syscall_id2 = syscall_id
161 syscall_id2 = int(numbers[1])
163 E("invalid syscall number in '%s'" % line)
166 t = { "id" : syscall_id,
168 "name" : syscall_name,
169 "func" : syscall_func,
170 "params" : syscall_params,
171 "decl" : "%-15s %s (%s);" % (return_type, syscall_func, params) }
173 self.syscalls.append(t)
175 def parse_file(self, file_path):
177 for line in fp.xreadlines():
180 if not line: continue
181 if line[0] == '#': continue
182 self.parse_line(line)
188 def __init__(self,out=sys.stdout):
194 def writeln(self,msg):
204 D2("write '%s'" % msg)
206 def writeln(self,msg):
207 self.line += msg + '\n'
208 D2("write '%s\\n'"% msg)
214 def create_file_path(path):
217 parent = os.path.dirname(path)
218 #print "parent: %s <- %s" % (parent, path)
219 if parent == "/" or parent == "":
226 #print "dir %s" % dir
227 if os.path.isdir(dir):
231 def walk_source_files(paths,callback,args,excludes=[]):
232 """recursively walk a list of paths and files, only keeping the source files in directories"""
234 if not os.path.isdir(path):
237 for root, dirs, files in os.walk(path):
238 #print "w-- %s (ex: %s)" % (repr((root,dirs)), repr(excludes))
244 r, ext = os.path.splitext(f)
245 if ext in [ ".h", ".c", ".cpp", ".S" ]:
246 callback( "%s/%s" % (root,f), args )
248 def cleanup_dir(path):
249 """create a directory if needed, and ensure that it is totally empty
250 by removing any existing content in it"""
251 if not os.path.exists(path):
254 for root, dirs, files in os.walk(path, topdown=False):
255 if root.endswith("kernel_headers/"):
256 # skip 'kernel_headers'
259 os.remove(os.path.join(root, name))
261 os.rmdir(os.path.join(root, name))
263 def update_file( path, newdata ):
264 """update a file on disk, only if its content has changed"""
265 if os.path.exists( path ):
267 f = open( path, "r" )
271 D("update_file: cannot read existing file '%s'" % path)
274 if oldata == newdata:
275 D2("update_file: no change to file '%s'" % path )
281 create_file_path(path)
283 D("update_file: cannot create path to '%s'" % path)
286 f = open( path, "w" )
293 class BatchFileUpdater:
294 """a class used to edit several files at once"""
296 self.old_files = set()
297 self.new_files = set()
300 def readFile(self,path):
301 #path = os.path.realpath(path)
302 if os.path.exists(path):
303 self.old_files.add(path)
305 def readDir(self,path):
306 #path = os.path.realpath(path)
307 for root, dirs, files in os.walk(path):
309 dst = "%s/%s" % (root,f)
310 self.old_files.add(dst)
312 def editFile(self,dst,data):
313 """edit a destination file. if the file is not mapped from a source,
314 it will be added. return 0 if the file content wasn't changed,
315 1 if it was edited, or 2 if the file is new"""
316 #dst = os.path.realpath(dst)
318 if os.path.exists(dst):
323 self.old_files.remove(dst)
328 self.new_data[dst] = data
329 self.new_files.add(dst)
332 def getChanges(self):
333 """determine changes, returns (adds, deletes, edits)"""
338 for dst in self.new_files:
339 if not (dst in self.old_files):
344 for dst in self.old_files:
345 if not dst in self.new_files:
348 return (adds, deletes, edits)
350 def _writeFile(self,dst,data=None):
351 if not os.path.exists(os.path.dirname(dst)):
352 create_file_path(dst)
354 data = self.new_data[dst]
356 f.write(self.new_data[dst])
359 def updateFiles(self):
360 adds, deletes, edits = self.getChanges()
362 for dst in sorted(adds):
365 for dst in sorted(edits):
368 for dst in sorted(deletes):
371 def updateP4Files(self):
372 adds, deletes, edits = self.getChanges()
375 files = string.join(sorted(adds)," ")
376 D( "%d new files will be p4 add-ed" % len(adds) )
379 D2("P4 ADDS: %s" % files)
380 o = commands.getoutput( "p4 add " + files )
384 files = string.join(sorted(edits)," ")
385 D( "%d files will be p4 edit-ed" % len(edits) )
386 D2("P4 EDITS: %s" % files)
387 o = commands.getoutput( "p4 edit " + files )
393 files = string.join(sorted(deletes)," ")
394 D( "%d files will be p4 delete-d" % len(deletes) )
395 D2("P4 DELETES: %s" % files)
396 o = commands.getoutput( "p4 delete " + files )