Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathutil.py
More file actions
Latest commit
574 lines (443 loc) · 16.5 KB
/
Copy pathutil.py
File metadata and controls
574 lines (443 loc) · 16.5 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
importsys
importcodecs
importgzip
importre
importos.path
importrandom
importbase64
importhashlib
fromioimportBytesIO
#Semantic version of extractor.
#Update this if any changes are made
VERSION="7.1.10"
PY_EXTENSIONS=".py", ".pyw"
STDLIB_PATH=os.path.dirname(os.__file__)
defget_analysis_version():
returnPYTHON_ANALYSIS_VERSION
defget_analysis_major_version():
returnPYTHON_ANALYSIS_MAJOR_VERSION
defupdate_analysis_version(version):
globalPYTHON_ANALYSIS_VERSION
PYTHON_ANALYSIS_VERSION=version
globalPYTHON_ANALYSIS_MAJOR_VERSION
PYTHON_ANALYSIS_MAJOR_VERSION=2ifPYTHON_ANALYSIS_VERSION.startswith("2") else3
update_analysis_version(os.environ.get("CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION", "3"))
#Flow graph labels:
#These should be powers of two, to allow use of bitsets.
NORMAL_EDGE=1
FALSE_EDGE=2
TRUE_EDGE=4
EXCEPTIONAL_EDGE=8
EXHAUSTED_EDGE=16
classSemmleError(Exception):
'Custom Error class, for reporting errors.'
pass
#Define our own printf function to avoid Python2/3 problems.
defprintf(fmt, *args):
'Format arguments using % operator and print to sys.stdout'
sys.stdout.write(fmt%args)
deffprintf(fout, fmt, *args):
'Format arguments using % operator and print to file'
fout.write(fmt%args)
defsafe_string(txt):
#Replace all characters after the first 10k
iflen(txt) >10000:
txt=txt[:10000] +u"..."
returntxt.replace(u'"', u'""')
defescaped_string(txt):
returntxt.replace(u'"', u'""')
ifos.name=='nt':
MAGIC_PREFIX=u"\\\\?\\"
defsafe_path(path):
'Returns an absolute path, safe for use on all OSes regardless of length.'
ifpath.startswith(MAGIC_PREFIX):
returnpath
returnMAGIC_PREFIX+os.path.abspath(path)
_open=open
defopen(path, *args):
assertsafe_path(path) ==path
return_open(path, *args)
else:
defsafe_path(path):
'Returns an absolute path, safe for use on all OSes regardless of length.'
ifos.path.isabs(path):
returnpath
returnos.path.abspath(path)
AUTO_GEN_STRING="/* AUTO GENERATED PART STARTS HERE */\n"
deffolder_tag(name):
returnname+';folder'
deftrap_id_escape(s):
"""Escapes characters that are interpreted specially in TRAP IDs"""
s=s.replace("&", "&")
s=s.replace("{", "{")
s=s.replace("}", "}")
s=s.replace('"', """)
s=s.replace('@', "@")
s=s.replace('#', "#")
returns
defgenerate_formatting_function(fmt):
'''Generate a new function that writes its arguments with the given format.
For example, for the format string "dd", this function will create the following function:
def format_ss(self, name, arg0, arg1):
self.out.write(u'%s(%s %s)\\n' % (name, str(arg0), str(arg1)))
'''
func_name='format_'+fmt
args= ['self', 'name'] + [ 'arg%d'%iforiinrange(len(fmt)) ]
defn='def %s(%s):\n'% (func_name, ', '.join(args))
values= [ _formatting_functions[f](a) forf, ainzip(fmt, args[2:])]
format_string="u'%s("+', '.join(['%s'] *len(fmt)) +")\\n'"
body=' self.out.write(%s %% (%s))\n'% (format_string, ',\n'.join(['name'] +values))
func=defn+body
namespace=globals()
exec (func, namespace)
function=namespace[func_name]
delnamespace[func_name]
returnfunction
def_format_d(val):
return'repr(%s)'%val
def_format_g(val):
return'self.pool.get(%s, %s)'% (val, val)
def_format_n(val):
return'''self.pool.get(%s, %s.trap_name) if hasattr(%s, 'trap_name') else self.pool.get(%s)'''% (val, val, val, val)
def_format_r(val):
returnval
def_format_u(val):
return'''_INVALID_RE.sub(u'\uFFFD', u'"%%s"' %% safe_string(%s))'''%val
def_format_b(val):
return'''u'"%%s"' %% safe_string(%s.decode("latin-1"))'''%val
def_format_s(val):
return'''%s if isinstance(%s, bytes) else _INVALID_RE.sub(u'\uFFFD', u'"%%s"' %% safe_string(str(%s)))'''% (_format_b(val), val, val)
def_format_B(val):
return'''u'"%%s"' %% escaped_string(%s.decode("latin-1"))'''%val
def_format_S(val):
return'''%s if isinstance(%s, bytes) else _INVALID_RE.sub(u'\uFFFD', u'"%%s"' %% escaped_string(str(%s)))'''% (_format_B(val), val, val)
def_format_x(val):
return'''(u"false", u"true")[%s]'''%val
def_format_q(val):
return'format_numeric_literal(%s)'%val
_formatting_functions= {
'b' : _format_b,
'd' : _format_d,
'g' : _format_g,
'n' : _format_n,
'r' : _format_r,
's' : _format_s,
'u' : _format_u,
'x' : _format_x,
'q' : _format_q,
'B' : _format_B,
'S' : _format_S,
}
defformat_numeric_literal(val):
txt=repr(val)
returnu'"%s"'%txt
classBuffer(object):
def__init__(self, out):
self.out=out
self.buf= []
defwrite(self, content):
self.buf.append(content)
iflen(self.buf) >10000:
self.flush()
defclose(self):
self.flush()
self.out.close()
defflush(self):
self.out.write(u''.join(self.buf))
self.buf= []
classUtf8Zip(object):
def__init__(self):
self.raw=BytesIO()
gout=gzip.GzipFile('', 'wb', 5, fileobj=self.raw)
self.out=codecs.getwriter('utf-8')(gout, errors='backslashreplace')
defwrite(self, data):
self.out.write(data)
defclose(self):
self.out.close()
defgetvalue(self):
returnself.raw.getvalue()
classTrapWriter(object):
_format_functions= {}
def__init__(self):
self.zip=Utf8Zip()
self.out=Buffer(self.zip)
self.pool=IDPool(self.out)
self.written_containers= {}
defwrite_tuple(self, name, fmt, *args):
'''Write tuple accepts the following format characters:
'b' : A bytes object. Limits the resulting string to ~10k.
'd' : An integer
'g' : A unicode object, as a globally shared object
'n' : A node object (any AST, flow or variable node)
'r' : "Raw", a precomputed id or similar.
's' : Any object to be written as a unicode string. Limits the string to ~10k.
'u' : A unicode object, as a string
'x' : A boolean
'B' : Like 'b' but not limited to 10k
'S' : Like 's' but not limited to 10k
'''
iffmtinself._format_functions:
returnself._format_functions[fmt](self, name, *args)
func=generate_formatting_function(fmt)
self._format_functions[fmt] =func
returnfunc(self, name, *args)
defget_node_id(self, node):
ifhasattr(node, 'trap_name'):
returnself.pool.get(node, node.trap_name)
else:
returnself.pool.get(node)
defhas_written(self, node):
returnnodeinself.pool.pool
defget_unique_id(self):
returnself.pool.get_unique_id()
'''Return an id that is shared across trap files,
whenever the label is used'''
defget_labelled_id(self, obj, label):
returnself.pool.get(obj, label)
defwrite_container(self, fullpath, is_file):
iffullpathinself.written_containers:
returnself.written_containers[fullpath]
folder, filename=os.path.split(fullpath)
ifis_file:
tag=get_source_file_tag(fullpath)
self.write_tuple(u'files', 'gs', tag, fullpath)
else:
tag=get_folder_tag(fullpath)
self.write_tuple(u'folders', 'gs', tag, fullpath)
self.written_containers[fullpath] =tag
iffolderandfilename:
folder_tag=self.write_container(folder, False)
self.write_tuple(u'containerparent' , 'gg', folder_tag, tag)
returntag
defwrite_file(self, fullpath):
'''Writes `files` tuple plus all container tuples, up to the root.
Returns the tag.
Records tuples written to avoid duplication.
'''
returnself.write_container(fullpath, True)
defwrite_folder(self, fullpath):
'''Writes `folders` tuple plus all container tuples, up to the root.
Returns the tag.
Records tuples written to avoid duplication.
'''
returnself.write_container(fullpath, False)
defget_compressed(self):
'''Returns the gzipped compressed, utf-8 encoded contents of this trap file.
Closes the underlying zip stream, which means that no more tuples can be added.'''
self.out.close()
returnself.zip.getvalue()
defwrite_comment(self, text):
self.out.write(u'// %s\n'%text)
# RegEx to find invalid characters
_INVALID_RE=re.compile(u'[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE)
class_HashableList(object):
'Utility class for handling lists in the IDPool'
def__init__(self, items):
self.items=items
def__eq__(self, other):
ifnotisinstance(other, _HashableList):
returnFalse
returnself.itemsisother.items
def__ne__(self, other):
ifnotisinstance(other, _HashableList):
returnTrue
returnself.itemsisnotother.items
def__hash__(self):
returnid(self.items)
classIDPool(object):
def__init__(self, out, init_id=10000):
self.out=out
self.pool= {}
self.next_id=init_id
defget_unique_id(self):
res=u'#'+str(self.next_id)
self.out.write(res+u' = *\n')
self.next_id+=1
returnres
defget(self, node, name=None):
"""Gets the ID for the given node, creating a new one if necessary.
Inside name (if supplied), the characters &, {, }, ", @, and # will be escaped,
as these have special meaning in TRAP IDs
"""
#Need to special case lists as they are unhashable
iftype(node) islist:
node=_HashableList(node)
ifnodeinself.pool:
returnself.pool[node]
next_id= (u'#'+
str(self.next_id))
ifnameisnotNone:
name=str(name)
name=u'@"%s"'%safe_string(trap_id_escape(name))
else:
name=u'*'
self.out.write(u"%s = %s\n"% (next_id, name))
self.pool[node] =next_id
self.next_id+=1
returnnext_id
defget_folder_tag(folder):
return'/'.join(folder.split(os.path.sep)) +';folder'
defget_source_file_tag(fullpath):
returnfullpath, sys.getfilesystemencoding() +u';sourcefile'
defmakedirs(path):
try:
os.makedirs(path)
exceptOSError:
#If directory does not exist then error was a real one.
ifnotos.path.isdir(path):
raise
defclean_cache(subdir, suffix, verbose):
#Remove any pre-existing cached files as they are now out of date
ifos.path.exists(subdir):
forfilenameinos.listdir(subdir):
ifnotfilename.endswith(suffix):
continue
filepath=os.path.join(subdir, filename)
try:
ifverbose:
print ("Deleting stale trap file: "+filepath)
os.remove(filepath)
exceptExceptionasex:
ifverbose:
msg="Failed to remove stale trap file %s due to %s"
print (msg% (filepath, repr(ex)))
else:
makedirs(subdir)
ifos.name=='nt':
defstorage_path(container, path):
''' Returns a path in a source archive, trap-output or trap-cache.'''
path=path.replace(":", "_")
ifos.path.isabs(path):
path=path[1:]
returnsafe_path(os.path.join(container, path))
defisdir(path):
iflen(path) >240:
path="\\\\?\\"+path
returnos.path.isdir(path)
defislink(path):
iflen(path) >240:
path="\\\\?\\"+path
returnos.path.islink(path)
deflistdir(path):
iflen(path) >240:
path="\\\\?\\"+path
returnos.listdir(path)
else:
defstorage_path(container, path):
''' Returns a path in a source archive, trap-output or trap-cache.'''
ifos.path.isabs(path):
path=path[1:]
returnsafe_path(os.path.join(container, path))
isdir=os.path.isdir
islink=os.path.islink
listdir=os.listdir
LATIN1=codecs.lookup("latin-1")
UTF8=codecs.lookup("utf-8")
defwas_interned_ascii_bytes(txt):
returntxtissys.intern(txt[:])
defis_a_number(txt):
try:
float(txt)
returnTrue
exceptValueError:
returnFalse
#Should only be set to True for debugging and testing
USE_INTOLERANT_ENCODING=False
defchange_default_encoding():
ifUSE_INTOLERANT_ENCODING:
def_decode(input, errors=None):
'''If the input is interned (program source) or a number, then it is safe to implicitly convert it.
Otherwise it may not be, so raise an exception'''
ifnotwas_interned_ascii_bytes(input) andnotis_a_number(input):
f=sys._getframe(1)
if"semmle"inf.f_code.co_filename:
raiseSemmleError(b"Implicit decode of '%s' at %s:%d"% (input, f.f_code.co_filename, f.f_lineno))
try:
returnUTF8.decode(input)
exceptUnicodeDecodeError:
returnLATIN1.decode(input)
def_encode(input, errors=None):
f=sys._getframe(1)
if"semmle"inf.f_code.co_filename:
raiseSemmleError("Implicit encode of '%s' at %s:%d"% (UTF8.encode(input), f.f_code.co_filename, f.f_lineno))
returnUTF8.encode(input, "backslashreplace")
else:
def_decode(input, errors=None):
'''Convert bytes to unicode without failing.'''
try:
returnUTF8.decode(input)
exceptUnicodeDecodeError:
returnLATIN1.decode(input)
def_encode(input, errors=None):
'''Convert unicode to bytes without failing.'''
returnUTF8.encode(input, "backslashreplace")
defsearch(name):
ifname!="safe":
returnNone
returncodecs.CodecInfo(_encode, _decode, name="safe")
codecs.register(search)
fromimportlibimportreload
reload(sys)
sys.setdefaultencoding("safe")
delsys.setdefaultencoding
_sys_rand=random.SystemRandom()
defuuid(local_name):
'''Return a randomised string to use as a UUID.
Do not use the uuid module as it calls out to ldconfig,
which is prohibited in some sandboxed environments.
'''
hex_string=hex(_sys_rand.randrange(1<<256))
#Strip leading '0x'
returnhex_string[2:] +"-"+local_name
classExtractable(object):
'''Extractable class representing a Extractable of extraction.
Typically a file, but may be other things like a built-in Python module.
'''
def__ne__(self, other):
returnnotself==other
@staticmethod
deffrom_path(path):
ifos.path.isdir(path):
returnFolderExtractable(path)
elifos.path.isfile(path):
returnFileExtractable(path)
else:
raiseIOError("% does not exist"%path)
classPathExtractable(Extractable):
PATTERN=421706893
__slots__= [ 'path' ]
def__init__(self, path):
assert"<compiled code>"notinpath
self.path=path
def__eq__(self, other):
returnisinstance(other, type(self)) andself.path==other.path
def__hash__(self):
returnhash(self.path) ^self.PATTERN
classFileExtractable(PathExtractable):
PATTERN=1903946595
__slots__= [ 'path' ]
def__str__(self):
return"file "+self.path
def__repr__(self):
return"FileExtractable(%r)"%self.path
classFolderExtractable(PathExtractable):
PATTERN=712343093
__slots__= [ 'path' ]
def__str__(self):
return"folder "+self.path
def__repr__(self):
return"FolderExtractable(%r)"%self.path
classBuiltinModuleExtractable(Extractable):
__slots__= [ 'name' ]
def__init__(self, name):
self.name=name
def__str__(self):
return"module "+self.name
def__repr__(self):
return"BuiltinModuleExtractable(%r)"%self.name
def__eq__(self, other):
returnisinstance(other, BuiltinModuleExtractable) andself.name==other.name
def__hash__(self):
returnhash(self.name) ^82753421
defbase64digest(code):
returnbase64.b64encode(hashlib.sha1(code.encode("utf8")).digest(), b"_-").decode("ascii")