From f2c7ea8a0d516236c8bb1d8a2bf04f87b364cccd Mon Sep 17 00:00:00 2001 From: Ofek Shilon Date: Sat, 5 Jul 2025 17:08:48 +0300 Subject: [PATCH] Adapt python cfg to python 3.13 --- lib/base-compiler.ts | 4 +-- lib/cfg/cfg-parsers/base.ts | 7 ++++- lib/cfg/cfg-parsers/python.ts | 59 ++++++++++++++++++++++++++--------- lib/cfg/cfg.ts | 11 +++++-- test/cfg-tests.ts | 2 +- 5 files changed, 63 insertions(+), 20 deletions(-) diff --git a/lib/base-compiler.ts b/lib/base-compiler.ts index d67906fa9..1390e218b 100644 --- a/lib/base-compiler.ts +++ b/lib/base-compiler.ts @@ -1420,7 +1420,7 @@ export class BaseCompiler { } if (produceCfg) { - result.cfg = cfg.generateStructure( + result.cfg = await cfg.generateStructure( this.compiler, ir.asm.map(line => ({text: line.text})), true, @@ -3134,7 +3134,7 @@ export class BaseCompiler { this.compiler.instructionSet === 'llvm' || (options && isOutputLikelyLllvmIr(options)) || this.llvmIr.isLlvmIr(result.asm); - result.cfg = cfg.generateStructure(this.compiler, result.asm, isLlvmIr); + result.cfg = await cfg.generateStructure(this.compiler, result.asm, isLlvmIr, result); } } diff --git a/lib/cfg/cfg-parsers/base.ts b/lib/cfg/cfg-parsers/base.ts index 7dc9569d9..969e036af 100644 --- a/lib/cfg/cfg-parsers/base.ts +++ b/lib/cfg/cfg-parsers/base.ts @@ -25,6 +25,7 @@ import _ from 'underscore'; import {EdgeColor} from '../../../types/compilation/cfg.interfaces.js'; +import {CompilationResult} from '../../../types/compilation/compilation.interfaces.js'; import type {ResultLineSource} from '../../../types/resultline/resultline.interfaces.js'; import {logger} from '../../logger.js'; import {BaseInstructionSetInfo, InstructionType} from '../instruction-sets/base.js'; @@ -71,7 +72,7 @@ export class BaseCFGParser { constructor(public readonly instructionSetInfo: BaseInstructionSetInfo) {} - public filterData(assembly: AssemblyLine[]) { + public filterData(assembly: AssemblyLine[]): AssemblyLine[] { const jmpLabelRegex = /\.L\d+:/; const isCode = (x: AssemblyLine) => x?.text && (x.source !== null || jmpLabelRegex.test(x.text) || this.isFunctionName(x)); @@ -146,6 +147,10 @@ export class BaseCFGParser { return line.text.trim().indexOf('.') !== 0 || line.text.startsWith('.omp_'); } + public async processFuncNames(code: AssemblyLine[], fullRes?: CompilationResult): Promise { + return code; + } + protected getAsmDirective(txt: string) { const pattern = /^\s*(\.[^ L]\S*)/; const match = txt.match(pattern); diff --git a/lib/cfg/cfg-parsers/python.ts b/lib/cfg/cfg-parsers/python.ts index 48df8bcc8..8ecf7866c 100644 --- a/lib/cfg/cfg-parsers/python.ts +++ b/lib/cfg/cfg-parsers/python.ts @@ -22,6 +22,9 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +import fs from 'node:fs/promises'; + +import {CompilationResult} from '../../../types/compilation/compilation.interfaces.js'; import {ResultLine} from '../../../types/resultline/resultline.interfaces.js'; import {InstructionType} from '../instruction-sets/base.js'; import {AssemblyLine, BaseCFGParser, CanonicalBB} from './base.js'; @@ -43,10 +46,8 @@ export class PythonCFGParser extends BaseCFGParser { return this.instructionSetInfo.getInstructionType(prevInst) !== InstructionType.notRetInst; } - override filterData(bytecode: ResultLine[]) { - // Filter out module prefix before first function, - // replace 'Disassembly of' with 'Function #' - const res: ResultLine[] = []; + override filterData(bytecode: ResultLine[]): ResultLine[] { + // Filter out module code before the first function let i = 0; while ( i < bytecode.length && @@ -55,31 +56,61 @@ export class PythonCFGParser extends BaseCFGParser { ) { i++; } + return bytecode.slice(i).filter(x => x.text && x.text.trim() !== ''); + } + + override async processFuncNames(bytecode: AssemblyLine[], fullRes?: CompilationResult): Promise { + // replace 'Disassembly of' with function name + const res: ResultLine[] = []; + let src: string | null = null; let funcIdx = 0; - for (let j = i; j < bytecode.length; j++) { - const line = bytecode[j]; - if (!line.text) continue; + for (let i = 0; i < bytecode.length; i++) { + const line = bytecode[i]; + let funcName: string | undefined = undefined; if (line.text.startsWith('Disassembly of')) { - line.text = `Function #${funcIdx++}`; + const srcLineStr = line.text.match(/line (\d+)/)?.[1]; + const srcLineNum = srcLineStr ? Number.parseInt(srcLineStr) : null; + if (srcLineNum && fullRes && fullRes.inputFilename) { + if (src === null) { + src = await fs.readFile(fullRes.inputFilename, 'utf8'); + const srcLine = src.split('\n')[srcLineNum - 1]; + funcName = srcLine.match(/def (\w+)\(/)?.[1]; + } + } + if (funcName) line.text = funcName; + else line.text = `Function #${funcIdx++}`; } res.push(line); } return res; } - // 10 POP_JUMP_IF_FALSE 5 (to 22) ===> captures "22" + // In python <= 3.12: + // 10 POP_JUMP_IF_FALSE 5 (to 22) ===> captures line num "22" + // In python >= 3.13: + // POP_JUMP_IF_FALSE 4 (to L1) ===> captures label "L1" override extractJmpTargetName(inst: string) { - const candidateName = inst.match(/\(to (\d+)\)$/); + const candidateName = inst.match(/\(to (\w+)\)$/); return candidateName ? candidateName[1] : ''; } - //' 6 >> 22 LOAD_FAST 0 (num):' ==> '22' - //' 4 12 LOAD_FAST 0 (num):' ==> '12' - //' >> 140 FOR_ITER 98 (to 340)' ==> 140 + //' 6 >> 22 LOAD_FAST 0 (num):' ==> '22' + //' 4 12 LOAD_FAST 0 (num):' ==> '12' + //' >> 140 FOR_ITER 98 (to 340)' ==> 140 + //' 5 L1: LOAD_FAST 0 (num)' ==> 'L1' (labels are present for python >= 3.13) + //' 3 LOAD_FAST_LOAD_FAST 0 (num, num)' ===> '3' override getBbId(firstInst: string): string { - return firstInst.match(/^\s*(\d+)?\s+>?>?\s+(\d+)/)?.[2] ?? ''; + const label = firstInst.match(/(\w+):/)?.[1]; + if (label) return label; + const bytecodeOffset = firstInst.match(/^\s*\d*?\s+>?>?\s+(\d+)/)?.[1]; + if (bytecodeOffset) return bytecodeOffset; + const srcLine = firstInst.match(/\d+/)?.[0]; + if (srcLine) return 'srcLine ' + srcLine; + + // TODO: when this stabilizes a bit, add a sentry report for missed BasicBlock ID + return ''; } override getBbFirstInstIdx(firstLine: number) { diff --git a/lib/cfg/cfg.ts b/lib/cfg/cfg.ts index c1ea7033e..90ba8b619 100644 --- a/lib/cfg/cfg.ts +++ b/lib/cfg/cfg.ts @@ -22,6 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. +import {CompilationResult} from '../../types/compilation/compilation.interfaces.js'; import type {CompilerInfo} from '../../types/compiler.interfaces.js'; import {AssemblyLine, Edge, Node, getParserByKey} from './cfg-parsers/index.js'; @@ -52,7 +53,12 @@ export type CFG = { edges: Edge[]; }; -export function generateStructure(compilerInfo: CompilerInfo, asmArr: AssemblyLine[], isLlvmIr: boolean) { +export async function generateStructure( + compilerInfo: CompilerInfo, + asmArr: AssemblyLine[], + isLlvmIr: boolean, + fullRes?: CompilationResult, +) { // figure out what we're working with const isa = isLlvmIr ? 'llvm' : compilerInfo.instructionSet; const compilerGroup = isLlvmIr ? 'llvm' : isLLVMBased(compilerInfo) ? 'clang' : compilerInfo.group; @@ -64,7 +70,8 @@ export function generateStructure(compilerInfo: CompilerInfo, asmArr: AssemblyLi ? new OatCFGParser(instructionSet) : new (getParserByKey(compilerGroup))(instructionSet); - const code = parser.filterData(asmArr); + let code = parser.filterData(asmArr); + code = await parser.processFuncNames(code, fullRes); const functions = parser.splitToFunctions(code); const result: Record = {}; for (const fn of functions) { diff --git a/test/cfg-tests.ts b/test/cfg-tests.ts index 6f39e1c87..809994957 100644 --- a/test/cfg-tests.ts +++ b/test/cfg-tests.ts @@ -41,7 +41,7 @@ async function DoCfgTest(cfgArg, filename, isLlvmIr = false, compilerInfo?: Comp version: cfgArg, }); } - const structure = generateStructure(compilerInfo, contents.asm, isLlvmIr); + const structure = await generateStructure(compilerInfo, contents.asm, isLlvmIr); expect(structure).toEqual(contents.cfg); }