├── .eslintrc.json ├── .github ├── branch.png ├── top_right.png └── triskel.png ├── .gitignore ├── .husky └── pre-commitA ├── .prettierrc ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── .vscodeignore ├── LICENSE.md ├── README.md ├── assets ├── .gitignore ├── triskel-icons.woff ├── triskel_black.svg ├── triskel_dragon.png └── triskel_white.svg ├── package.json ├── postcss.config.js ├── src ├── custom.d.ts ├── view │ ├── App.tsx │ ├── components │ │ ├── BasicBlockContainer.tsx │ │ ├── EdgeView.tsx │ │ ├── FunctionSelection.tsx │ │ ├── FunctionView.tsx │ │ ├── GraphView.tsx │ │ ├── InstructionContainer.tsx │ │ ├── Minimap.tsx │ │ ├── SearchableComboBox.tsx │ │ ├── SplashScreen.tsx │ │ ├── SyntaxHighlighter.tsx │ │ ├── TransformContainer.tsx │ │ ├── context.ts │ │ └── triskel.svg │ ├── graph-viewer.ts │ ├── graph-viewer.tsx │ ├── hooks │ │ ├── useFileContents.ts │ │ └── useWasm.ts │ ├── llvmir │ │ ├── cfg.ts │ │ ├── common.ts │ │ ├── highlighting.ts │ │ ├── parser.ts │ │ └── regexp.ts │ ├── styles.css │ ├── triskel │ │ ├── triskel-wasm.d.ts │ │ ├── triskel-wasm.js │ │ └── triskel-wasm.wasm │ └── vscode.ts └── web │ └── extension.ts ├── tailwind.config.js ├── tsconfig.json ├── typedoc.js ├── webpack.config.js └── yarn.lock /.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 | } -------------------------------------------------------------------------------- /.github/branch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/a09d0af41457a45b758ba1f005c5dc4a355eda37/.github/branch.png -------------------------------------------------------------------------------- /.github/top_right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/a09d0af41457a45b758ba1f005c5dc4a355eda37/.github/top_right.png -------------------------------------------------------------------------------- /.github/triskel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/a09d0af41457a45b758ba1f005c5dc4a355eda37/.github/triskel.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | dist 3 | node_modules 4 | .vscode-test-web/ 5 | *.vsix 6 | .eslintcache 7 | docs -------------------------------------------------------------------------------- /.husky/pre-commitA: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn run lint-staged -------------------------------------------------------------------------------- /.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/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 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "basicblock", 4 | "funcid", 5 | "iffalse", 6 | "iftrue", 7 | "indirectbr", 8 | "insn", 9 | "Royer" 10 | ] 11 | } -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | **/*.ts 2 | **/*.tsx 3 | **/tsconfig.json 4 | 5 | *.ll -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /assets/.gitignore: -------------------------------------------------------------------------------- 1 | triskel-icons/ -------------------------------------------------------------------------------- /assets/triskel-icons.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/a09d0af41457a45b758ba1f005c5dc4a355eda37/assets/triskel-icons.woff -------------------------------------------------------------------------------- /assets/triskel_black.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /assets/triskel_dragon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/triskellib/vscode/a09d0af41457a45b758ba1f005c5dc4a355eda37/assets/triskel_dragon.png -------------------------------------------------------------------------------- /assets/triskel_white.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | "@tailwindcss/postcss": {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /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/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/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/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 | -------------------------------------------------------------------------------- /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/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/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/Minimap.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef, ReactNode, useCallback, useEffect, useContext } from "react"; 2 | import { LayoutContext, SelectedBlockContext, ViewPortContext } from "./context"; 3 | import { Point } from "../triskel/triskel-wasm"; 4 | 5 | const PADDING = 200; 6 | 7 | const Minimap = () => { 8 | const layout = useContext(LayoutContext); 9 | const viewport = useContext(ViewPortContext); 10 | const { selected } = useContext(SelectedBlockContext); 11 | 12 | const [scale, setScale] = useState(1); 13 | const [pan, setPan] = useState({ x: 0, y: 0 }); 14 | 15 | const containerRef = useRef(null); 16 | 17 | const [svgSize, setSvgSize] = useState({ width: 0, height: 0 }); 18 | 19 | const [isPanning, setIsPanning] = useState(false); 20 | const [startPan, setStartPan] = useState({ x: 0, y: 0 }); 21 | 22 | const scaleMap = useCallback((x: number) => x * x, []); 23 | 24 | // Centers the graph 25 | const center = useCallback(() => { 26 | if (!containerRef.current || layout === undefined) return; 27 | 28 | const paddedWidth = layout.width + 2 * PADDING; 29 | const paddedHeight = layout.height + 2 * PADDING; 30 | 31 | const rect = containerRef.current.getBoundingClientRect(); 32 | const newScale = Math.min(rect.width / paddedWidth, rect.height / paddedHeight); 33 | setScale(Math.sqrt(newScale)); 34 | 35 | let x = 0; 36 | if (paddedWidth < rect.width / newScale) { 37 | x = (paddedWidth - rect.width / newScale) / 2; 38 | } 39 | 40 | let y = 0; 41 | if (paddedHeight < rect.height / newScale) { 42 | y = (paddedHeight - rect.height / newScale) / 2; 43 | } 44 | 45 | x = (x - PADDING) * newScale; 46 | y = (y - PADDING) * newScale; 47 | 48 | setPan({ x, y }); 49 | }, [containerRef.current, layout, setPan]); 50 | 51 | useEffect(center, [center]); 52 | 53 | const handleMouseDown = (event: React.MouseEvent) => { 54 | if (event.button !== 0 || !containerRef.current || !layout) return; 55 | setIsPanning(true); 56 | 57 | const rect = containerRef.current.getBoundingClientRect(); 58 | let x = (event.clientX - rect.left + pan.x) / scaleMap(scale); 59 | let y = (event.clientY - rect.top + pan.y) / scaleMap(scale); 60 | 61 | x = x * scaleMap(viewport.scale) - viewport.size.x / 2; 62 | y = y * scaleMap(viewport.scale) - viewport.size.y / 2; 63 | 64 | const scaleRatio = scaleMap(scale) / scaleMap(viewport.scale); 65 | setStartPan({ 66 | x: x - event.clientX / scaleRatio, 67 | y: y - event.clientY / scaleRatio, 68 | }); 69 | }; 70 | 71 | const handleMouseUp = useCallback(() => { 72 | setIsPanning(false); 73 | }, [setIsPanning]); 74 | 75 | const handleMouseMove = (event: React.MouseEvent) => { 76 | if (isPanning) { 77 | const scaleRatio = scaleMap(scale) / scaleMap(viewport.scale); 78 | viewport.setPan({ 79 | x: startPan.x + event.clientX / scaleRatio, 80 | y: startPan.y + event.clientY / scaleRatio, 81 | }); 82 | } 83 | }; 84 | 85 | // Gets the size of the SVG 86 | useEffect(() => { 87 | if (!containerRef.current) return; 88 | const rect = containerRef.current.getBoundingClientRect(); 89 | setSvgSize({ width: rect.width, height: rect.height }); 90 | }, [scale, containerRef.current, setSvgSize, scaleMap]); 91 | 92 | // Size observer 93 | useEffect(() => { 94 | if (!containerRef.current) return; 95 | 96 | const observer = new ResizeObserver(([entry]) => { 97 | setSvgSize({ 98 | width: entry.contentRect.width, 99 | height: entry.contentRect.height, 100 | }); 101 | center(); 102 | }); 103 | 104 | observer.observe(containerRef.current); 105 | 106 | return () => { 107 | observer.disconnect(); 108 | }; 109 | }, [containerRef.current, center, setSvgSize]); 110 | 111 | // The size of the viewport 112 | const ViewPortX = Math.max(pan.x / scaleMap(scale), viewport.pan.x / scaleMap(viewport.scale)) * scaleMap(scale); 113 | const ViewPortY = Math.max(pan.y / scaleMap(scale), viewport.pan.y / scaleMap(viewport.scale)) * scaleMap(scale); 114 | 115 | const ViewPortWidth = 116 | Math.min( 117 | (pan.x + svgSize.width) / scaleMap(scale), 118 | (viewport.pan.x + viewport.size.x) / scaleMap(viewport.scale) 119 | ) * 120 | scaleMap(scale) - 121 | ViewPortX; 122 | const ViewPortHeight = 123 | Math.min( 124 | (pan.y + svgSize.height) / scaleMap(scale), 125 | (viewport.pan.y + viewport.size.y) / scaleMap(viewport.scale) 126 | ) * 127 | scaleMap(scale) - 128 | ViewPortY; 129 | 130 | return ( 131 |
136 |
143 | 153 | 154 | 155 | 156 | 163 | 164 | 165 | 166 | 167 | {layout && 168 | [...layout.blocks].map(([name, block], idx) => ( 169 | 181 | ))} 182 | 183 | 184 | 192 | 200 | 201 |
202 |
203 | ); 204 | }; 205 | 206 | export default Minimap; 207 | -------------------------------------------------------------------------------- /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/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/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/components/TransformContainer.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef, ReactNode, useCallback, useEffect, useContext } from "react"; 2 | import { LayoutContext, SelectedBlockContext, ViewPortContext } from "./context"; 3 | import EdgeView from "./EdgeView"; 4 | 5 | const PADDING = 200; 6 | 7 | interface TransformContainerProps { 8 | children: ReactNode; 9 | width: number; 10 | height: number; 11 | } 12 | 13 | const TransformContainer = ({ children, width, height }: TransformContainerProps) => { 14 | const { scale, setScale, size, setSize, pan, setPan } = useContext(ViewPortContext); 15 | const layout = useContext(LayoutContext); 16 | const { selected, setSelected } = useContext(SelectedBlockContext); 17 | 18 | const [lastMouse, setLastMouse] = useState({ x: 0, y: 0 }); 19 | const containerRef = useRef(null); 20 | 21 | const [isPanning, setIsPanning] = useState(false); 22 | const [startPan, setStartPan] = useState({ x: 0, y: 0 }); 23 | 24 | const scaleMap = useCallback((x: number) => x * x, []); 25 | 26 | const center = useCallback(() => { 27 | if (!containerRef.current) return; 28 | 29 | const paddedWidth = width + 2 * PADDING; 30 | const paddedHeight = height + 2 * PADDING; 31 | 32 | const rect = containerRef.current.getBoundingClientRect(); 33 | const newScale = Math.max(Math.min(rect.width / paddedWidth, rect.height / paddedHeight, 1), 0.001); 34 | setScale(Math.sqrt(newScale)); 35 | 36 | let x = 0; 37 | if (paddedWidth < rect.width / newScale) { 38 | x = (paddedWidth - rect.width / newScale) / 2; 39 | } 40 | 41 | let y = 0; 42 | if (paddedHeight < rect.height / newScale) { 43 | y = (paddedHeight - rect.height / newScale) / 2; 44 | } 45 | 46 | x = (x - PADDING) * newScale; 47 | y = (y - PADDING) * newScale; 48 | 49 | setPan({ x, y }); 50 | }, [containerRef.current, width, height, setPan]); 51 | 52 | useEffect(center, [center]); 53 | 54 | useEffect(() => { 55 | if (layout === undefined || !containerRef.current || !selected.shouldFocus) return; 56 | setSelected({ name: selected.name }); 57 | 58 | const rect = containerRef.current.getBoundingClientRect(); 59 | 60 | const block = layout.blocks.get(selected.name)!; 61 | 62 | const x = ((block.width + 2 * block.x) * scaleMap(scale) - rect.width) / 2; 63 | const y = ((block.height + 2 * block.y) * scaleMap(scale) - rect.height) / 2; 64 | setPan({ x, y }); 65 | }, [containerRef.current, scale, selected, layout, setPan]); 66 | 67 | // Zoom while preserving the cursor position in world space 68 | const setScaleAndPos = useCallback( 69 | (newScale: number, clientX: number, clientY: number) => { 70 | if (!containerRef.current) return; 71 | 72 | const rect = containerRef.current.getBoundingClientRect(); 73 | const mouseX = clientX - rect.left; 74 | const mouseY = clientY - rect.top; 75 | 76 | const scaleRatio = scaleMap(newScale) / scaleMap(scale); 77 | 78 | // Adjust position to keep the mouse position fixed during zooming 79 | setPan({ 80 | x: (mouseX + pan.x) * scaleRatio - mouseX, 81 | y: (mouseY + pan.y) * scaleRatio - mouseY, 82 | }); 83 | 84 | setScale(newScale); 85 | }, 86 | [containerRef, pan, setPan, scale, setScale] 87 | ); 88 | 89 | const handleWheel = useCallback( 90 | (event: React.WheelEvent) => { 91 | event.preventDefault(); 92 | event.stopPropagation(); 93 | const newScale = Math.min(Math.max(scale - event.deltaY * 0.0005, 0.01), 1); 94 | setScaleAndPos(newScale, event.clientX, event.clientY); 95 | }, 96 | [setScaleAndPos] 97 | ); 98 | 99 | const handleMouseDown = useCallback( 100 | (event: React.MouseEvent) => { 101 | if (event.button !== 1 || !containerRef.current) return; 102 | setIsPanning(true); 103 | setStartPan({ x: pan.x + event.clientX, y: pan.y + event.clientY }); 104 | }, 105 | [pan, setIsPanning, setStartPan] 106 | ); 107 | 108 | const handleMouseUp = useCallback(() => { 109 | setIsPanning(false); 110 | }, [setIsPanning]); 111 | 112 | const handleMouseMove = useCallback( 113 | (event: React.MouseEvent) => { 114 | if (isPanning) { 115 | setPan({ 116 | x: startPan.x - event.clientX, 117 | y: startPan.y - event.clientY, 118 | }); 119 | } 120 | 121 | setLastMouse({ x: event.clientX, y: event.clientY }); 122 | }, 123 | [isPanning, startPan, setLastMouse] 124 | ); 125 | 126 | useEffect(() => { 127 | if (!containerRef.current) return; 128 | const rect = containerRef.current.getBoundingClientRect(); 129 | 130 | setSize({ x: rect.width, y: rect.height }); 131 | }, [scale, containerRef.current, setSize, scaleMap]); 132 | 133 | // Context menu 134 | useEffect(() => { 135 | const handler = (event: MessageEvent) => { 136 | const message = event.data; // The JSON data our extension sent 137 | console.log(message); 138 | 139 | switch (message.command) { 140 | case "graph-commands.zoom": { 141 | setScaleAndPos(1, lastMouse.x, lastMouse.y); 142 | break; 143 | } 144 | 145 | case "graph-commands.center": { 146 | center(); 147 | break; 148 | } 149 | 150 | case "basicblock-commands.center": { 151 | setSelected({ name: message.block, shouldFocus: true }); 152 | break; 153 | } 154 | } 155 | }; 156 | 157 | window.addEventListener("message", handler); 158 | 159 | return () => { 160 | window.removeEventListener("message", handler); 161 | }; 162 | }, [setSelected, setScaleAndPos, center, containerRef, lastMouse]); 163 | 164 | useEffect(() => { 165 | if (!containerRef.current) return; 166 | const rect = containerRef.current.getBoundingClientRect(); 167 | setSize({ x: rect.width, y: rect.height }); 168 | }, [containerRef.current, setSize]); 169 | 170 | useEffect(() => { 171 | if (!containerRef.current) return; 172 | 173 | const observer = new ResizeObserver(([entry]) => { 174 | setSize({ x: entry.contentRect.width, y: entry.contentRect.height }); 175 | }); 176 | 177 | observer.observe(containerRef.current); 178 | 179 | return () => { 180 | observer.disconnect(); 181 | }; 182 | }, [containerRef.current, setSize]); 183 | 184 | // Mouse coordinates for display 185 | let mouseX = 0; 186 | let mouseY = 0; 187 | 188 | if (containerRef.current) { 189 | const rect = containerRef.current.getBoundingClientRect(); 190 | 191 | mouseX = Math.trunc((lastMouse.x + pan.x - rect.left) / scaleMap(scale)); 192 | mouseY = Math.trunc((lastMouse.y + pan.y - rect.top) / scaleMap(scale)); 193 | } 194 | 195 | return ( 196 |
201 |
210 | 221 | {children} 222 | 223 |
224 |
225 |

226 | 227 | Mouse: ({mouseX}, {mouseY}) 228 | 229 | 230 | Zoom: {Math.round(scaleMap(scale) * 100)}% 231 |

232 |
233 |
234 | ); 235 | }; 236 | 237 | export default TransformContainer; 238 | -------------------------------------------------------------------------------- /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/components/triskel.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /src/view/llvmir/cfg.ts: -------------------------------------------------------------------------------- 1 | /// A type for the AST of LLVM IR 2 | 3 | import { Regexp } from "./regexp"; 4 | 5 | export type AST = { 6 | module: Module; 7 | }; 8 | 9 | export class Module { 10 | functions: Map = new Map(); 11 | } 12 | 13 | export class Function { 14 | basicBlocks: Map = new Map(); 15 | root: string | undefined = undefined; 16 | 17 | constructor(public module: Module, public name: string) { 18 | module.functions.set(name, this); 19 | } 20 | } 21 | 22 | export class Edge { 23 | constructor(public from: string, public to: string, public type: "true" | "false" | "none" = "none") {} 24 | } 25 | 26 | export class BasicBlock { 27 | instructions: Instruction[] = []; 28 | 29 | successors: Edge[] = []; 30 | 31 | first_address: number | undefined = undefined; 32 | 33 | constructor(public fun: Function, public name: string) { 34 | fun.basicBlocks.set(name, this); 35 | if (fun.root === undefined) { 36 | fun.root = name; 37 | } 38 | } 39 | 40 | addEdge(to: string, type: "true" | "false" | "none" = "none") { 41 | this.successors.push(new Edge(this.name, to, type)); 42 | } 43 | 44 | /** 45 | * Add an instruction to the basic block 46 | * @param insn The instruction to add 47 | * @returns True if the instruction is a terminator instruction 48 | */ 49 | addInstruction(line_nb: number, insn: string, lines: string[]): [boolean, number] { 50 | if (this.first_address === undefined) this.first_address = line_nb; 51 | else this.first_address = Math.min(this.first_address, line_nb); 52 | 53 | const conditionalBranchMatch = insn.match(Regexp.conditionalBranchInstruction); 54 | if (insn.startsWith(" br i1")) console.log([...insn], conditionalBranchMatch); 55 | if (conditionalBranchMatch !== null && conditionalBranchMatch.groups !== undefined) { 56 | console.log("Found a branch", insn); 57 | const conditional = conditionalBranchMatch.groups["conditional"]; 58 | const iftrue = conditionalBranchMatch.groups["iftrue"]; 59 | const iffalse = conditionalBranchMatch.groups["iffalse"]; 60 | const branchInstruction = new ConditionalBranchInstruction( 61 | conditional, 62 | new Label(iftrue), 63 | new Label(iffalse), 64 | insn, 65 | line_nb + 1 66 | ); 67 | this.instructions.push(branchInstruction); 68 | 69 | this.addEdge(iftrue, "true"); 70 | this.addEdge(iffalse, "false"); 71 | return [false, line_nb]; 72 | } 73 | 74 | const unconditionalBranchMatch = insn.match(Regexp.unconditionalBranchInstruction); 75 | if (unconditionalBranchMatch !== null && unconditionalBranchMatch.groups !== undefined) { 76 | const target = unconditionalBranchMatch.groups["target"]; 77 | const branchInstruction = new UnconditionalBranchInstruction(new Label(target), insn, line_nb + 1); 78 | this.instructions.push(branchInstruction); 79 | 80 | this.addEdge(target); 81 | return [false, line_nb]; 82 | } 83 | 84 | const switchMatch = insn.match(Regexp.switchInstruction); 85 | if (switchMatch !== null && switchMatch.groups !== undefined) { 86 | const value = switchMatch.groups["value"]; 87 | const defaultTarget = switchMatch.groups["default"]; 88 | 89 | this.addEdge(defaultTarget); 90 | 91 | let extended_insn = insn; 92 | const initial_line_nb = line_nb; 93 | while (extended_insn.indexOf("]") == -1) { 94 | line_nb += 1; 95 | extended_insn += "\n" + lines[line_nb]; 96 | } 97 | 98 | const targetMatches = [...extended_insn.substring(switchMatch[0].length).matchAll(Regexp.switchCases)]; 99 | 100 | let targets: { value: string; target: Label }[] = []; 101 | 102 | for (let j = 1; j < targetMatches.length; ++j) { 103 | const value = targetMatches[j].groups!["value"]; 104 | const target = targetMatches[j].groups!["target"]; 105 | targets.push({ 106 | value, 107 | target: new Label(target), 108 | }); 109 | 110 | this.addEdge(target); 111 | } 112 | 113 | this.instructions.push( 114 | new SwitchInstruction(value, new Label(defaultTarget), targets, extended_insn, initial_line_nb + 1) 115 | ); 116 | return [false, line_nb]; 117 | } 118 | 119 | const indirectBrMatch = insn.match(Regexp.indirectBr); 120 | if (indirectBrMatch !== null && indirectBrMatch.groups !== undefined) { 121 | let s = insn.substring(indirectBrMatch[0].length); 122 | while (s.indexOf("]") == -1) { 123 | line_nb += 1; 124 | s += lines[line_nb]; 125 | } 126 | 127 | const targetMatches = [...s.matchAll(Regexp.indirectBrLabel)]; 128 | 129 | for (let j = 1; j < targetMatches.length; ++j) { 130 | const target = targetMatches[j].groups!["target"]; 131 | this.addEdge(target); 132 | } 133 | 134 | this.instructions.push(new TerminatorInstruction("indirectbr", insn, line_nb + 1)); 135 | return [false, line_nb]; 136 | } 137 | 138 | const otherTerminatorMatch = insn.match(Regexp.otherTerminatorInstruction); 139 | if (otherTerminatorMatch !== null && otherTerminatorMatch.groups !== undefined) { 140 | this.instructions.push({ 141 | opcode: otherTerminatorMatch.groups["opcode"], 142 | content: insn, 143 | group: "Terminator", 144 | address: line_nb + 1, 145 | }); 146 | return [false, line_nb]; 147 | } 148 | 149 | this.instructions.push({ opcode: "", content: insn, group: "Other", address: line_nb + 1 }); 150 | 151 | return [false, line_nb]; 152 | } 153 | } 154 | 155 | export interface Instruction { 156 | opcode: string; 157 | content: string; 158 | group: "Terminator" | "Other"; 159 | address: number; 160 | } 161 | 162 | export class TerminatorInstruction implements Instruction { 163 | readonly group = "Terminator"; 164 | 165 | constructor( 166 | public opcode: 167 | | "ret" 168 | | "br" 169 | | "switch" 170 | | "invoke" 171 | | "indirectbr" 172 | | "callbr" 173 | | "resume" 174 | | "catchswitch" 175 | | "catchret" 176 | | "cleanupret" 177 | | "unreachable", 178 | public content: string, 179 | public address: number 180 | ) {} 181 | } 182 | 183 | export class Label { 184 | constructor(public name: string) {} 185 | } 186 | 187 | export class BranchInstruction extends TerminatorInstruction { 188 | constructor(public conditional: boolean, public content: string, public address: number) { 189 | super("br", content, address); 190 | } 191 | } 192 | 193 | export class ConditionalBranchInstruction extends BranchInstruction { 194 | readonly conditional = true; 195 | 196 | constructor( 197 | public condition: string, 198 | public iftrue: Label, 199 | public iffalse: Label, 200 | public content: string, 201 | public address: number 202 | ) { 203 | super(true, content, address); 204 | } 205 | } 206 | 207 | export class UnconditionalBranchInstruction extends BranchInstruction { 208 | readonly conditional = false; 209 | 210 | constructor(public target: Label, public content: string, public address: number) { 211 | super(false, content, address); 212 | } 213 | } 214 | 215 | export class SwitchInstruction extends TerminatorInstruction { 216 | constructor( 217 | public value: string, 218 | public defaultTarget: Label, 219 | public targets: { value: string; target: Label }[], 220 | public content: string, 221 | public address: number 222 | ) { 223 | super("switch", content, address); 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | (?