├── assets ├── .gitignore ├── triskel-icons.woff ├── triskel_dragon.png ├── triskel_black.svg └── triskel_white.svg ├── .vscodeignore ├── .github ├── branch.png ├── triskel.png └── top_right.png ├── .husky └── pre-commitA ├── .gitignore ├── src ├── view │ ├── triskel │ │ ├── triskel-wasm.wasm │ │ ├── triskel-wasm.d.ts │ │ └── triskel-wasm.js │ ├── vscode.ts │ ├── graph-viewer.tsx │ ├── llvmir │ │ ├── common.ts │ │ ├── parser.ts │ │ ├── highlighting.ts │ │ ├── regexp.ts │ │ └── cfg.ts │ ├── components │ │ ├── SplashScreen.tsx │ │ ├── InstructionContainer.tsx │ │ ├── context.ts │ │ ├── SearchableComboBox.tsx │ │ ├── FunctionView.tsx │ │ ├── EdgeView.tsx │ │ ├── SyntaxHighlighter.tsx │ │ ├── BasicBlockContainer.tsx │ │ ├── GraphView.tsx │ │ ├── FunctionSelection.tsx │ │ ├── triskel.svg │ │ ├── Minimap.tsx │ │ └── TransformContainer.tsx │ ├── styles.css │ ├── hooks │ │ ├── useFileContents.ts │ │ └── useWasm.ts │ ├── graph-viewer.ts │ └── App.tsx ├── custom.d.ts └── web │ └── extension.ts ├── postcss.config.js ├── tailwind.config.js ├── typedoc.js ├── .prettierrc ├── .vscode ├── settings.json ├── tasks.json └── launch.json ├── tsconfig.json ├── .eslintrc.json ├── README.md ├── webpack.config.js ├── package.json └── LICENSE.md /assets/.gitignore: -------------------------------------------------------------------------------- 1 | triskel-icons/ -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | **/*.ts 2 | **/*.tsx 3 | **/tsconfig.json 4 | 5 | *.ll -------------------------------------------------------------------------------- /.github/branch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/.github/branch.png -------------------------------------------------------------------------------- /.github/triskel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/.github/triskel.png -------------------------------------------------------------------------------- /.husky/pre-commitA: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn run lint-staged -------------------------------------------------------------------------------- /.github/top_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/.github/top_right.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | .vscode-test-web/ 5 | *.vsix 6 | .eslintcache 7 | docs -------------------------------------------------------------------------------- /assets/triskel-icons.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/assets/triskel-icons.woff -------------------------------------------------------------------------------- /assets/triskel_dragon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/assets/triskel_dragon.png -------------------------------------------------------------------------------- /src/view/triskel/triskel-wasm.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/HEAD/src/view/triskel/triskel-wasm.wasm -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | "@tailwindcss/postcss": {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /src/view/vscode.ts: -------------------------------------------------------------------------------- 1 | interface vscode { 2 | postMessage(message: any): void; 3 | } 4 | 5 | declare const vscode: vscode; 6 | 7 | export default vscode; 8 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | content: ["./src/**/*.{ts,tsx}"], 3 | theme: { 4 | extend: {}, 5 | }, 6 | plugins: [], 7 | }; 8 | -------------------------------------------------------------------------------- /typedoc.js: -------------------------------------------------------------------------------- 1 | const glob = require("glob"); 2 | 3 | module.exports = { 4 | entryPoints: glob.sync("src/web/**/*.ts").filter((e) => !e.includes("test")), 5 | }; -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": false, 3 | "printWidth": 120, 4 | "tabWidth": 4, 5 | "bracketSpacing": true, 6 | "singleQuote": false, 7 | "arrowParens": "always", 8 | "trailingComma": "es5" 9 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "basicblock", 4 | "funcid", 5 | "iffalse", 6 | "iftrue", 7 | "indirectbr", 8 | "insn", 9 | "Royer" 10 | ] 11 | } -------------------------------------------------------------------------------- /src/custom.d.ts: -------------------------------------------------------------------------------- 1 | declare module "*.wasm" { 2 | const value: string; 3 | export default value; 4 | } 5 | 6 | declare module "*.svg" { 7 | import React from "react"; 8 | export const ReactComponent: React.FC>; 9 | export default ReactComponent; 10 | } 11 | -------------------------------------------------------------------------------- /src/view/graph-viewer.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | import ReactDOM from "react-dom/client"; 4 | 5 | import App from "./App"; 6 | 7 | import "./styles.css"; 8 | 9 | const root = ReactDOM.createRoot(document.getElementById("root")!); // Create a root element 10 | 11 | root.render( 12 | 13 | 14 | 15 | ); 16 | -------------------------------------------------------------------------------- /src/view/llvmir/common.ts: -------------------------------------------------------------------------------- 1 | export function removeTrailing(str: string, trail: string): string { 2 | if (str.endsWith(trail)) { 3 | return str.slice(0, -trail.length); 4 | } else { 5 | return str; 6 | } 7 | } 8 | 9 | const escape = /\\[0-9a-fA-F]{2}/; 10 | export function normalizeIdentifier(str: string): string { 11 | const prefix = str.slice(0, 1); 12 | const pureIdentifier = str.endsWith('"') ? str.slice(2, -1) : str.slice(1); 13 | const normalizedIdentifier = pureIdentifier.replace(escape, (match: string) => { 14 | return String.fromCharCode(parseInt(match.slice(1), 16)); 15 | }); 16 | return prefix + normalizedIdentifier; 17 | } -------------------------------------------------------------------------------- /src/view/components/SplashScreen.tsx: -------------------------------------------------------------------------------- 1 | import TriskelIcon from "./triskel.svg"; 2 | 3 | const SplashScreen = () => { 4 | return ( 5 |
9 |
10 | 11 |
12 | 13 |

Triskel - Made with ❤️ in France

14 |
15 | ); 16 | }; 17 | 18 | export default SplashScreen; 19 | -------------------------------------------------------------------------------- /src/view/styles.css: -------------------------------------------------------------------------------- 1 | @import "tailwindcss"; 2 | 3 | editor-text { 4 | font-family: var(--vscode-editor-font-family); 5 | font-weight: var(--vscode-editor-font-weight); 6 | font-size: var(--vscode-editor-font-size); 7 | } 8 | 9 | vscode-split-layout { 10 | height: 100%; 11 | width: 100%; 12 | } 13 | 14 | .insn:focus { 15 | background-color: color-mix(in srgb, var(--vscode-foreground) 7%, transparent); 16 | } 17 | 18 | [slot="start"], 19 | [slot="end"] { 20 | align-items: center; 21 | display: flex; 22 | flex-direction: column; 23 | overflow: hidden; 24 | } 25 | 26 | vscode-tree { 27 | width: 100%; 28 | } 29 | 30 | vscode-tree > leaf { 31 | padding-left: 10px; 32 | } 33 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "CommonJS", 4 | "target": "ES2020", 5 | "lib": ["ES2020", "DOM", "DOM.Iterable"], 6 | "outDir": "dist", 7 | "esModuleInterop": true, 8 | "sourceMap": true, 9 | "jsx": "react-jsx", 10 | "forceConsistentCasingInFileNames": true, 11 | "importHelpers": true, 12 | "strict": true, 13 | 14 | "allowJs": true, 15 | "skipLibCheck": true, 16 | "allowSyntheticDefaultImports": true, 17 | "noFallthroughCasesInSwitch": true, 18 | "moduleResolution": "node", 19 | "resolveJsonModule": true, 20 | "isolatedModules": true, 21 | }, 22 | "exclude": ["node_modules", ".vscode-test"] 23 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "compile-web", 9 | "group": { 10 | "kind": "build", 11 | "isDefault": true 12 | }, 13 | "problemMatcher": ["$ts-webpack", "$tslint-webpack"] 14 | }, 15 | { 16 | "type": "npm", 17 | "script": "watch-web", 18 | "group": "build", 19 | "isBackground": true, 20 | "problemMatcher": ["$ts-webpack-watch", "$tslint-webpack-watch"] 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["./node_modules/gts"], 3 | "root": true, 4 | "parser": "@typescript-eslint/parser", 5 | "parserOptions": { 6 | "ecmaVersion": 6, 7 | "sourceType": "module" 8 | }, 9 | "plugins": ["@typescript-eslint"], 10 | "rules": { 11 | "@typescript-eslint/naming-convention": "warn", 12 | "@typescript-eslint/semi": "warn", 13 | "@typescript-eslint/no-namespace": "off", 14 | "@typescript-eslint/no-unused-vars": ["warn", { "args": "none" }], 15 | "curly": "warn", 16 | "eqeqeq": "warn", 17 | "no-throw-literal": "warn", 18 | "node/no-unpublished-require": ["error", { "allowModules": ["mocha"] }], 19 | "quotes": ["warn", "double", { "avoidEscape": true }], 20 | "semi": "off" 21 | }, 22 | "ignorePatterns": ["*.js", "**/*.d.ts"] 23 | } -------------------------------------------------------------------------------- /src/view/hooks/useFileContents.ts: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | import vscode from "../vscode"; 3 | 4 | const useFileContents = () => { 5 | const [fileContent, setFileContent] = useState(undefined); 6 | 7 | useEffect(() => { 8 | const handleMessage = (event: any) => { 9 | console.log(event.data); 10 | 11 | const message = event.data; 12 | if (message.command === "setFileContent") { 13 | setFileContent(message.text); 14 | } 15 | }; 16 | 17 | window.addEventListener("message", handleMessage); 18 | 19 | return () => window.removeEventListener("message", handleMessage); 20 | }, [setFileContent]); 21 | 22 | useEffect(() => { 23 | vscode.postMessage({ command: "getFileContent" }); 24 | }, []); 25 | 26 | return fileContent; 27 | }; 28 | 29 | export default useFileContents; 30 | -------------------------------------------------------------------------------- /src/view/hooks/useWasm.ts: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | import { EmbindModule } from "../triskel/triskel-wasm"; 3 | 4 | const useWasm = () => { 5 | const [wasmModule, setWasmModule] = useState(undefined); 6 | 7 | useEffect(() => { 8 | console.log("LOADING WASM"); 9 | // @ts-ignore 10 | window.Module = {}; 11 | // @ts-ignore 12 | window.Module.onRuntimeInitialized = async () => { 13 | console.log("LOADED WASM"); 14 | // @ts-ignore 15 | setWasmModule(window.Module); 16 | }; 17 | 18 | // Dynamically load the WebAssembly script 19 | const script = document.createElement("script"); 20 | // @ts-ignore 21 | script.src = window.__WASM_URL__; // Ensure the path is correct 22 | script.async = true; 23 | script.onload = () => console.log("✅ WASM Script Loaded"); 24 | 25 | document.body.appendChild(script); 26 | 27 | // Cleanup function to remove the script 28 | return () => { 29 | document.body.removeChild(script); 30 | // @ts-ignore 31 | delete window.Module; 32 | }; 33 | }, [setWasmModule]); 34 | 35 | return [wasmModule]; 36 | }; 37 | 38 | export default useWasm; 39 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Web Extension ", 10 | "type": "pwa-extensionHost", 11 | "debugWebWorkerHost": true, 12 | "request": "launch", 13 | "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--extensionDevelopmentKind=web"], 14 | "outFiles": ["${workspaceFolder}/dist/web/**/*.js"], 15 | "preLaunchTask": "npm: watch-web" 16 | }, 17 | { 18 | "name": "Extension Tests", 19 | "type": "extensionHost", 20 | "debugWebWorkerHost": true, 21 | "request": "launch", 22 | "args": [ 23 | "--extensionDevelopmentPath=${workspaceFolder}", 24 | "--extensionDevelopmentKind=web", 25 | "--extensionTestsPath=${workspaceFolder}/dist/web/test/suite/index" 26 | ], 27 | "outFiles": ["${workspaceFolder}/dist/web/**/*.js"], 28 | "preLaunchTask": "npm: watch-web" 29 | } 30 | ] 31 | } -------------------------------------------------------------------------------- /src/view/components/InstructionContainer.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback } from "react"; 2 | import { Instruction } from "../llvmir/cfg"; 3 | import vscode from "../vscode"; 4 | import "../styles.css"; 5 | import SyntaxHighlighter from "./SyntaxHighlighter"; 6 | 7 | export interface InstructionContainerProps { 8 | insn: Instruction; 9 | } 10 | 11 | const InstructionContainer = ({ insn }: InstructionContainerProps) => { 12 | const gotoLine = useCallback( 13 | (i: number) => { 14 | vscode.postMessage({ command: "gotoLine", line: insn.address + i }); 15 | }, 16 | [insn.address] 17 | ); 18 | 19 | return ( 20 | <> 21 | {insn.content.split("\n").map((line, i) => ( 22 |

gotoLine(i)} 26 | > 27 | 31 | {insn.address + i} 32 | 33 | 34 | {line} 35 | 36 |

37 | ))} 38 | 39 | ); 40 | }; 41 | 42 | export default InstructionContainer; 43 | -------------------------------------------------------------------------------- /src/view/components/context.ts: -------------------------------------------------------------------------------- 1 | import { createContext } from "react"; 2 | import { Point, PointVector } from "../triskel/triskel-wasm"; 3 | import { BasicBlock, Edge } from "../llvmir/cfg"; 4 | 5 | export interface ViewPort { 6 | scale: number; 7 | setScale: React.Dispatch>; 8 | pan: Point; 9 | setPan: React.Dispatch>; 10 | size: Point; 11 | setSize: React.Dispatch>; 12 | } 13 | 14 | export const ViewPortContext = createContext({ 15 | scale: 0, 16 | pan: { x: 0, y: 0 }, 17 | size: { x: 0, y: 0 }, 18 | setScale: () => {}, 19 | setSize: () => {}, 20 | setPan: () => {}, 21 | }); 22 | 23 | export interface BlockLayout { 24 | x: number; 25 | y: number; 26 | width: number; 27 | height: number; 28 | 29 | block: BasicBlock; 30 | } 31 | 32 | export interface EdgeLayout { 33 | waypoints: PointVector; 34 | edge: Edge; 35 | } 36 | 37 | export interface Layout { 38 | blocks: Map; 39 | edges: EdgeLayout[]; 40 | width: number; 41 | height: number; 42 | } 43 | 44 | export const LayoutContext = createContext(undefined); 45 | 46 | export interface BlockSelection { 47 | name: string; 48 | shouldFocus?: boolean; 49 | } 50 | 51 | export interface SelectedBlock { 52 | selected: BlockSelection; 53 | setSelected: React.Dispatch>; 54 | } 55 | export const SelectedBlockContext = createContext({ 56 | selected: { name: "" }, 57 | setSelected: () => {}, 58 | }); 59 | -------------------------------------------------------------------------------- /src/view/triskel/triskel-wasm.d.ts: -------------------------------------------------------------------------------- 1 | // TypeScript bindings for emscripten-generated code. Automatically generated at compile time. 2 | declare namespace RuntimeExports { 3 | let HEAPF32: any; 4 | let HEAPF64: any; 5 | let HEAP_DATA_VIEW: any; 6 | let HEAP8: any; 7 | let HEAPU8: any; 8 | let HEAP16: any; 9 | let HEAPU16: any; 10 | let HEAP32: any; 11 | let HEAPU32: any; 12 | let HEAP64: any; 13 | let HEAPU64: any; 14 | } 15 | interface WasmModule { 16 | } 17 | 18 | export interface ClassHandle { 19 | isAliasOf(other: ClassHandle): boolean; 20 | delete(): void; 21 | deleteLater(): this; 22 | isDeleted(): boolean; 23 | clone(): this; 24 | } 25 | export interface PointVector extends ClassHandle { 26 | size(): number; 27 | get(_0: number): Point | undefined; 28 | push_back(_0: Point): void; 29 | resize(_0: number, _1: Point): void; 30 | set(_0: number, _1: Point): boolean; 31 | } 32 | 33 | export interface CFGLayout extends ClassHandle { 34 | edge_count(): number; 35 | node_count(): number; 36 | get_waypoints(_0: number): PointVector; 37 | get_coords(_0: number): Point; 38 | get_height(): number; 39 | get_width(): number; 40 | } 41 | 42 | export interface LayoutBuilder extends ClassHandle { 43 | build(): CFGLayout; 44 | make_empty_node(): number; 45 | make_edge(_0: number, _1: number): number; 46 | make_node(_0: number, _1: number): number; 47 | graphviz(): string; 48 | } 49 | 50 | export type Point = { 51 | x: number, 52 | y: number 53 | }; 54 | 55 | interface EmbindModule { 56 | PointVector: { 57 | new(): PointVector; 58 | }; 59 | CFGLayout: {}; 60 | LayoutBuilder: {}; 61 | make_layout_builder(): LayoutBuilder; 62 | } 63 | 64 | export type MainModule = WasmModule & typeof RuntimeExports & EmbindModule; 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LLVM Graph View 2 | 3 | ![LLVM Graph View](.github/triskel.png) 4 | 5 | ![LLVM Graph View zoomed in](.github/branch.png) 6 | 7 | An interactive graph view for `.ll` files, powered by the [Triskel](https://github.com/triskellib/triskel) graph layout engine. 8 | 9 | ## Quick Start 10 | 11 | To view the graph of a `.ll` file, click the **Triskel** icon at the top right of the screen. 12 | 13 | ![Top Right Icon](.github/top_right.png) 14 | 15 | ## Features 16 | 17 | ### Function Selection 18 | Use the search bar to search for function names or basic block labels within the selected function. 19 | 20 | ### Graph View Controls 21 | - **Pan**: Middle-click and drag. 22 | - **Zoom**: Scroll to zoom in/out. 23 | - **Reset Zoom**: Right-click to set zoom level to 100%. 24 | - **Center Graph**: Right-click to center the graph view. 25 | 26 | ### Block Interaction 27 | - **Ellipsis Menu**: Click the "..." menu to: 28 | - Center the view on the current block. 29 | - Copy the block's contents. 30 | - Go to the block’s location in the text editor. 31 | - **Jump to Line**: Click on an instruction to navigate the text editor to the corresponding line. 32 | - **Block Labels**: Click on labels to jump to the associated block. 33 | 34 | ### Graph Overview 35 | - **Center View**: Click to center the view on the cursor. 36 | - **Move View**: Drag to reposition the view. 37 | 38 | ### Text Editor Integration 39 | - **Sync to Graph**: Right-click and select **Sync Graph View** to jump to the corresponding instruction in the graph view. 40 | 41 | ## Performance 42 | 43 | The extension has been tested with `.ll` files containing up to 2K lines and functions with ~100 nodes. Performance may vary with larger files. 44 | 45 | ## Errors & Feedback 46 | 47 | This project is in early development. If you encounter any issues or bugs, please report them along with the problematic `.ll` file. 48 | 49 | ## Feature Requests 50 | 51 | Have a feature in mind? Feel free to submit your request! 52 | -------------------------------------------------------------------------------- /src/view/components/SearchableComboBox.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | 3 | export interface SearchableComboBoxProps { 4 | options: string[]; 5 | selected: string | undefined; 6 | onSelect: (selected: string) => void; 7 | } 8 | 9 | const SearchableComboBox = ({ options, selected, onSelect }: SearchableComboBoxProps) => { 10 | const [searchTerm, setSearchTerm] = useState(""); 11 | const [isOpen, setIsOpen] = useState(false); 12 | 13 | const filteredOptions = options.filter((option) => option.toLowerCase().includes(searchTerm.toLowerCase())); 14 | 15 | const handleSearchChange = (e: any) => { 16 | setSearchTerm(e.target.value); 17 | setIsOpen(true); 18 | }; 19 | 20 | const handleOptionSelect = (option: string) => { 21 | onSelect(option); 22 | setSearchTerm(option); 23 | setIsOpen(false); 24 | }; 25 | 26 | const handleBlur = () => { 27 | setIsOpen(false); 28 | }; 29 | 30 | return ( 31 |
32 | setIsOpen(true)} 38 | /> 39 |
40 | {filteredOptions.length > 0 ? ( 41 | filteredOptions.map((option, index) => ( 42 |
handleOptionSelect(option)} 46 | > 47 | {option} 48 |
49 | )) 50 | ) : ( 51 |
No results found
52 | )} 53 |
54 |
55 | ); 56 | }; 57 | 58 | export default SearchableComboBox; 59 | -------------------------------------------------------------------------------- /src/view/components/FunctionView.tsx: -------------------------------------------------------------------------------- 1 | import { useContext, useEffect } from "react"; 2 | import { LayoutContext } from "./context"; 3 | import TransformContainer from "./TransformContainer"; 4 | import BasicBlockContainer from "./BasicBlockContainer"; 5 | import EdgeView from "./EdgeView"; 6 | import vscode from "../vscode"; 7 | 8 | const FunctionView = () => { 9 | const layout = useContext(LayoutContext); 10 | 11 | // Context menu 12 | useEffect(() => { 13 | if (layout === undefined) return; 14 | 15 | const handler = (event: MessageEvent) => { 16 | const message = event.data; // The JSON data our extension sent 17 | console.log(message); 18 | 19 | switch (message.command) { 20 | case "basicblock-commands.copy": { 21 | const name = message.block; 22 | const block = layout.blocks.get(name)!; 23 | let text = name + ":\n"; 24 | 25 | block.block.instructions.forEach((instruction) => { 26 | text += instruction.content + "\n"; 27 | }); 28 | 29 | vscode.postMessage({ command: "copy", text }); 30 | break; 31 | } 32 | 33 | case "basicblock-commands.goto": { 34 | const name = message.block; 35 | const block = layout.blocks.get(name)!; 36 | const line = block.block.instructions[0].address - 1; 37 | 38 | vscode.postMessage({ command: "gotoLine", line, moveFocus: true }); 39 | break; 40 | } 41 | } 42 | }; 43 | 44 | window.addEventListener("message", handler); 45 | 46 | return () => { 47 | window.removeEventListener("message", handler); 48 | }; 49 | }, [layout]); 50 | 51 | if (layout === undefined) return null; 52 | 53 | return ( 54 | 55 | {[...layout.blocks].map(([name, block], idx) => ( 56 | 57 | ))} 58 | {layout.edges.map((edge, idx) => ( 59 | 60 | ))} 61 | 62 | ); 63 | }; 64 | 65 | export default FunctionView; 66 | -------------------------------------------------------------------------------- /src/view/components/EdgeView.tsx: -------------------------------------------------------------------------------- 1 | import { useContext, useState } from "react"; 2 | import { PointVector } from "../triskel/triskel-wasm"; 3 | import { Edge } from "../llvmir/cfg"; 4 | import { ViewPortContext } from "./context"; 5 | 6 | export interface EdgeProps { 7 | waypoints: PointVector; 8 | edge: Edge; 9 | } 10 | const scaleMap = (x: number) => x * x; 11 | 12 | const EdgeView = ({ waypoints, edge }: EdgeProps) => { 13 | const { scale } = useContext(ViewPortContext); 14 | 15 | const [isHovered, setIsHovered] = useState(false); 16 | 17 | let elements = []; 18 | let start = waypoints.get(0)!; 19 | 20 | let color = "var(--vscode-foreground)"; 21 | 22 | if (edge.type === "true") color = "var(--vscode-charts-green)"; 23 | else if (edge.type === "false") color = "var(--vscode-charts-red)"; 24 | if (isHovered) color = "var(--vscode-focusBorder)"; 25 | 26 | for (let j = 1; j < waypoints.size(); j++) { 27 | const end = waypoints.get(j)!; 28 | elements.push( 29 | 38 | ); 39 | elements.push( 40 | setIsHovered(true)} 49 | onMouseLeave={() => setIsHovered(false)} 50 | /> 51 | ); 52 | start = end; 53 | } 54 | 55 | elements.push( 56 | setIsHovered(true)} 63 | onMouseLeave={() => setIsHovered(false)} 64 | /> 65 | ); 66 | 67 | return {elements}; 68 | }; 69 | 70 | export default EdgeView; 71 | -------------------------------------------------------------------------------- /src/view/llvmir/parser.ts: -------------------------------------------------------------------------------- 1 | import { normalizeIdentifier } from "./common"; 2 | import { Regexp } from "./regexp"; 3 | import { Function, Module, BasicBlock } from "./cfg"; 4 | 5 | export const parse = (document: string): Module => { 6 | const module: Module = new Module(); 7 | 8 | let lastFunction: Function | undefined; 9 | let lastBlock: BasicBlock | undefined; 10 | 11 | const lines = document.split("\n"); 12 | 13 | for (let i = 0; i < lines.length; i++) { 14 | // Split at the first ';' to exclude comments 15 | const line = lines[i].split(";", 2)[0]; 16 | 17 | if (line === "") { 18 | continue; 19 | } 20 | 21 | const defineMatch = line.match(Regexp.define); 22 | if (defineMatch !== null && defineMatch.index !== null && defineMatch.groups !== undefined) { 23 | const funcid = defineMatch.groups["funcid"]; 24 | lastFunction = new Function(module, funcid); 25 | lastBlock = new BasicBlock(lastFunction, "entry"); 26 | continue; 27 | } 28 | 29 | const labelMatch = line.match(Regexp.label); 30 | if (labelMatch !== null && labelMatch.index !== undefined && labelMatch.groups !== undefined) { 31 | console.assert(lastFunction !== undefined, "Label found outside of function definition"); 32 | const block_name = normalizeIdentifier(`%${labelMatch.groups["label"]}`); 33 | 34 | // If this is the first block in the function, replace entry 35 | if (lastFunction!.basicBlocks.size === 1 && lastBlock!.instructions.length === 0) { 36 | lastFunction!.basicBlocks.clear(); 37 | lastFunction!.root = undefined; 38 | } else { 39 | console.assert(lastBlock === undefined, "Label found before terminator instruction"); 40 | } 41 | 42 | lastBlock = new BasicBlock(lastFunction!, block_name); 43 | continue; 44 | } 45 | 46 | const closeMatch = line.match(Regexp.close); 47 | if (closeMatch !== null) { 48 | console.assert(lastFunction !== undefined, "Function end found outside of function definition"); 49 | console.assert(lastBlock === undefined, "Function ended before terminator instruction"); 50 | 51 | lastBlock = undefined; 52 | lastFunction = undefined; 53 | continue; 54 | } 55 | 56 | if (lastBlock !== undefined) { 57 | const [terminated, j] = lastBlock.addInstruction(i, line, lines); 58 | i = j; 59 | 60 | if (terminated) { 61 | lastBlock = undefined; 62 | } 63 | } 64 | } 65 | 66 | return module; 67 | }; 68 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | //@ts-check 7 | "use strict"; 8 | 9 | //@ts-check 10 | /** @typedef {import('webpack').Configuration} WebpackConfig **/ 11 | 12 | const path = require("path"); 13 | const webpack = require("webpack"); 14 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 15 | 16 | /** @type WebpackConfig */ 17 | const webExtensionConfig = { 18 | mode: "none", 19 | target: "web", 20 | entry: { 21 | extension: "./src/web/extension.ts", 22 | "graph-viewer": "./src/view/graph-viewer.tsx", 23 | }, 24 | output: { 25 | filename: "[name].js", 26 | path: path.resolve(__dirname, "./dist"), 27 | libraryTarget: "commonjs", 28 | devtoolModuleFilenameTemplate: "../../[resource-path]", 29 | }, 30 | resolve: { 31 | extensions: [".ts", ".js", ".tsx", ".css"], 32 | }, 33 | module: { 34 | rules: [ 35 | { 36 | test: /\.(ts|tsx)$/, 37 | use: [ 38 | { 39 | loader: "ts-loader", 40 | }, 41 | ], 42 | exclude: /node_modules/, 43 | }, 44 | { 45 | test: /\.css$/, 46 | use: ["style-loader", "css-loader", "postcss-loader"], 47 | }, 48 | { 49 | test: /\.svg$/, 50 | use: ["@svgr/webpack"], 51 | generator: { 52 | cache: false, 53 | }, 54 | }, 55 | ], 56 | }, 57 | plugins: [ 58 | // fix "process is not defined" error: 59 | new webpack.ProvidePlugin({ 60 | process: "process/browser", 61 | }), 62 | new CopyWebpackPlugin({ 63 | patterns: [ 64 | { 65 | from: "src/view/triskel", 66 | to: "", 67 | }, 68 | ], 69 | }), 70 | ], 71 | externals: { 72 | vscode: "commonjs vscode", // ignored because it doesn't exist 73 | }, 74 | performance: { 75 | hints: false, 76 | }, 77 | devtool: "nosources-source-map", // create a source map that points to the original source file 78 | infrastructureLogging: { 79 | level: "log", // enables logging required for problem matchers 80 | }, 81 | cache: { 82 | type: "filesystem", // Enables persistent caching 83 | }, 84 | }; 85 | 86 | module.exports = [webExtensionConfig]; 87 | -------------------------------------------------------------------------------- /src/view/graph-viewer.ts: -------------------------------------------------------------------------------- 1 | import "./graph-viewer.css"; 2 | 3 | const NODE_WIDTH = 100; 4 | const NODE_HEIGHT = 75; 5 | 6 | // Dictionary to track nodes by id 7 | let nodes: { [key: string]: any } = {}; 8 | 9 | // Dictionary to track edges by id 10 | let edges: { [key: string]: any } = {}; 11 | 12 | let graphWidth = 0; 13 | let graphHeight = 0; 14 | 15 | let scale = 1; 16 | let offsetX = 0; 17 | let offsetY = 0; 18 | let isDragging = false; 19 | let startDragX: number, startDragY: number; 20 | 21 | // Function to set up the canvas for high-DPI screens 22 | const setupCanvas = (canvas: HTMLCanvasElement) => { 23 | const rect = canvas.getBoundingClientRect(); // Get CSS size 24 | const dpr = window.devicePixelRatio || 1; 25 | 26 | // Set internal resolution to match high-DPI screens 27 | canvas.width = rect.width * dpr; 28 | canvas.height = rect.height * dpr; 29 | 30 | // Scale drawing operations to match the new resolution 31 | const ctx = canvas.getContext("2d"); 32 | if (ctx) { 33 | ctx.setTransform(dpr, 0, 0, dpr, 0, 0); 34 | } 35 | return ctx; 36 | }; 37 | 38 | // Draws a node 39 | const drawNode = (ctx: CanvasRenderingContext2D, node_id: string) => { 40 | const node = nodes[node_id]; 41 | 42 | // Draw the rectangle 43 | ctx.beginPath(); 44 | ctx.rect(node.x, node.y, node.width, node.height); 45 | ctx.fillStyle = "white"; 46 | ctx.fill(); 47 | ctx.lineWidth = 2; 48 | ctx.strokeStyle = "black"; 49 | ctx.stroke(); 50 | 51 | ctx.font = "32px sans"; 52 | ctx.textAlign = "center"; 53 | ctx.textBaseline = "middle"; 54 | ctx.fillStyle = "black"; 55 | ctx.fillText(node.name, node.x + node.width / 2, node.y + node.height / 2); 56 | }; 57 | 58 | // Initialize the viewer 59 | window.addEventListener("load", () => { 60 | const canvas = document.getElementById("llvm-graph-view-graphCanvas") as HTMLCanvasElement; 61 | const graphInput = document.getElementById("llvm-graph-view-graphInput") as HTMLTextAreaElement; 62 | const ctx = setupCanvas(canvas); 63 | 64 | if (!ctx || !graphInput) { 65 | console.error("Failed to initialize graph viewer"); 66 | return; 67 | } 68 | 69 | // Set default input if empty 70 | if (graphInput.value === "") { 71 | graphInput.value = "a -> b\na -> e\nb -> c\nb -> d\ne -> f\nf -> e\nc -> g\nd -> g\ne -> g"; 72 | } 73 | 74 | // Handle window resize 75 | window.addEventListener("resize", () => { 76 | setupCanvas(canvas); 77 | }); 78 | 79 | // Add event listeners for graph manipulation 80 | document.getElementById("llvm-graph-view-updateGraphBtn")?.addEventListener("click", () => { 81 | // Update graph logic here 82 | }); 83 | 84 | document.getElementById("llvm-graph-view-centerGraphBtn")?.addEventListener("click", () => { 85 | // Center graph logic here 86 | }); 87 | }); 88 | -------------------------------------------------------------------------------- /src/view/components/SyntaxHighlighter.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode, useContext } from "react"; 2 | import rules from "../llvmir/highlighting"; 3 | import { SelectedBlockContext } from "./context"; 4 | 5 | export interface SyntaxHighlighterProps { 6 | children: string; 7 | } 8 | 9 | interface Unformatted { 10 | type: "unformatted"; 11 | value: string; 12 | } 13 | 14 | interface Formatted { 15 | type: "formatted"; 16 | value: ReactNode; 17 | } 18 | 19 | const SyntaxHighlighter = ({ children }: SyntaxHighlighterProps) => { 20 | const { setSelected } = useContext(SelectedBlockContext); 21 | 22 | // Function to apply styles based on regex rules 23 | const applySyntaxHighlighting = (text: string) => { 24 | let result: (Unformatted | Formatted)[] = [{ type: "unformatted", value: text }]; // Start with an array that contains the original text 25 | 26 | // Iterate through each rule and apply it to the text 27 | rules.forEach((rule) => { 28 | const newResult: (Unformatted | Formatted)[] = []; 29 | 30 | result.forEach((segment) => { 31 | if (segment.type === "formatted") { 32 | newResult.push(segment); 33 | return; 34 | } 35 | 36 | let lastIndex = 0; 37 | const matches = [...segment.value.matchAll(rule.regex)]; 38 | 39 | matches.forEach((match) => { 40 | const start = match.index!; 41 | const end = start + match[0].length!; 42 | 43 | if (start > lastIndex) { 44 | newResult.push({ type: "unformatted", value: segment.value.slice(lastIndex, start) }); 45 | } 46 | 47 | if (rule.name === "label") { 48 | newResult.push({ 49 | type: "formatted", 50 | value: ( 51 | setSelected({ name: match.groups!["label"]!, shouldFocus: true })} 56 | > 57 | {match[0]} 58 | 59 | ), 60 | }); 61 | } else { 62 | newResult.push({ 63 | type: "formatted", 64 | value: ( 65 | 66 | {match[0]} 67 | 68 | ), 69 | }); 70 | } 71 | 72 | lastIndex = end; 73 | }); 74 | 75 | if (lastIndex < segment.value.length) { 76 | newResult.push({ type: "unformatted", value: segment.value.slice(lastIndex) }); 77 | } 78 | }); 79 | 80 | result = newResult; 81 | }); 82 | 83 | return result; 84 | }; 85 | 86 | return <>{applySyntaxHighlighting(children).map((e) => e.value)}; 87 | }; 88 | 89 | export default SyntaxHighlighter; 90 | -------------------------------------------------------------------------------- /src/view/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import "./styles.css"; 3 | 4 | import useFileContents from "./hooks/useFileContents"; 5 | import { Function, Module } from "./llvmir/cfg"; 6 | import { parse } from "./llvmir/parser"; 7 | import GraphView from "./components/GraphView"; 8 | import { BlockSelection, Layout, LayoutContext, SelectedBlockContext, ViewPortContext } from "./components/context"; 9 | import FunctionView from "./components/FunctionView"; 10 | import { Point } from "./triskel/triskel-wasm"; 11 | import Minimap from "./components/Minimap"; 12 | import VscodeProgressRing from "@vscode-elements/react-elements/dist/components/VscodeProgressRing.js"; 13 | import VscodeSplitLayout from "@vscode-elements/react-elements/dist/components/VscodeSplitLayout.js"; 14 | import VscodeCollapsible from "@vscode-elements/react-elements/dist/components/VscodeCollapsible.js"; 15 | import FunctionSelection from "./components/FunctionSelection"; 16 | 17 | const App = () => { 18 | const document = useFileContents(); 19 | const [module, setModule] = useState(undefined); 20 | const [selectedFunction, setSelectFunction] = useState(undefined); 21 | const [layout, setLayout] = useState(undefined); 22 | const [selected, setSelected] = useState({ name: "" }); 23 | 24 | const [scale, setScale] = useState(1); 25 | const [pan, setPan] = useState({ x: 0, y: 0 }); 26 | const [size, setSize] = useState({ x: 0, y: 0 }); 27 | 28 | useEffect(() => { 29 | if (document === undefined) { 30 | return; 31 | } 32 | setModule(parse(document)); 33 | }, [document, setModule]); 34 | 35 | if (module === undefined) { 36 | return ( 37 |
38 | 39 |
40 | ); 41 | } 42 | 43 | return ( 44 |
45 | 46 | 47 | 48 | 49 |
50 |
51 | 56 | 57 |
58 | 59 | 60 | 61 | 62 |
63 |
64 | 65 |
66 | 67 | 68 |
69 | 70 | 71 | 72 | 73 |
74 | ); 75 | }; 76 | 77 | export default App; 78 | -------------------------------------------------------------------------------- /src/view/components/BasicBlockContainer.tsx: -------------------------------------------------------------------------------- 1 | import { useContext, useState } from "react"; 2 | import { BasicBlock } from "../llvmir/cfg"; 3 | import InstructionContainer from "./InstructionContainer"; 4 | import vscode from "../vscode"; 5 | import { BlockLayout, SelectedBlockContext, ViewPortContext } from "./context"; 6 | import VscodeIcon from "@vscode-elements/react-elements/dist/components/VscodeIcon.js"; 7 | 8 | export interface BasicBlockContainerProps { 9 | block: BlockLayout; 10 | name: string; 11 | } 12 | 13 | const scaleMap = (x: number) => x * x; 14 | 15 | const BasicBlockContainer = ({ block, name }: BasicBlockContainerProps) => { 16 | const { selected, setSelected } = useContext(SelectedBlockContext); 17 | const [isHovered, setIsHovered] = useState(false); 18 | const { scale } = useContext(ViewPortContext); 19 | 20 | if (scale < 0.3) { 21 | return ( 22 | 29 | ); 30 | } 31 | 32 | return ( 33 | 34 | 35 |
setIsHovered(true)} 42 | onMouseLeave={() => setIsHovered(false)} 43 | onFocus={() => setSelected({ name })} 44 | onBlur={() => setSelected({ name: "" })} 45 | > 46 |
47 |

label {name}

48 |
49 | { 57 | e.preventDefault(); 58 | e.target.dispatchEvent( 59 | new MouseEvent("contextmenu", { 60 | bubbles: true, 61 | clientX: e.clientX, 62 | clientY: e.clientY, 63 | }) 64 | ); 65 | e.stopPropagation(); 66 | }} 67 | /> 68 |
69 |
70 |
71 | 72 | {block.block && 73 | block.block.instructions.map((insn, idx) => )} 74 |
75 |
76 |
77 | ); 78 | }; 79 | 80 | export default BasicBlockContainer; 81 | -------------------------------------------------------------------------------- /src/view/llvmir/highlighting.ts: -------------------------------------------------------------------------------- 1 | // Inspired by https://github.com/colejcummins/llvm-syntax-highlighting/ 2 | 3 | import { CSSProperties, ReactNode } from "react"; 4 | 5 | export interface HighlightStyle { 6 | regex: RegExp; 7 | style: CSSProperties; 8 | name: string; 9 | callback?: (match: string) => ReactNode; 10 | } 11 | 12 | namespace RegexPatterns { 13 | // A modified \b 14 | const b = "(\\b(?%(${identifier}|\\d+))\\b`, "g"); 25 | export const global = new RegExp(`@\\b${identifier}\\b`, "g"); 26 | 27 | export const attribute = new RegExp(`[#!]\\b[-a-zA-Z$._0-9]+\\b`, "g"); 28 | 29 | export const constant = new RegExp(`${b}(true|false|null|none)\\b`, "g"); 30 | export const int = new RegExp(`${b}\\d+\\b`, "g"); 31 | export const float = new RegExp(`${b}\\d+\\.\\d+\\b`, "g"); 32 | export const hex = new RegExp(`${b}0(x|X)[0-9a-fA-F]+\\b`, "g"); 33 | 34 | export const string = new RegExp(`".+?"(?+)`, "g"); 43 | export const array = new RegExp(`(\\[d+s+xs+.+?\\]+)`, "g"); 44 | } 45 | 46 | const rules: HighlightStyle[] = [ 47 | { 48 | name: "comment", 49 | regex: RegexPatterns.comment, 50 | style: { color: "var(--vscode-symbolIcon-commentForeground)" }, 51 | }, 52 | { 53 | name: "string", 54 | regex: RegexPatterns.string, 55 | style: { color: "var(--vscode-symbolIcon-stringForeground)" }, 56 | }, 57 | { 58 | name: "label", 59 | regex: RegexPatterns.label, 60 | style: { color: "var(--vscode-symbolIcon-textForeground)" }, 61 | }, 62 | { 63 | name: "local", 64 | regex: RegexPatterns.local, 65 | style: { color: "var(--vscode-symbolIcon-textForeground)" }, 66 | }, 67 | { 68 | name: "global", 69 | regex: RegexPatterns.global, 70 | style: { color: "var(--vscode-symbolIcon-textForeground)" }, 71 | }, 72 | { 73 | name: "attribute", 74 | regex: RegexPatterns.attribute, 75 | style: { color: "var(--vscode-symbolIcon-colorForeground)" }, 76 | }, 77 | { 78 | name: "constant", 79 | regex: RegexPatterns.constant, 80 | style: { color: "var(--vscode-symbolIcon-numberForeground)" }, 81 | }, 82 | { 83 | name: "float", 84 | regex: RegexPatterns.float, 85 | style: { color: "var(--vscode-symbolIcon-numberForeground)" }, 86 | }, 87 | { 88 | name: "int", 89 | regex: RegexPatterns.int, 90 | style: { color: "var(--vscode-symbolIcon-numberForeground)" }, 91 | }, 92 | { 93 | name: "hex", 94 | regex: RegexPatterns.hex, 95 | style: { color: "var(--vscode-symbolIcon-numberForeground)" }, 96 | }, 97 | { 98 | name: "mnemonic", 99 | regex: RegexPatterns.mnemonic, 100 | style: { color: "var(--vscode-symbolIcon-keywordForeground)" }, 101 | }, 102 | { 103 | name: "primitive", 104 | regex: RegexPatterns.primitives, 105 | style: { color: "var(--vscode-symbolIcon-structForeground)" }, 106 | }, 107 | { 108 | name: "vector", 109 | regex: RegexPatterns.vector, 110 | style: { color: "var(--vscode-symbolIcon-structForeground)" }, 111 | }, 112 | { 113 | name: "array", 114 | regex: RegexPatterns.array, 115 | style: { color: "var(--vscode-symbolIcon-structForeground)" }, 116 | }, 117 | ]; 118 | 119 | export default rules; 120 | -------------------------------------------------------------------------------- /src/view/components/GraphView.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode, useEffect, useRef, useState } from "react"; 2 | import { Function, Edge } from "../llvmir/cfg"; 3 | import useWasm from "../hooks/useWasm"; 4 | import BasicBlockContainer from "./BasicBlockContainer"; 5 | import { BlockLayout, EdgeLayout, Layout } from "./context"; 6 | import SplashScreen from "./SplashScreen"; 7 | import VscodeProgressRing from "@vscode-elements/react-elements/dist/components/VscodeProgressRing.js"; 8 | 9 | export interface GraphViewProps { 10 | fun: Function | undefined; 11 | setLayout: React.Dispatch>; 12 | } 13 | 14 | const dfs = (fun: Function, block_name: string, visited: string[]) => { 15 | if (visited.indexOf(block_name) != -1) { 16 | return; 17 | } 18 | visited.push(block_name); 19 | const block = fun.basicBlocks.get(block_name)!; 20 | 21 | block.successors.forEach((child) => { 22 | dfs(fun, child.to, visited); 23 | }); 24 | }; 25 | 26 | const GraphView = ({ fun, setLayout }: GraphViewProps) => { 27 | const [wasm] = useWasm(); 28 | 29 | const [laidOut, setLaidOut] = useState(false); 30 | 31 | const [visited, setVisited] = useState([]); 32 | 33 | const itemRefs = useRef>(new Map()); 34 | 35 | useEffect(() => { 36 | if (fun === undefined) return; 37 | 38 | setLaidOut(false); 39 | 40 | // Identify nodes connected to the root 41 | let visited: string[] = []; 42 | dfs(fun, fun.root!, visited); 43 | setVisited(visited); 44 | 45 | console.log("VISITED", visited); 46 | 47 | itemRefs.current = new Map(); 48 | }, [fun, itemRefs, setVisited, setLaidOut]); 49 | 50 | useEffect(() => { 51 | if (laidOut || wasm === undefined || fun === undefined) { 52 | return; 53 | } 54 | 55 | const layout_graph = async () => { 56 | console.log("Laying out function"); 57 | 58 | const name_map = new Map(); 59 | let builder = wasm.make_layout_builder(); 60 | 61 | const getSize = (block: string) => { 62 | const bb = itemRefs.current.get(block)!.getBoundingClientRect()!; 63 | 64 | console.log(block, bb.width, bb.height); 65 | return bb; 66 | }; 67 | 68 | visited.forEach((block) => { 69 | const bb = getSize(block); 70 | const id = builder.make_node(bb.height, bb.width); 71 | name_map.set(block, id); 72 | }); 73 | 74 | const edges: Map = new Map(); 75 | visited.forEach((block) => 76 | fun.basicBlocks.get(block)!.successors.forEach((edge) => { 77 | const id = builder.make_edge(name_map.get(block)!, name_map.get(edge.to)!); 78 | edges.set(id, edge); 79 | }) 80 | ); 81 | 82 | let layout = builder.build(); 83 | 84 | const blockLayouts = new Map(); 85 | const edgeLayouts: EdgeLayout[] = []; 86 | 87 | visited.forEach((block) => { 88 | const id = name_map.get(block); 89 | const coords = layout.get_coords(id!); 90 | const size = getSize(block); 91 | 92 | blockLayouts.set(block, { 93 | x: coords.x, 94 | y: coords.y, 95 | width: size.width, 96 | height: size.height, 97 | block: fun.basicBlocks.get(block)!, 98 | }); 99 | }); 100 | 101 | for (let i = 0; i < layout.edge_count(); i++) { 102 | edgeLayouts.push({ 103 | waypoints: layout.get_waypoints(i), 104 | edge: edges.get(i)!, 105 | }); 106 | } 107 | 108 | setLayout({ 109 | blocks: blockLayouts, 110 | edges: edgeLayouts, 111 | width: layout.get_width(), 112 | height: layout.get_height(), 113 | }); 114 | setLaidOut(true); 115 | 116 | builder.delete(); 117 | layout.delete(); 118 | }; 119 | 120 | layout_graph(); 121 | }, [laidOut, visited, wasm, itemRefs, setLaidOut, setLayout]); 122 | 123 | if (laidOut) { 124 | return null; 125 | } 126 | 127 | if (fun === undefined) { 128 | return ; 129 | } 130 | 131 | return ( 132 |
133 | 134 | {visited.length > 200 && ( 135 |

136 | The function you want to display has {visited.length} nodes 137 |
In testing we managed to load functions with less than 1K nodes 138 |
139 | You might be here a while :) 140 |

141 | )} 142 |
143 | {visited.map((name, idx) => ( 144 |
itemRefs.current.set(name, el)}> 145 | 149 |
150 | ))} 151 |
152 |
153 | ); 154 | }; 155 | 156 | export default GraphView; 157 | -------------------------------------------------------------------------------- /src/view/components/FunctionSelection.tsx: -------------------------------------------------------------------------------- 1 | import VscodeTextfield from "@vscode-elements/react-elements/dist/components/VscodeTextfield.js"; 2 | import VscodeIcon from "@vscode-elements/react-elements/dist/components/VscodeIcon.js"; 3 | import VscodeTree from "@vscode-elements/react-elements/dist/components/VscodeTree.js"; 4 | import { Function, Module } from "../llvmir/cfg"; 5 | import { useContext, useEffect, useState } from "react"; 6 | import { SelectedBlockContext, ViewPortContext } from "./context"; 7 | 8 | export interface FunctionSelectionProps { 9 | module: Module; 10 | selectedFunction: Function | undefined; 11 | setSelectFunction: React.Dispatch>; 12 | } 13 | 14 | const FunctionSelection = ({ module, selectedFunction, setSelectFunction }: FunctionSelectionProps) => { 15 | const { selected, setSelected } = useContext(SelectedBlockContext); 16 | const { setScale } = useContext(ViewPortContext); 17 | 18 | const [search, setSearch] = useState(""); 19 | 20 | useEffect(() => { 21 | const handler = (event: MessageEvent) => { 22 | const message = event.data; // The JSON data our extension sent 23 | console.log(message); 24 | 25 | switch (message.command) { 26 | case "sync": { 27 | const function_name = message.function_name; 28 | const block_name = message.block_name; 29 | 30 | if (!selectedFunction || function_name !== selectedFunction.name) { 31 | setSelectFunction(module.functions.get(function_name)); 32 | } 33 | 34 | setSelected({ name: block_name, shouldFocus: true }); 35 | 36 | break; 37 | } 38 | } 39 | }; 40 | 41 | window.addEventListener("message", handler); 42 | 43 | return () => { 44 | window.removeEventListener("message", handler); 45 | }; 46 | }, [module, selectedFunction, setSelected, setSelectFunction, setScale]); 47 | 48 | return ( 49 |
50 | setSearch((e.target as any).value)} 55 | > 56 | 57 | 58 | 59 | 66 | (selectedFunction !== undefined && k === selectedFunction.name) || 67 | k.toLowerCase().indexOf(search.toLowerCase()) != -1 68 | ) 69 | .map(([k, v]) => { 70 | if (selectedFunction === undefined || k !== selectedFunction.name) 71 | return { 72 | label: k, 73 | value: `function-${k}`, 74 | tooltip: "Function", 75 | decorations: [ 76 | { 77 | appearance: "counter-badge", 78 | content: `${v.basicBlocks.size}`, 79 | }, 80 | ], 81 | subItems: [ 82 | { 83 | label: "", 84 | }, 85 | ], 86 | }; 87 | 88 | return { 89 | label: k, 90 | tooltip: "Function", 91 | value: `function-${k}`, 92 | open: true, 93 | selected: true, 94 | decorations: [ 95 | { 96 | appearance: "counter-badge", 97 | content: `${v.basicBlocks.size}`, 98 | }, 99 | ], 100 | subItems: [...v.basicBlocks] 101 | .filter(([k, _]) => k.toLowerCase().indexOf(search.toLowerCase()) != -1) 102 | .map(([k, _]) => ({ 103 | label: k, 104 | selected: k === selected.name, 105 | tooltip: "Basic Block", 106 | value: `block-${k}`, 107 | })), 108 | }; 109 | })} 110 | onVscTreeSelect={(e) => { 111 | console.log(e, e.detail.value, e.detail.label); 112 | if (e.detail.value.startsWith("function")) { 113 | if (selectedFunction !== undefined && selectedFunction.name === e.detail.label) { 114 | setSelectFunction(undefined); 115 | } else { 116 | setSelectFunction(module.functions.get(e.detail.label)); 117 | } 118 | 119 | setSelected({ name: "" }); 120 | } else if (e.detail.value.startsWith("block")) { 121 | if (selected.name === e.detail.label) { 122 | setSelected({ name: "" }); 123 | } else { 124 | setSelected({ name: e.detail.label, shouldFocus: true }); 125 | } 126 | } 127 | }} 128 | /> 129 |
130 | ); 131 | }; 132 | 133 | export default FunctionSelection; 134 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "llvm-cfg", 3 | "publisher": "JackRoyer", 4 | "license": "AGPL-3.0-only", 5 | "author": "Jack Royer", 6 | "displayName": "LLVM CFG View", 7 | "description": "LLVM IR CFG view for Visual Studio Code", 8 | "version": "1.1.1", 9 | "repository": "https://github.com/triskellib/vscode", 10 | "icon": "./assets/triskel_dragon.png", 11 | "engines": { 12 | "vscode": "^1.63.0" 13 | }, 14 | "contributes": { 15 | "menus": { 16 | "webview/context": [ 17 | { 18 | "command": "llvm-cfg.graph-commands.center", 19 | "group": "graph-commands", 20 | "when": "webviewId == 'llvm-cfg.graphView' && webviewSection == 'graph-view'" 21 | }, 22 | { 23 | "command": "llvm-cfg.graph-commands.zoom", 24 | "group": "graph-commands", 25 | "when": "webviewId == 'llvm-cfg.graphView' && webviewSection == 'graph-view'" 26 | }, 27 | { 28 | "command": "llvm-cfg.basicblock-commands.copy", 29 | "group": "basicblock-commands", 30 | "when": "webviewId == 'llvm-cfg.graphView' && webviewSection == 'basicblock-view'" 31 | }, 32 | { 33 | "command": "llvm-cfg.basicblock-commands.goto", 34 | "group": "basicblock-commands", 35 | "when": "webviewId == 'llvm-cfg.graphView' && webviewSection == 'basicblock-view'" 36 | }, 37 | { 38 | "command": "llvm-cfg.basicblock-commands.center", 39 | "group": "basicblock-commands", 40 | "when": "webviewId == 'llvm-cfg.graphView' && webviewSection == 'basicblock-view'" 41 | } 42 | ], 43 | "editor/title": [ 44 | { 45 | "command": "llvm-cfg.showPreview", 46 | "when": "resourceLangId == llvm", 47 | "group": "navigation" 48 | } 49 | ], 50 | "editor/context": [ 51 | { 52 | "command": "llvm-cfg.sync-views", 53 | "when": "editorLangId == llvm", 54 | "group": "navigation" 55 | } 56 | ] 57 | }, 58 | "commands": [ 59 | { 60 | "command": "llvm-cfg.showPreview", 61 | "title": "Show Graph View", 62 | "icon": "$(triskel-icon)" 63 | }, 64 | { 65 | "command": "llvm-cfg.graph-commands.center", 66 | "title": "Center graph", 67 | "category": "Graph View" 68 | }, 69 | { 70 | "command": "llvm-cfg.graph-commands.zoom", 71 | "title": "Zoom 100%", 72 | "category": "Graph View" 73 | }, 74 | { 75 | "command": "llvm-cfg.basicblock-commands.copy", 76 | "title": "Copy content", 77 | "category": "Basic Block" 78 | }, 79 | { 80 | "command": "llvm-cfg.basicblock-commands.goto", 81 | "title": "Goto basic block in file", 82 | "category": "Basic Block" 83 | }, 84 | { 85 | "command": "llvm-cfg.basicblock-commands.center", 86 | "title": "Center on basic block", 87 | "category": "Basic Block" 88 | }, 89 | { 90 | "command": "llvm-cfg.sync-views", 91 | "title": "Sync Graph View", 92 | "category": "Editor" 93 | } 94 | ], 95 | "icons": { 96 | "triskel-icon": { 97 | "description": "Triskel icon", 98 | "default": { 99 | "fontPath": "assets/triskel-icons.woff", 100 | "fontCharacter": "\\E900" 101 | } 102 | } 103 | }, 104 | "languages": [ 105 | { 106 | "id": "llvm", 107 | "aliases": [ 108 | "LLVM", 109 | "llvm" 110 | ], 111 | "extensions": [ 112 | ".ll" 113 | ] 114 | } 115 | ] 116 | }, 117 | "activationEvents": [ 118 | "onStartupFinished" 119 | ], 120 | "browser": "./dist/extension.js", 121 | "scripts": { 122 | "integration-test": "vscode-test-web --browserType=chromium --extensionDevelopmentPath=. --extensionTestsPath=dist/web/test/suite/index.js", 123 | "test": "jest", 124 | "pretest": "yarn run compile-web", 125 | "vscode:prepublish": "yarn run package-web", 126 | "compile-web": "webpack", 127 | "watch-web": "webpack --watch", 128 | "package-web": "webpack --mode production --devtool hidden-source-map", 129 | "docs": "typedoc", 130 | "lint": "eslint src --ext ts", 131 | "lint-staged": "lint-staged", 132 | "pretty": "prettier --config .prettierrc 'src/**/*.ts' --write", 133 | "format": "eslint src --fix --ext ts && prettier --config .prettierrc 'src/**/*.ts' --write", 134 | "run-in-browser": "vscode-test-web --browserType=chromium --extensionDevelopmentPath=. .", 135 | "prepare": "husky install" 136 | }, 137 | "devDependencies": { 138 | "@babel/preset-react": "^7.26.3", 139 | "@svgr/webpack": "^8.1.0", 140 | "@types/jest-when": "^3.5.0", 141 | "@types/mocha": "^9.0.0", 142 | "@types/react": "^18.3.18", 143 | "@types/react-dom": "^18.3.5", 144 | "@types/vscode": "^1.63.0", 145 | "@types/webpack-env": "^1.16.3", 146 | "@typescript-eslint/eslint-plugin": "^5.9.1", 147 | "@typescript-eslint/parser": "^5.9.1", 148 | "@vscode/test-web": "^0.0.15", 149 | "assert": "^2.0.0", 150 | "autoprefixer": "^10.4.21", 151 | "css-loader": "^7.1.2", 152 | "eslint": "^8.6.0", 153 | "eslint-plugin-node": "^11.1.0", 154 | "eslint-plugin-prettier": "^4.0.0", 155 | "file-loader": "^6.2.0", 156 | "glob": "^7.2.0", 157 | "gts": "^3.1.0", 158 | "husky": "^7.0.4", 159 | "jest": "^27.5.1", 160 | "jest-mock-vscode": "^0.1.3", 161 | "jest-when": "^3.5.1", 162 | "lint-staged": ">=10", 163 | "mini-css-extract-plugin": "^2.9.2", 164 | "mocha": "^9.1.3", 165 | "postcss-loader": "^8.1.1", 166 | "prettier": "^2.5.1", 167 | "process": "^0.11.10", 168 | "shiki": "^3.2.1", 169 | "style-loader": "^4.0.0", 170 | "ts-jest": "^27.1.3", 171 | "ts-loader": "^9.2.6", 172 | "typedoc": "^0.22.12", 173 | "typescript": "^4.5.4", 174 | "vsce": "^2.6.7", 175 | "webpack": "^5.66.0", 176 | "webpack-cli": "^4.9.1" 177 | }, 178 | "lint-staged": { 179 | "*.(t|j)s": [ 180 | "eslint --cache --fix", 181 | "prettier --write" 182 | ], 183 | "*.(json|md)": [ 184 | "prettier --write" 185 | ] 186 | }, 187 | "dependencies": { 188 | "@emotion/is-prop-valid": "^1.3.1", 189 | "@tailwindcss/postcss": "^4.0.14", 190 | "@vscode-elements/react-elements": "^0.9.0", 191 | "@vscode/codicons": "^0.0.36", 192 | "copy-webpack-plugin": "^13.0.0", 193 | "path": "^0.12.7", 194 | "postcss": "^8.5.3", 195 | "react": "^19.0.0", 196 | "react-dom": "^19.0.0", 197 | "react-elements": "vscode-elements/react-elements", 198 | "tailwindcss": "^4.0.14" 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /src/view/components/triskel.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | -------------------------------------------------------------------------------- /assets/triskel_black.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /assets/triskel_white.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | -------------------------------------------------------------------------------- /src/view/llvmir/regexp.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Namespace containing all regexps for parsing LLVM IR 3 | */ 4 | export namespace Regexp { 5 | // Fragments 6 | 7 | /** 8 | * Standard identifier from https://llvm.org/docs/LangRef.html#identifiers 9 | */ 10 | const identifierFrag = xstr(`( 11 | [-a-zA-Z$._][-a-zA-Z$._0-9]*| # Standard Identifier Regex 12 | ".*?" # Quoted identifier 13 | )`); 14 | 15 | /** 16 | * Matches global identifiers 17 | */ 18 | const globalVarFrag = `@(${identifierFrag}|\\d+)`; 19 | 20 | /** 21 | * Matches local identifiers 22 | */ 23 | const allLocalVarFrag = xstr(`%( 24 | ${identifierFrag}| # Named identifiers 25 | \\d+ # Anonymous identifiers 26 | )`); 27 | 28 | /** 29 | * Matches attributes 30 | */ 31 | const attributeGroupFrag = "#\\d+"; 32 | 33 | /** 34 | * Matches metadata 35 | */ 36 | const metadataFrag = `!(${identifierFrag}|\\d+)`; 37 | 38 | /** 39 | * Vacuum up all identifiers by "OR-ing" all of them 40 | */ 41 | const allIdentifiersFrag = xstr(`( 42 | ${globalVarFrag}| # Global Identifiers 43 | ${allLocalVarFrag}| # Local variables 44 | ${attributeGroupFrag}| # Attributes 45 | ${metadataFrag} # Metadata 46 | )`); 47 | 48 | // Regexes 49 | 50 | /** 51 | * Generic identifier regex, without named capture 52 | * Used with getWordRangeAtPosition 53 | */ 54 | export const identifier = new RegExp(`${allIdentifiersFrag}`); 55 | 56 | /** 57 | * Matches an identifier or a label 58 | */ 59 | export const identifierOrLabel = xre( 60 | `( 61 | ${allIdentifiersFrag}| # Normal identifier 62 | (${identifierFrag}|\\d+): # Label identifier 63 | )` 64 | ); 65 | 66 | /** 67 | * We consider an assignment an identifier followed by a '=' 68 | * Since the named capture 'value' is first it will have precedence 69 | * otherwise it is a reference it will show up in the named caputure 'user' 70 | */ 71 | export const valueOrUser = xre( 72 | `( 73 | (?${allIdentifiersFrag})\\s*=| # Assignments are captured first if applicable 74 | (?${allIdentifiersFrag})(\\*|) # Otherwise grab identifiers as uses 75 | )`, 76 | "g" 77 | ); 78 | 79 | /** 80 | * We take all locals followed optionally by a comma 81 | * This is used in function declarations to grab 82 | * the 'assignment' of the function's parameters 83 | */ 84 | export const argument = xre( 85 | ` 86 | (?${allLocalVarFrag}) # Capture local variables in the 'value' capture 87 | \\s* # Whitespace can follow 88 | (,|$) # Must end with a comma or end of string 89 | `, 90 | "g" 91 | ); 92 | 93 | /** 94 | * Labels are matched inside the 'label' capture 95 | */ 96 | export const label = xre(` 97 | ^ # Match start of line 98 | (?