99 lines
5.1 KiB
Python
99 lines
5.1 KiB
Python
"""Read JVM descriptors without loading plugins or invoking any backend/data operation."""
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
import zipfile
|
|
|
|
|
|
def parse_class(payload):
|
|
stream = io.BytesIO(payload)
|
|
def u1(): return struct.unpack('>B', stream.read(1))[0]
|
|
def u2(): return struct.unpack('>H', stream.read(2))[0]
|
|
def u4(): return struct.unpack('>I', stream.read(4))[0]
|
|
if u4() != 0xCAFEBABE: raise ValueError('Invalid JVM class')
|
|
u2(); u2(); count=u2(); cp=[None]*count; index=1
|
|
while index<count:
|
|
tag=u1()
|
|
if tag==1: cp[index]=(tag,stream.read(u2()).decode('utf-8','replace'))
|
|
elif tag in (3,4): stream.read(4)
|
|
elif tag in (5,6): stream.read(8); index+=1
|
|
elif tag in (7,8,16,19,20): cp[index]=(tag,u2())
|
|
elif tag in (9,10,11,12,17,18): cp[index]=(tag,u2(),u2())
|
|
elif tag==15: stream.read(3)
|
|
else: raise ValueError('Unknown JVM constant tag '+str(tag))
|
|
index+=1
|
|
def text(index): return cp[index][1]
|
|
def owner(index): return text(cp[index][1])
|
|
def attributes():
|
|
for _ in range(u2()): u2(); stream.seek(u4(),1)
|
|
def members():
|
|
result=[]
|
|
for _ in range(u2()):
|
|
access,name,descriptor=u2(),text(u2()),text(u2());attributes()
|
|
if access&1: result.append([name,descriptor])
|
|
return result
|
|
u2(); name=owner(u2()); parent=u2(); parent=owner(parent) if parent else None
|
|
for _ in range(u2()): u2()
|
|
fields=members(); methods=members(); refs=[]
|
|
for entry in cp:
|
|
if entry and entry[0] in (9,10,11):
|
|
target=cp[entry[2]]
|
|
refs.append({'kind':'fields' if entry[0]==9 else 'methods','owner':owner(entry[1]),'name':text(target[1]),'descriptor':text(target[2])})
|
|
return {'name':name,'super':parent,'fields':fields,'methods':methods,'refs':refs}
|
|
|
|
|
|
def jar_classes(path):
|
|
with zipfile.ZipFile(path) as archive:
|
|
return {name[:-6]:parse_class(archive.read(name)) for name in archive.namelist() if name.endswith('.class') and not name.startswith('META-INF/')}
|
|
|
|
|
|
def reflection_requirements(source, backend):
|
|
aliases={'UUID':'java/util/UUID','String':'java/lang/String','JsonObject':'com/google/gson/JsonObject'}
|
|
primitives={'int':'I','long':'J','boolean':'Z'}
|
|
rows=[]
|
|
for match in re.finditer(r'getMethod\("([^"\n]+)"([^)]*)\)',source):
|
|
name,args=match.groups(); descriptor='('
|
|
for value in args.split(','):
|
|
value=value.strip()
|
|
if not value:continue
|
|
if not value.endswith('.class'):raise ValueError('Reflection contract is not a literal type list')
|
|
value=value[:-6];descriptor+=primitives.get(value) or 'L'+aliases.get(value,value.replace('.','/'))+';'
|
|
descriptor+=')'
|
|
matches=[item for item in backend['methods'] if item[0]==name and item[1].startswith(descriptor)]
|
|
if len(matches)!=1:raise ValueError('Preserved JARVIS lacks exact reflected signature: '+name+descriptor)
|
|
rows.append({'kind':'methods','owner':backend['name'],'name':name,'descriptor':matches[0][1]})
|
|
return rows
|
|
|
|
|
|
def verify(frontend_jars, contract, reflection_source=None):
|
|
classes=contract['classes']; requirements=list(contract.get('reflectionRequirements',[]))
|
|
for path in frontend_jars:
|
|
for value in jar_classes(path).values():
|
|
requirements.extend(ref for ref in value['refs'] if ref['owner'].startswith(('com/dunerealms/jarvis/','com/example/dunerealms/','com/example/duneess/')))
|
|
if reflection_source is not None:
|
|
requirements.extend(reflection_requirements(Path(reflection_source).read_text(encoding='utf-8'),classes['com/dunerealms/jarvis/JarvisTranslator']))
|
|
unique={(item['kind'],item['owner'],item['name'],item['descriptor']) for item in requirements}
|
|
failures=[]
|
|
for kind,owner,name,descriptor in sorted(unique):
|
|
current=owner;found=False;seen=set()
|
|
while current in classes and current not in seen:
|
|
seen.add(current); row=classes[current]
|
|
if [name,descriptor] in row[kind]:found=True;break
|
|
current=row.get('super')
|
|
if not found:failures.append(owner+'.'+name+descriptor)
|
|
if failures:raise ValueError('Preserved backend ABI mismatch: '+', '.join(failures))
|
|
return {'requiredDescriptors':len(unique),'missing':[], 'backendSha256':contract['backendSha256']}
|
|
|
|
|
|
def contract_for_actual(jarvis, core, fixture):
|
|
import hashlib
|
|
rows={}
|
|
for path,kind in ((jarvis,'jarvis'),(core,'core')):
|
|
value=hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
if not any(row['kind']==kind and row['sha256']==value for row in fixture['variants']):
|
|
raise ValueError('Retained '+kind+' bytes are not a reviewed live variant')
|
|
rows.update({key:{name:row[name] for name in ('name','super','fields','methods')} for key,row in jar_classes(path).items() if key.startswith(('com/dunerealms/jarvis/','com/example/dunerealms/'))})
|
|
return {'classes':dict(fixture['parents'],**rows),'reflectionRequirements':fixture['reflectionRequirements'],
|
|
'backendSha256':hashlib.sha256(Path(jarvis).read_bytes()).hexdigest()}
|

Staff