├── .gitignore ├── .spread.yaml ├── .travis.yml ├── LICENSE ├── README.md ├── assembler ├── assembler.go ├── assembler_test.go └── gnu │ └── gnu.go ├── cmd └── asm2go │ ├── asm2go.go │ └── asm2go_test.go ├── snap └── snapcraft.yaml ├── testdata ├── addition_amd64 │ ├── add2.go │ ├── addition │ │ ├── addition_amd64.go │ │ └── addition_amd64.s │ └── src │ │ └── addition.s └── keccak │ ├── keccak │ ├── keccak_arm.go │ ├── keccak_arm.s │ ├── keccak_arm64.go │ └── keccak_arm64.s │ ├── keccakcheck.go │ ├── src │ ├── keccak_arm64_src.s │ └── keccak_arm_src.s │ └── task.yaml └── vendor └── vendor.json /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.o 3 | 4 | *.obj 5 | 6 | *.lis 7 | 8 | cover\.html 9 | cover\.out 10 | \.vscode/ 11 | 12 | \.spread-reuse*\.yaml 13 | 14 | vendor/*/ 15 | *.snap 16 | 17 | *.bz2 18 | -------------------------------------------------------------------------------- /.spread.yaml: -------------------------------------------------------------------------------- 1 | project: asm2go 2 | 3 | backends: 4 | lxd: 5 | systems: [ubuntu-18.04] 6 | 7 | suites: 8 | testdata/: 9 | summary: Keccak function on ARM/ARM64 example 10 | environment: 11 | GOARCH/arm: arm 12 | GOARM/arm: 7 13 | QEMU_EXEC/arm: qemu-arm-static 14 | kill-timeout: 30m 15 | prepare: | 16 | apt update 17 | apt install build-essential gcc-arm-linux-gnueabihf gcc-aarch64-linux-gnu qemu-user-static libvirt-bin wget -y -qq 18 | snap install go --classic --channel=1.10/stable 19 | export GOARCH=amd64 20 | export GOPATH=$(go env GOPATH) 21 | export PATH="$GOPATH/bin:$PATH" 22 | go get -u github.com/kardianos/govendor 23 | govendor sync 24 | govendor fetch +out 25 | go install ../../... 26 | restore: | 27 | snap remove go 28 | 29 | path: /root/go/src/github.com/anonymouse64/asm2go -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | go: 4 | - 1.10.x 5 | - tip 6 | 7 | go_import_path: github.com/anonymouse64/asm2go 8 | 9 | addons: 10 | apt: 11 | packages: 12 | - gcc-arm-linux-gnueabihf 13 | update: true 14 | 15 | install: 16 | - go get -u github.com/kardianos/govendor 17 | - govendor sync 18 | - govendor fetch +out 19 | 20 | script: 21 | - go test -race -coverprofile=coverage.txt -covermode=atomic ./... 22 | 23 | after_success: 24 | - bash <(curl -s https://codecov.io/bash) 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {{ project }} Copyright (C) {{ year }} {{ organization }} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # asm2go 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/anonymouse64/asm2go)](https://goreportcard.com/report/github.com/anonymouse64/asm2go) 4 | [![license](https://img.shields.io/badge/license-GPLv3-blue.svg)](LICENSE) 5 | [![Build Status](https://travis-ci.com/anonymouse64/asm2go.svg?branch=master)](https://travis-ci.com/anonymouse64/asm2go) 6 | [![codecov](https://codecov.io/gh/anonymouse64/asm2go/branch/master/graph/badge.svg)](https://codecov.io/gh/anonymouse64/asm2go) 7 | [![Snap Status](https://build.snapcraft.io/badge/anonymouse64/asm2go.svg)](https://build.snapcraft.io/user/anonymouse64/asm2go) 8 | [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fanonymouse64%2Fasm2go.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fanonymouse64%2Fasm2go?ref=badge_shield) 9 | 10 | 11 | This project aims to automatically generate working Golang assembly from native assembly and a golang declaration file, mainly used for implementing performance-intensive complex functions in assembly. 12 | 13 | ## Usage 14 | 15 | `asm2go` requires 2 files, a native assembly file that assembles properly using `as` (the GNU assembler), and a Golang declaration file that contains signatures for the functions implemented in assembly. These names must match exactly, if a symbol in the assembly doesn't have a corresponding go function declaration the generation fails (this restriction is somewhat arbitrary right now and may be lifted in the future). 16 | 17 | As to writing the actual assembly code to be translated, there are a few caveats. 18 | 19 | 0. Argument calling convention in Go places arguments on the stack, so you should write the assembly code to reference the stack for accessing arguments provided to functions. This may or may not match what is normally done, for example registers are sometimes used instead for passing arguments, but referencing the stack seems to be the best way to do this. 20 | 1. Data symbols are not yet supported. For example, defining an array of data with a symbol referring to the start of the array isn't supported. This is due to the fact that this tool translates the compiled object code into Golang assembly, at which point most data symbol references in the code have been translated into addresses, which means that simply including the array won't work as it will likely be repositioned in the final binary by go. This translation could be made to work, but it would be quite difficult. 21 | 2. The produced Golang assembly currently includes a RET at the end, which means that you shouldn't also include returning instructions (such as `bx lr` for ARM) as the Golang assembler will already insert this information. 22 | 3. Supported instructions are translated from native assembly into Golang's supported syntax. For example `mov r2 lr` in native ARM is translated to `MOVW R14, R2` in native plan9 assembly. Currently this is only supported for ARM, but it would be easy to support this on other architecture's using `golang.org/x/arch`. 23 | 4. No assembly function flags are currently supported. I eventually hope to solve this by annotating the function's declaration in the go source file. For example to insert the `NOPTR` flag, I think eventually a comment like `// asm2go:noptr` would be included above the function's declaration. Specifying the frame sizes should also probably be supported this way. It would be nice for `asm2go` to dynamically determine the size of the arguments, but this isn't currently implemented. 24 | 25 | Furthermore, the assembler must either be specified with the `-as` option, which can be a absolute path or a name on `$PATH`. In the same folder as the assembler must be the executables `strip` and `objdump` must also be available (note that assemblers specified with a prefix such as `arm-linux-gnueabihf-as` works properly; the prefix is resolved to find `arm-linux-gnueabihf-objdump`, etc - this allows cross compiling to work as expected). `strip` is used to remove debugging information from the compiled object file, and `objdump` is used to parse the actual hex instructions that are associated with instructions. 26 | 27 | Assembler options may be specified with `as-opts`, as many times as needed. For example to use the options `-march=armv7-a` and the option `-mfpu=neon-vfpv4`, you would invoke `asm2go` as follows: 28 | 29 | ``` 30 | asm2go -file somefile.s -gofile somefile.go -as-opts -march=armv7-a -as-opts -mfpu=neon-vfpv4 31 | ``` 32 | 33 | The output can either be a file specified with the `-out` option, or if not specified the output is dumped to stdout. 34 | 35 | #### Usage message 36 | 37 | ``` 38 | $ asm2go --help 39 | Usage of asm2go: 40 | -as string 41 | assembler to use (default "gas") 42 | -as-opts value 43 | Assembler options to use 44 | -file string 45 | file to assemble 46 | -gofile string 47 | go file with function declarations 48 | -out string 49 | output file to place data in (empty uses stdout) 50 | ``` 51 | 52 | ## Examples 53 | 54 | ### Keccak 55 | 56 | This example uses the assembly file from the KeccakCodePackage here : https://github.com/gvanas/KeccakCodePackage. Specifically, the ARMv7A implementation here: https://github.com/gvanas/KeccakCodePackage/blob/master/lib/low/KeccakP-1600/OptimizedAsmARM/KeccakP-1600-armv7a-le-neon-gcc.s was modified to only contain the KeccakF-1600 function (it was also modified to use some constants passed in as an argument instead of hard-coded into the assembly as a symbol). 57 | 58 | To generate the native go assembly from the native ARM assembly copied here run: 59 | 60 | $ git clone github.com/anonymouse64/asm2go 61 | $ cd asm2go 62 | $ go install 63 | $ export PATH="$GOPATH/bin:$PATH" 64 | $ cd tests/keccak_arm 65 | $ go generate 66 | $ go build keccak_check.go 67 | $ ./keccak_check 68 | Success! 69 | $ 70 | 71 | This uses the go:generate comment inside `keccak_check.go` 72 | 73 | The assembly generated uses the WORD feature of Plan9 assembly to translate all unsupported native instructions like such: 74 | 75 | ``` 76 | TEXT ·KeccakF1600(SB), 0, $0-8 77 | MOVW 0x4(R13), R0 // ldr r0 [sp #4] 78 | MOVW 0x8(R13), R1 // ldr r1 [sp #8] 79 | WORD $0xed2d8b10; // vpush {d8-d15} 80 | WORD $0xf42007dd; // vld1.64 {d0} [r0 :64]! 81 | WORD $0xf42027dd; // vld1.64 {d2} [r0 :64]! 82 | WORD $0xf42047dd; // vld1.64 {d4} [r0 :64]! 83 | ... 84 | ``` 85 | 86 | The only required parts are the ARM assembly file (`keccak.s`) and the go declaration file which declares the assembly-implemented function in go. The go file doesn't need anything extra, just the function declaration: 87 | 88 | ``` 89 | package keccak 90 | 91 | // go:noescape 92 | // This function is implemented in keccak.s 93 | func KeccakF1600(state *[25]uint64, constants *[24]uint64) 94 | 95 | ``` 96 | 97 | ## License 98 | 99 | This project is licensed under the GPLv3. See LICENSE file for full license. 100 | Copyright 2018 Canonical Ltd. -------------------------------------------------------------------------------- /assembler/assembler.go: -------------------------------------------------------------------------------- 1 | package assembler 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "io" 7 | 8 | "golang.org/x/arch/arm/armasm" 9 | "golang.org/x/arch/arm64/arm64asm" 10 | ) 11 | 12 | const ( 13 | unrecognizedInstr = `instruction %s not supported in plan9` 14 | unsupportedArch = `architecture %s not supported` 15 | ) 16 | 17 | // MachineInstruction represents an individual machine instruction as found in a binary 18 | // executable, etc. 19 | type MachineInstruction struct { 20 | // The raw assembly instruction as parsed from the output 21 | RawInstruction string 22 | // The instruction string without any comments 23 | InstructionString string 24 | // The bytes corresponding to the actual machine instruction assembled 25 | Bytes []byte 26 | // The endianness of the instruction bytes 27 | BytesEndianness binary.ByteOrder 28 | // The command (or opcode) of the instruction 29 | Command string 30 | // The arguments for the opcode - can be nil if command has no arguments 31 | Arguments []string 32 | // The line number this instruction was found on - note not currently implemented 33 | LineNumber uint64 34 | // Any comment found in the objdump output of the machine instruction - note that this won't correspond to 35 | // the comment included in original source (even if the original source was in assembly) 36 | // but rather any automatically generated comments such as the hex value of particular constants that were 37 | // translated from labels, i.e. "jmp MYLABEL" might get translated into "jmp #16 ; 0x10" if MYLABEL gets put at 38 | // address 0x10 39 | Comment string 40 | // The address of the instruction (i.e. the PC) 41 | Address uint64 42 | } 43 | 44 | // Assembler is a generic assembler implementation interface 45 | // i.e. this interface is implemented for GNU assembler (aka gas) with GnuAssembler, etc. 46 | // Currently only implemented for GNU assembler, but armcc + yasm are on the TODO list 47 | type Assembler interface { 48 | // AssembleToMachineCode takes an assembly source file, and assembler options and 49 | // returns an object code file and assembly listing file suitable for parsing in ProcessMachineCodeToInstructions 50 | AssembleToMachineCode(string, []string) (string, string, error) 51 | // ParseObjectSymbols will take in a file and return all symbols defined from that file 52 | ParseObjectSymbols(string) ([]Symbol, error) 53 | // ProcessMachineCodeToInstructions will take a map of symbol names -> symbols (determined from 54 | // processing ParseObjectSymbols return value) and should produce a map of those symbols to their 55 | // respective instructions 56 | ProcessMachineCodeToInstructions(string, map[string]Symbol) (map[string][]MachineInstruction, error) 57 | // Architecture returns the architecture that this compiler runs for 58 | Architecture() string 59 | } 60 | 61 | // Symbol is a entry in the symbol table of an object file 62 | type Symbol struct { 63 | // Global is whether this symbol has the "g" flag set 64 | Global bool 65 | // UniqueGlobal is whether this symbol has the "u" flag set 66 | UniqueGlobal bool 67 | // Local is whether this symbol has the "l" flag set 68 | Local bool 69 | // Weak is whether this symbol has the "w" flag set 70 | Weak bool 71 | // Constructor is whether this symbol has the "C" flag set 72 | Constructor bool 73 | // Warning is whether this symbol has the "W" flag set 74 | Warning bool 75 | // IndirectReference is whether this symbol has the "I" flag set 76 | IndirectReference bool 77 | // RelocationProcessingFunction is whether this symbol has the "i" flag set 78 | RelocationProcessingFunction bool 79 | // Debugging is whether this symbol has the "d" flag set 80 | Debugging bool 81 | // Dynamic is whether this symbol has the "D" flag set 82 | Dynamic bool 83 | // Function is whether this symbol has the "F" flag set 84 | Function bool 85 | // File is whether this symbol has the "f" flag set 86 | File bool 87 | // Object is whether this symbol has the "O" flag set 88 | Object bool 89 | // Name is the name of the symbol (5th column in `objdump -t output`) 90 | Name string 91 | // Section is what section the symbol is in (3rd column in `objdump -t output`) 92 | Section string 93 | // AlignmentSizeField is the 4th column in `objdump -t output` 94 | AlignmentSizeField uint64 95 | // ValueAddressField is the 1st column in `objdump -t output` 96 | ValueAddressField uint64 97 | } 98 | 99 | type invalidAssembler struct{} 100 | 101 | func (i invalidAssembler) AssembleToMachineCode(string, []string) (string, string, error) { 102 | return "", "", fmt.Errorf("unimplemented assembler") 103 | } 104 | 105 | func (i invalidAssembler) ParseObjectSymbols(string) ([]Symbol, error) { 106 | return nil, fmt.Errorf("unimplemented assembler") 107 | } 108 | 109 | func (i invalidAssembler) ProcessMachineCodeToInstructions(string, map[string]Symbol) (map[string][]MachineInstruction, error) { 110 | return nil, fmt.Errorf("unimplemented assembler") 111 | } 112 | 113 | func (i invalidAssembler) Architecture() string { 114 | return "invalid" 115 | } 116 | 117 | // InvalidAssembler returns an Assembler that doesn't work or do anything - useful for returning errors... 118 | func InvalidAssembler() Assembler { 119 | return invalidAssembler{} 120 | } 121 | 122 | func (instr MachineInstruction) errIsUnsupported(err error, arch string) bool { 123 | return err.Error() == fmt.Sprintf(unrecognizedInstr, instr.Command) || err.Error() == fmt.Sprintf(unsupportedArch, arch) 124 | } 125 | 126 | // WriteOutput formats an instruction for golang compatibility using unsupported opcode syntax. 127 | // See https://golang.org/doc/asm#unsupported_opcodes for more details 128 | // tryTranslate controls whether or not to attempt to translate this instruction to Golang syntax 129 | // and output that instead 130 | func (instr MachineInstruction) WriteOutput(arch string, w io.Writer, tryTranslate bool) error { 131 | // Write out the indentation for this instruction 132 | fmt.Fprintf(w, " ") 133 | 134 | // Switch on the method to use for outputting this instruction 135 | switch { 136 | case tryTranslate: 137 | err := instr.writePlan9Supported(arch, w) 138 | // if there was no error, exit the switch, otherwise fallback on 139 | // using unsupported opcode syntax 140 | if err == nil { 141 | break 142 | } else if !instr.errIsUnsupported(err, arch) { 143 | // error isn't an unsupported error, so return this and fail for this instruction 144 | return err 145 | } 146 | fallthrough 147 | default: 148 | instr.writePlan9Unsupported(arch, w) 149 | } 150 | 151 | // Now we add the actual instructions as a new column for each command/argument 152 | fmt.Fprintf(w, "// %s\t", instr.Command) 153 | for _, arg := range instr.Arguments { 154 | fmt.Fprintf(w, "%s\t", arg) 155 | } 156 | 157 | fmt.Fprintln(w) 158 | 159 | return nil 160 | 161 | } 162 | 163 | func reverseEndianness(byteSlice []byte) { 164 | for i, j := 0, len(byteSlice)-1; i < j; i, j = i+1, j-1 { 165 | byteSlice[i], byteSlice[j] = byteSlice[j], byteSlice[i] 166 | } 167 | } 168 | 169 | func (instr MachineInstruction) writePlan9Unsupported(arch string, w io.Writer) error { 170 | // First check whether the architecture specified is 32-bit or 64-bit 171 | // default to 64-bit 172 | maxBits := 64 173 | switch arch { 174 | case "amd64", 175 | "arm64": 176 | maxBits = 64 177 | case "arm": 178 | maxBits = 32 179 | } 180 | 181 | // Calculate the prefixes to use based on the number of bits 182 | var prefixes []string 183 | var lengths []int 184 | if maxBits == 64 && arch == "arm64" { 185 | // arm64 architecture doesn't support LONG's as 32-bit's instead 186 | // 32-bit instructions are WORD's 187 | prefixes = []string{ 188 | "QUAD $0x%02x%02x%02x%02x%02x%02x%02x%02x; \t", 189 | "WORD $0x%02x%02x%02x%02x; \t", 190 | "BYTE $0x%02x; \t", 191 | } 192 | lengths = []int{ 193 | 8, 194 | 4, 195 | 1, 196 | } 197 | } else if maxBits == 64 { 198 | // Other 64 bit architecture's have QUAD = 8 bytes, LONG = 4 bytes, WORD = 2 bytes, BYTE = 1 byte 199 | prefixes = []string{ 200 | "QUAD $0x%02x%02x%02x%02x%02x%02x%02x%02x; \t", 201 | "LONG $0x%02x%02x%02x%02x; \t", 202 | "WORD $0x%02x%02x; \t", 203 | "BYTE $0x%02x; \t", 204 | } 205 | lengths = []int{ 206 | 8, 207 | 4, 208 | 2, 209 | 1, 210 | } 211 | } else if maxBits == 32 { 212 | // TODO : check other 32-bit architecures to see what isa length they support... 213 | // To my knowledge, ARM, PowerPC, and MIPS all only support fixed width 32-bit instructions, 214 | // but others may allow/more 215 | // However, on 386, we also have LONG, but it's not clear from the plan 9 assembler reference what size 216 | // LONG is : https://9p.io/sys/doc/asm.html 217 | // So for now, just assume that every 32-bit architecture only allows WORD's and BYTE's 218 | prefixes = []string{ 219 | "WORD $0x%02x%02x%02x%02x; \t", 220 | "BYTE $0x%02x; \t", 221 | } 222 | lengths = []int{ 223 | 4, 224 | 1, 225 | } 226 | } else { 227 | // unsupported architecture, unsure what to do, so fail 228 | return fmt.Errorf("unsupported architecture: %s", arch) 229 | } 230 | 231 | // Iterate over the various lengths to insert, inserting as many of the bytes as we can 232 | // for each size 233 | opcodes := instr.Bytes 234 | for i, byteLen := range lengths { 235 | // While we have more opcodes than the current size, add that size 236 | for len(opcodes) >= byteLen { 237 | // This trick let's us use the variadic argument to Fprintf - we put all of 238 | // the opcodes into a []interface{}, rather than use the []byte directly 239 | // Note that using the []byte directly doesn't work because you can't cast a []type 240 | // into an []interface{} without looping over each element of the []type, casting each 241 | // element into an interface{} because an interface{} contains more than just the underlying 242 | // object 243 | args := make([]interface{}, byteLen) 244 | for i, opcode := range opcodes[:byteLen] { 245 | args[i] = opcode 246 | } 247 | // For some reason the plan9 assembler puts down data for 32 bit architectures in the order they appear 248 | // but for 64-bit architecture's swaps the endianness, so for 64-bit we need to reverse the endianness of the bytes 249 | // them into the array 250 | // TODO: apparently amd64 is the only architecture that needs it's bytes reversed? Should investigate... 251 | // arm64 doesn't need it's bytes reversed here 252 | if arch == "amd64" { 253 | for i, j := 0, len(args)-1; i < j; i, j = i+1, j-1 { 254 | args[i], args[j] = args[j], args[i] 255 | } 256 | } 257 | 258 | fmt.Fprintf(w, prefixes[i], args...) 259 | 260 | // Drop these bytes for next time 261 | opcodes = opcodes[byteLen:] 262 | } 263 | } 264 | 265 | return nil 266 | } 267 | 268 | func (instr MachineInstruction) writePlan9Supported(arch string, w io.Writer) error { 269 | switch arch { 270 | case "arm": 271 | // the arm decoder expects the bytes in little endian 272 | instrBytes := make([]byte, len(instr.Bytes)) 273 | copy(instrBytes, instr.Bytes) 274 | reverseEndianness(instrBytes) 275 | // to translate this machine instruction into plan9 assembly, first see if it can be decoded 276 | goInstr, err := armasm.Decode(instrBytes, armasm.ModeARM) 277 | if err != nil { 278 | // Then we couldn't decode this instruction and we should 279 | // use the WORD method 280 | return fmt.Errorf(unrecognizedInstr, instr.Command) 281 | } 282 | 283 | fmt.Fprintf(w, "%s \t", armasm.GoSyntax(goInstr, instr.Address, nil, nil)) 284 | case "arm64": 285 | // the arm decoder expects the bytes in little endian 286 | instrBytes := make([]byte, len(instr.Bytes)) 287 | copy(instrBytes, instr.Bytes) 288 | reverseEndianness(instrBytes) 289 | // to translate this machine instruction into plan9 assembly, first see if it can be decoded 290 | goInstr, err := arm64asm.Decode(instrBytes) 291 | if err != nil { 292 | // Then we couldn't decode this instruction and we should 293 | // use the WORD method 294 | return fmt.Errorf(unrecognizedInstr, instr.Command) 295 | } 296 | 297 | fmt.Fprintf(w, "%s \t", arm64asm.GoSyntax(goInstr, instr.Address, nil, nil)) 298 | default: 299 | return fmt.Errorf(unsupportedArch, arch) 300 | } 301 | 302 | return nil 303 | } 304 | -------------------------------------------------------------------------------- /assembler/assembler_test.go: -------------------------------------------------------------------------------- 1 | package assembler 2 | 3 | import ( 4 | "bytes" 5 | "encoding/hex" 6 | "regexp" 7 | "strings" 8 | "testing" 9 | "unicode" 10 | ) 11 | 12 | type instructionTest struct { 13 | instr MachineInstruction 14 | instrByteString string 15 | arch string 16 | tryPlan9 bool 17 | err error 18 | output string 19 | } 20 | 21 | func TestInstructionFormatHex(t *testing.T) { 22 | tables := []instructionTest{ 23 | // ARM tests 24 | // supported opcodes 25 | {MachineInstruction{ 26 | Command: "mov", 27 | Arguments: []string{"r2", "lr"}, 28 | }, 29 | "e1a0200e", 30 | "arm", 31 | false, 32 | nil, 33 | "WORD $0xe1a0200e; // mov r2 lr", 34 | }, 35 | {MachineInstruction{ 36 | Command: "mov", 37 | Arguments: []string{"r2", "lr"}, 38 | }, 39 | "e1a0200e", 40 | "arm", 41 | true, 42 | nil, 43 | "MOVW R14, R2 // mov r2 lr", 44 | }, 45 | // unsupported opcodes 46 | {MachineInstruction{ 47 | Command: "vld1.64", 48 | Arguments: []string{"{d0}", "[r0 :64]! "}, 49 | }, 50 | "f42007dd", 51 | "arm", 52 | true, 53 | nil, 54 | "WORD $0xf42007dd; // vld1.64 {d0} [r0 :64]!", 55 | }, 56 | {MachineInstruction{ 57 | Command: "vld1.64", 58 | Arguments: []string{"{d0}", "[r0 :64]! "}, 59 | }, 60 | "f42007dd", 61 | "arm", 62 | false, 63 | nil, 64 | "WORD $0xf42007dd; // vld1.64 {d0} [r0 :64]!", 65 | }, 66 | 67 | // ARM64 tests 68 | {MachineInstruction{ 69 | Command: "ldr", 70 | Arguments: []string{"x0", "[sp", "#8]"}, 71 | }, 72 | "f94007e0", 73 | "arm64", 74 | false, 75 | nil, 76 | "WORD $0xf94007e0; // ldr x0 [sp #8]", 77 | }, 78 | {MachineInstruction{ 79 | Command: "ldr", 80 | Arguments: []string{"x0", "[sp", "#8]"}, 81 | }, 82 | "f94007e0", 83 | "arm64", 84 | true, 85 | nil, 86 | "MOVD 8(RSP), R0 // ldr x0 [sp #8]", 87 | }, 88 | } 89 | 90 | // Parse all of the hex strings into the actual byte arrays 91 | for i := range tables { 92 | instrBytes, err := hex.DecodeString(tables[i].instrByteString) 93 | if err != nil { 94 | t.Errorf("Failed to parse hex string for table %d : %s", i, tables[i].instrByteString) 95 | } 96 | tables[i].instr.Bytes = instrBytes 97 | } 98 | 99 | for _, table := range tables { 100 | // make a buffer for the tabwriter 101 | var buf bytes.Buffer 102 | err := table.instr.WriteOutput(table.arch, &buf, table.tryPlan9) 103 | tabOutputString := adjustWhitespace(buf.String()) 104 | if err != table.err || tabOutputString != table.output { 105 | t.Errorf("Unable to make format instruction of (instr=%v, arch=%s, tryPlan9=%t), got: (err=%v,\noutput=%s\n) want: (err=%v,\noutput=%s\n).", table.instr, table.arch, table.tryPlan9, err, tabOutputString, table.err, table.output) 106 | } 107 | } 108 | } 109 | 110 | // adjustWhitespace replaces any sequence of white space with a single white space in the string 111 | // this simplifies comparing strings that will have formatting in them, etc. 112 | // code from : https://stackoverflow.com/questions/37290693/how-to-remove-redundant-spaces-whitespace-from-a-string-in-golang 113 | func adjustWhitespace(s string) string { 114 | // This regex replaces all whitespace inside a string (i.e. not at the start and the end) with a single one 115 | innerReplace := regexp.MustCompile(`[\s\p{Zs}]{2,}`).ReplaceAllString(s, " ") 116 | // This deletes all starting/trailing whitespace, and also replaces all whitespace characters with a single space 117 | // this is because the above regex doesn't properly handle cases with just a single tab character, etc. 118 | return strings.TrimSpace(strings.Map(func(r rune) rune { 119 | if unicode.IsSpace(r) { 120 | return ' ' 121 | } 122 | return r 123 | }, innerReplace)) 124 | } 125 | -------------------------------------------------------------------------------- /assembler/gnu/gnu.go: -------------------------------------------------------------------------------- 1 | package gnu 2 | 3 | import ( 4 | "encoding/binary" 5 | "encoding/hex" 6 | "fmt" 7 | "os" 8 | "os/exec" 9 | "path/filepath" 10 | "regexp" 11 | "strconv" 12 | "strings" 13 | "unicode" 14 | 15 | "github.com/anonymouse64/asm2go/assembler" 16 | ) 17 | 18 | // GnuAssembler implements Assembler interface and works with gnu "as" (aka "gas") assembler 19 | type GnuAssembler struct { 20 | // The assembler executable itself - this should always be an absolute path 21 | AsExecutable string 22 | // The architecture to compile for 23 | Arch string 24 | // for cross-compilers such as arm-linux-gnueabihf-as, we can find other tools (such as objdump) automatically 25 | // by looking in the same folder as asExecutable and prepending the prefix to whatever tool we are looking 26 | // in the example for arm-linux-gnueabihf-as, prefix will be "arm-linux-gnueabihi-" 27 | Prefix string 28 | // the folder where tools such as gcc, as, objdump, strip etc. should all be found 29 | // this should always be equal to filepath.Split(g.asExecutable) 30 | BinToolsFolder string 31 | } 32 | 33 | func (g GnuAssembler) toolExecutable(name string) string { 34 | return filepath.Join(g.BinToolsFolder, g.Prefix+name) 35 | } 36 | 37 | func (g GnuAssembler) objdump() string { 38 | return g.toolExecutable("objdump") 39 | } 40 | 41 | // Architecture returns the architecture of the this GNU assembler 42 | func (g GnuAssembler) Architecture() string { 43 | return g.Arch 44 | } 45 | 46 | // AssembleToMachineCode takes an assembly file with options and returns a corresponding compiled object file, and a 47 | // assembly listing file 48 | func (g GnuAssembler) AssembleToMachineCode(file string, asOpts []string) (string, string, error) { 49 | cwd, err := os.Getwd() 50 | if err != nil { 51 | return "", "", err 52 | } 53 | 54 | // Get the filenames to use for this assembly 55 | _, fileBaseName := filepath.Split(file) 56 | lisFile := filepath.Join(cwd, "asm2go-"+fileBaseName+".lis") 57 | objFile := filepath.Join(cwd, "asm2go-"+fileBaseName+".obj") 58 | 59 | args := []string{ 60 | "-o", 61 | objFile, 62 | fmt.Sprintf("-aln=%s", lisFile), 63 | file, 64 | } 65 | 66 | // Add any additional assembler options that might be necessary 67 | args = append(args, asOpts...) 68 | 69 | // Run the assembler to compile the file into object code 70 | asCmd := exec.Command(g.AsExecutable, args...) 71 | cmb, err := asCmd.CombinedOutput() 72 | if err != nil { 73 | return "", "", fmt.Errorf("error assembling (%v) : \n%s", err, string(cmb[:])) 74 | } 75 | 76 | // Now strip all debug information from the file, which probably isn't present, but if it is 77 | // it will mess up the parsing of the assembly source alongside the instruction bytes 78 | stripCmd := exec.Command(g.toolExecutable("strip"), "--strip-debug", objFile) 79 | stripCmb, err := stripCmd.CombinedOutput() 80 | if err != nil { 81 | return "", "", fmt.Errorf("error stripping debug info from object file (%v) : \n%s", err, string(stripCmb[:])) 82 | } 83 | 84 | return objFile, lisFile, nil 85 | } 86 | 87 | // ParseObjectSymbols takes in an object file and returns a list of all symbols from that object file 88 | func (g GnuAssembler) ParseObjectSymbols(objectFile string) ([]assembler.Symbol, error) { 89 | // To get all the object symbols from the object file, we use objdump with the -t option to display symbol names 90 | // and the C option demangles C++ names 91 | cmd := exec.Command(g.objdump(), "-t", "-C", objectFile) 92 | cmb, err := cmd.CombinedOutput() 93 | if err != nil { 94 | return nil, fmt.Errorf("error processing object file %s (%v) : \n%s", objectFile, err, string(cmb[:])) 95 | } 96 | strOutput := string(cmb[:]) 97 | 98 | // Find the first occurrence of "SYMBOL TABLE:" 99 | symbolTableStart := strings.Index(strOutput, "SYMBOL TABLE:") 100 | if symbolTableStart == -1 { 101 | return nil, fmt.Errorf("error processing objdump output: %v", cmb) 102 | } 103 | 104 | // Split everything by newlines and remove the first line, which is "SYMBOL TABLE:" 105 | tableRows := strings.Split(strOutput[symbolTableStart:], "\n") 106 | if len(tableRows) < 2 { 107 | return nil, fmt.Errorf("error processing objdump output: %v", cmb) 108 | } 109 | tableRows = tableRows[1:] 110 | 111 | // Now actually process all of the rows into Symbol's 112 | return processObjdumpTable(tableRows) 113 | } 114 | 115 | func deleteSpace(r rune) rune { 116 | if unicode.IsSpace(r) { 117 | return -1 118 | } 119 | return r 120 | } 121 | 122 | // This regex matches the hex address of an instruction, the binary of the instruction itself, and then the corresponding instruction 123 | // as 3 subgroups 124 | var instructionRegex = regexp.MustCompile(`(?m)^(?:\s*)([0-9a-f]+):(?:\s*)([0-9a-f ]+)\t(.+)$`) 125 | 126 | // This regex matches an opcode of letters, numbers and the ".", and all possible arguments as 2 subgroups 127 | var opcodeArgsRegex = regexp.MustCompile(`(?m)(^[a-zA-z0-9.]+)(?:\s*)(.*)$`) 128 | 129 | // This regex matches the end of a set of instructions associated with a symbol 130 | // a more readable version of this regex would be simply a check for the next line that is "\t..." 131 | // or the empty string after calling strings.TrimSpace 132 | var symbolEndRegex = regexp.MustCompile(`(?m)(^((\t\.\.\.)|[ \t]*)$)|(^$)`) 133 | 134 | // ProcessMachineCodeToInstructions takes in an object file and a map of symbol names -> Symbol that are to be processed 135 | // and returns a map of symbol name -> machine instructions corresponding to that symbol 136 | func (g GnuAssembler) ProcessMachineCodeToInstructions(objectFile string, syms map[string]assembler.Symbol) (map[string][]assembler.MachineInstruction, error) { 137 | // First, we use objdump on the object file to get a listing of the disassembled source 138 | cmd := exec.Command(g.objdump(), "-S", "-C", "-w", objectFile) 139 | cmb, err := cmd.CombinedOutput() 140 | if err != nil { 141 | return nil, fmt.Errorf("error processing object file %s (%v) : \n%s", objectFile, err, string(cmb[:])) 142 | } 143 | lines := strings.Split(string(cmb[:]), "\n") 144 | 145 | // With the source file, we need to find the first line in the output that starts with "FFFFFFF :" 146 | // (FFFFFFF being some hex address) as that is the start of the disassembly for the specified symbols 147 | // then find the end of the instructions for that symbol identified by either the first blank line after the start 148 | // oy by "\t..." which is displayed for padding 0's that may be added to the end of the symbol's instructions 149 | symInstrStrings := make(map[string][]string) 150 | for sym := range syms { 151 | var start int 152 | var end int 153 | // We have to generate this regex each time, as we include the name of the symbol in the regex 154 | symbolStartRegex := regexp.MustCompile(fmt.Sprintf(`(?m)^[0-9a-f]+ <%s>:`, sym)) 155 | 156 | for index, line := range lines { 157 | loc := symbolStartRegex.FindStringIndex(line) 158 | if len(loc) == 2 { 159 | // found the start, now look for the end 160 | start = index 161 | for index2, line := range lines[index:] { 162 | loc := symbolEndRegex.FindStringIndex(line) 163 | if len(loc) == 2 { 164 | // the ending isn't just index2, it's index2 + the length of the start 165 | end = index2 + start 166 | break 167 | } 168 | } 169 | break 170 | } 171 | } 172 | // the range starts at start+1 to drop the "FFFFFFF :"" 173 | symInstrStrings[sym] = lines[start+1 : end] 174 | } 175 | 176 | // Now that we have all the instruction lines, we need to parse each line into a MachineInstruction 177 | symMachInstrs := make(map[string][]assembler.MachineInstruction) 178 | for sym, instrStrings := range symInstrStrings { 179 | // Loop over each instruction, parsing it into a MachineInstruction 180 | for _, instrString := range instrStrings { 181 | for _, instMatches := range instructionRegex.FindAllStringSubmatch(instrString, -1) { 182 | // In the second group delete all whitespace to join all hex bytes together into a single string 183 | // Then we decode it into an actual byte slice 184 | decodedBytes, err := hex.DecodeString(strings.Map(deleteSpace, instMatches[2])) 185 | if err != nil { 186 | return nil, err 187 | } 188 | 189 | // The RawInstruction occurs in the 3rd element of match and may have a 190 | // comment after it, usually automatically generated for symbols that have been resolved to a hex address 191 | // so we split it by the ";" which is the comment character, then we can split the instruction itself 192 | // into opcodes / arguments 193 | var commentString string 194 | rawInstructions := strings.SplitN(instMatches[3], ";", 2) 195 | if len(rawInstructions) == 1 { 196 | commentString = "" 197 | } else { 198 | commentString = rawInstructions[1] 199 | } 200 | 201 | // Now find the instruction and the opcodes using the regex which reports the opcode 202 | // as the first subgroup and all arguments (if any) as the second group which will always exist 203 | // but sometimes may be the empty string 204 | opcodeMatches := opcodeArgsRegex.FindAllStringSubmatch(rawInstructions[0], -1) 205 | if len(opcodeMatches) == 0 { 206 | return nil, fmt.Errorf("error: invalid instruction format: %s", instrString) 207 | } 208 | 209 | // Split the arguments by a comma and trim off all whitespace 210 | instrArgs := strings.Split(opcodeMatches[0][2], ",") 211 | formattedArgs := make([]string, len(instrArgs)) 212 | for index, instrArg := range instrArgs { 213 | formattedArgs[index] = strings.TrimSpace(instrArg) 214 | } 215 | 216 | // Parse the address from the instMatches 217 | address, err := strconv.ParseUint(instMatches[1], 16, 64) 218 | if err != nil { 219 | return nil, err 220 | } 221 | 222 | // Finally build up the instruction and add it into the map 223 | symMachInstrs[sym] = append(symMachInstrs[sym], assembler.MachineInstruction{ 224 | Address: address, 225 | Bytes: decodedBytes, 226 | BytesEndianness: binary.LittleEndian, 227 | RawInstruction: instMatches[3], 228 | InstructionString: rawInstructions[0], 229 | Comment: strings.TrimSpace(commentString), 230 | Command: opcodeMatches[0][1], 231 | Arguments: formattedArgs, 232 | }) 233 | } 234 | } 235 | } 236 | 237 | return symMachInstrs, nil 238 | } 239 | 240 | func processObjdumpTable(tableRows []string) ([]assembler.Symbol, error) { 241 | var symbols []assembler.Symbol 242 | var err error 243 | for _, line := range tableRows { 244 | trimmedLine := strings.TrimSpace(line) 245 | if trimmedLine == "" { 246 | continue 247 | } 248 | var sym assembler.Symbol 249 | // First handle the symbol value / address 250 | out := strings.SplitN(trimmedLine, " ", 2) 251 | if len(out) < 2 { 252 | return nil, fmt.Errorf("error processing objdump row (line is incorrectly formatted) : %s", line) 253 | } 254 | 255 | sym.ValueAddressField, err = strconv.ParseUint(out[0], 16, 64) 256 | if err != nil { 257 | return nil, err 258 | } 259 | 260 | // Now handle the flags string, which will always be length of 7 char's 261 | restLine := out[1] 262 | if len(restLine) < 8 { 263 | return nil, fmt.Errorf("error processing objdump row (line is missing flag column) : %s", line) 264 | } 265 | err = parseFlagString(&sym, restLine[:7]) 266 | if err != nil { 267 | return nil, err 268 | } 269 | 270 | // Drop the flag string from the row and process the rest of the line as the section, alignment/size field and the name 271 | // Note that the separator between the section and the alignment/size field is a tab, while everywhere else is a space 272 | // hence the duplicated strings.Split 273 | cols := strings.Split(restLine[8:], "\t") 274 | if len(cols) < 2 { 275 | return nil, fmt.Errorf("error processing objdump row (line is too short) : %s", line) 276 | } 277 | cols = append([]string{cols[0]}, strings.SplitN(cols[1], " ", 2)...) 278 | if len(cols) < 3 { 279 | return nil, fmt.Errorf("error processing objdump row (line is too short) : %s", line) 280 | } 281 | sym.Section = cols[0] 282 | sym.AlignmentSizeField, err = strconv.ParseUint(cols[1], 16, 64) 283 | if err != nil { 284 | return nil, err 285 | } 286 | sym.Name = cols[2] 287 | 288 | symbols = append(symbols, sym) 289 | } 290 | 291 | return symbols, nil 292 | } 293 | 294 | // parseFlagString works on the 2nd column of `objdump -t` 295 | // documentation on this column used from here : http://manpages.ubuntu.com/manpages/xenial/en/man1/objdump.1.html 296 | func parseFlagString(sym *assembler.Symbol, flagString string) error { 297 | if sym == nil || len(flagString) == 0 { 298 | return fmt.Errorf("invalid arguments : sym=%+v, flagString=%+v ", sym, flagString) 299 | } 300 | switch flagString[0] { 301 | case 'l': 302 | sym.Local = true 303 | case 'g': 304 | sym.Global = true 305 | case 'u': 306 | sym.UniqueGlobal = true 307 | case '!': 308 | sym.Global = true 309 | sym.Local = true 310 | case ' ': 311 | break 312 | default: 313 | return fmt.Errorf("invalid flag at position 0 : %c", flagString[0]) 314 | } 315 | 316 | switch flagString[1] { 317 | case 'w': 318 | sym.Weak = true 319 | case ' ': 320 | break 321 | default: 322 | return fmt.Errorf("invalid flag at position 1 : %c", flagString[1]) 323 | } 324 | 325 | switch flagString[2] { 326 | case 'C': 327 | sym.Constructor = true 328 | case ' ': 329 | break 330 | default: 331 | return fmt.Errorf("invalid flag at position 2 : %c", flagString[2]) 332 | } 333 | 334 | switch flagString[3] { 335 | case 'W': 336 | sym.Warning = true 337 | case ' ': 338 | break 339 | default: 340 | return fmt.Errorf("invalid flag at position 3 : %c", flagString[3]) 341 | } 342 | 343 | switch flagString[4] { 344 | case 'I': 345 | sym.IndirectReference = true 346 | case 'i': 347 | sym.RelocationProcessingFunction = true 348 | case ' ': 349 | break 350 | default: 351 | return fmt.Errorf("invalid flag at position 4 : %c", flagString[4]) 352 | } 353 | 354 | switch flagString[5] { 355 | case 'd': 356 | sym.Debugging = true 357 | case 'D': 358 | sym.Dynamic = true 359 | case ' ': 360 | break 361 | default: 362 | return fmt.Errorf("invalid flag at position 5 : %c", flagString[5]) 363 | } 364 | 365 | switch flagString[6] { 366 | case 'F': 367 | sym.Function = true 368 | case 'f': 369 | sym.File = true 370 | case 'O': 371 | sym.Object = true 372 | case ' ': 373 | break 374 | default: 375 | return fmt.Errorf("invalid flag at position 6 : %c", flagString[6]) 376 | } 377 | 378 | return nil 379 | } 380 | -------------------------------------------------------------------------------- /cmd/asm2go/asm2go.go: -------------------------------------------------------------------------------- 1 | // asm2go - a utility for automatically generating golang assembly wrappers from complete native assembly 2 | // functions 3 | 4 | package main 5 | 6 | import ( 7 | "bufio" 8 | "flag" 9 | "fmt" 10 | "go/ast" 11 | "go/parser" 12 | "go/token" 13 | "io" 14 | "log" 15 | "os" 16 | "os/exec" 17 | "path/filepath" 18 | "reflect" 19 | "runtime" 20 | "strings" 21 | "text/tabwriter" 22 | 23 | "github.com/anonymouse64/asm2go/assembler" 24 | "github.com/anonymouse64/asm2go/assembler/gnu" 25 | ) 26 | 27 | type arrayFlags []string 28 | 29 | func (i *arrayFlags) String() string { 30 | return "" 31 | } 32 | 33 | func (i *arrayFlags) Set(value string) error { 34 | *i = append(*i, value) 35 | return nil 36 | } 37 | 38 | var assemblerOptions arrayFlags 39 | 40 | // FunctionDeclaration represents a function declaration as found in a go source file 41 | // It is used primarily to parse information from the go declaration for an assembly function 42 | // and then use that information to fill in the information needed in the plan9 assembly function 43 | // declaration 44 | type FunctionDeclaration struct { 45 | // The name of the function 46 | Name string 47 | // The names of each of the arguments 48 | ArgumentNames []string 49 | // The type of each argument as a reflect.Type, because that's easier to work with than the ast types 50 | ArgumentTypes []reflect.Type 51 | // The size of each argument in bytes - note that if the input is a static array of a fixed size then this count 52 | // will be the size of each element * number of elements, but if it is a slice, then this will just be 3 int64's for 53 | // the start of the slice, the length and the capacity of the slice 54 | ArgumentSizes []uintptr 55 | ResultNames []string 56 | ResultTypes []reflect.Type 57 | ResultSizes []uintptr 58 | SignatureString string 59 | DocComments string 60 | } 61 | 62 | // makeAssembler uses the user-specified assemblerName + assemblerFile to fill in details about the assembler 63 | // to use for assembling the program 64 | func makeAssembler(assemblerName string, assemblerFile string) (assembler.Assembler, error) { 65 | // First see if we have the name of this assembler, in which case we can just try to find a corresponding assembler file 66 | var err error 67 | var assemblerExecName string 68 | _, assemblerExec := filepath.Split(assemblerFile) 69 | arch := runtime.GOARCH 70 | switch assemblerName { 71 | case "": 72 | // We don't have the name, so look in the file, which should be an absolute file 73 | switch { 74 | case strings.Contains(assemblerFile, "yasm"): 75 | // TODO: implement yasm support 76 | return assembler.InvalidAssembler(), fmt.Errorf("%s is not supported yet", assemblerFile) 77 | case assemblerExec == "as": 78 | // native "as" treat as gas 79 | fallthrough 80 | case strings.Contains(assemblerFile, "gcc") || strings.Contains(assemblerFile, "gnu"): 81 | // Determine the prefix for this assembler - make sure that the assembler ends in "as" 82 | binToolsFolder, prefix := filepath.Split(assemblerFile) 83 | if strings.HasSuffix(assemblerFile, "as") { 84 | // Drop the last 2 characters and use that as the prefix 85 | prefix = prefix[:len(prefix)-2] 86 | } else { 87 | prefix = "" 88 | } 89 | // Use gas assembler, check what architecture 90 | if strings.Contains(assemblerFile, "arm") { 91 | return gnu.GnuAssembler{ 92 | AsExecutable: assemblerFile, 93 | Arch: "arm", 94 | Prefix: prefix, 95 | BinToolsFolder: binToolsFolder, 96 | }, nil 97 | } else if strings.Contains(assemblerFile, "aarch64") { 98 | return gnu.GnuAssembler{ 99 | AsExecutable: assemblerFile, 100 | Arch: "arm64", 101 | Prefix: prefix, 102 | BinToolsFolder: binToolsFolder, 103 | }, nil 104 | } 105 | return gnu.GnuAssembler{ 106 | AsExecutable: assemblerFile, 107 | Arch: arch, 108 | Prefix: prefix, 109 | BinToolsFolder: binToolsFolder, 110 | }, nil 111 | case strings.Contains(assemblerFile, "armcc"): 112 | // TODO: implement armcc 113 | fallthrough 114 | default: 115 | return assembler.InvalidAssembler(), fmt.Errorf("%s is not supported yet", assemblerFile) 116 | } 117 | case "arm-linux-gnueabihf-as": 118 | arch = "arm" 119 | assemblerExecName = "arm-linux-gnueabihf-as" 120 | fallthrough 121 | case "gas": 122 | if assemblerExecName == "" { 123 | assemblerExecName = "as" 124 | } 125 | var executable string 126 | // If the file path wasn't specified look for it 127 | if assemblerFile == "" { 128 | executable, err = exec.LookPath(assemblerExecName) 129 | if err != nil { 130 | return assembler.InvalidAssembler(), err 131 | } 132 | } else { 133 | executable = assemblerFile 134 | } 135 | binToolsFolder, prefix := filepath.Split(executable) 136 | prefix = prefix[:len(prefix)-2] 137 | return gnu.GnuAssembler{ 138 | AsExecutable: executable, 139 | Arch: arch, 140 | Prefix: prefix, 141 | BinToolsFolder: binToolsFolder, 142 | }, nil 143 | default: 144 | return assembler.InvalidAssembler(), fmt.Errorf("%s is not supported yet", assemblerName) 145 | } 146 | } 147 | 148 | // getStringFromFilePosition gets the associated string from a file given a start and end position 149 | func getStringFromFilePosition(fset *token.FileSet, start, end token.Pos) (string, error) { 150 | // Check that the start comes before the end 151 | if start > end { 152 | return "", fmt.Errorf("error: invalid positions : %v -> %v", start, end) 153 | } 154 | 155 | // Make sure that the two positions are for the same file 156 | startFile := fset.File(start) 157 | endFile := fset.File(end) 158 | 159 | if endFile == nil || startFile == nil { 160 | return "", fmt.Errorf("error: start or end positions are nil") 161 | } 162 | 163 | if startFile != endFile { 164 | return "", fmt.Errorf("error: start + end are not in the same file (start=%#v, end=%#v)", startFile, endFile) 165 | } 166 | 167 | absoluteStart := fset.Position(start) 168 | absoluteEnd := fset.Position(end) 169 | 170 | // Check that the file exists 171 | if _, err := os.Stat(absoluteStart.Filename); err != nil { 172 | return "", err 173 | } 174 | 175 | // Open the file for reading 176 | f, err := os.Open(absoluteStart.Filename) 177 | if err != nil { 178 | log.Fatal(err) 179 | } 180 | defer f.Close() 181 | scanner := bufio.NewScanner(f) 182 | 183 | // Note: line numbers from token.Position is 1-indexed 184 | lineNumber := 1 185 | 186 | // corner case where the start + end are on the same line 187 | if absoluteStart.Line == absoluteEnd.Line { 188 | // Scan up to the specifiied line number 189 | for lineNumber = 1; scanner.Scan() && lineNumber < absoluteStart.Line; lineNumber++ { 190 | } 191 | 192 | // Make sure we actually read the required number of lines, otherwise fail 193 | if lineNumber != absoluteStart.Line { 194 | fmt.Println(lineNumber) 195 | fmt.Println(absoluteStart.Line) 196 | return "", fmt.Errorf("error: line %d doesn't exist in file %s", absoluteStart.Line, absoluteStart.Filename) 197 | } 198 | // Otherwise we are on the desired line, so make sure that the end column is within this line 199 | line := scanner.Text() 200 | if absoluteEnd.Column-1 <= len(line) { 201 | return line[absoluteStart.Column-1 : absoluteEnd.Column-1], nil 202 | } else { 203 | // Line too short 204 | fmt.Println(absoluteStart.Column, absoluteEnd.Column, len(line), line) 205 | return "", fmt.Errorf("error: line %d of %s too short", lineNumber, absoluteStart.Filename) 206 | } 207 | } 208 | 209 | // General case - start + end on different lines 210 | // Start scanning up to the start line number 211 | var text string 212 | 213 | for ; scanner.Scan(); lineNumber++ { 214 | if lineNumber == absoluteStart.Line { 215 | // then we found the start - ensure that the column number for the start is within this line 216 | line := scanner.Text() 217 | if absoluteStart.Column <= len(line) { 218 | // Column number is 1-indexed so subtract 1 from it for the position in the string slice 219 | text = line[absoluteStart.Column-1:] 220 | break 221 | } else { 222 | return "", fmt.Errorf("error: line %d of %s too short", lineNumber, absoluteStart.Filename) 223 | } 224 | } 225 | } 226 | 227 | // Now scan up to the end line number, adding all text up to the end column 228 | for ; scanner.Scan(); lineNumber++ { 229 | if lineNumber == absoluteEnd.Line { 230 | // then we found the end - ensure that the column number for the start is within this line 231 | line := scanner.Text() 232 | if absoluteEnd.Column <= len(line) { 233 | // Column number is 1-indexed so subtract 1 from it for the position in the string slice 234 | text += line[absoluteStart.Column-1:] 235 | break 236 | } else { 237 | return "", fmt.Errorf("error: line %d of %s too short", lineNumber, absoluteStart.Filename) 238 | } 239 | } else { 240 | text += scanner.Text() 241 | } 242 | } 243 | 244 | return text, nil 245 | } 246 | 247 | // parseGoLangFileForFuncDecls will parse a golang source file looking for suitable 248 | // assembly implemented function declarations and return any found functions 249 | // the map is of the function name to the declaration struct 250 | func parseGoLangFileForFuncDecls(goSrc string) (map[string]FunctionDeclaration, error) { 251 | 252 | // Create an AST by parsing the go file 253 | fset := token.NewFileSet() 254 | // Ensure that we also parse comments into the file set 255 | f, err := parser.ParseFile(fset, goSrc, nil, parser.ParseComments) 256 | if err != nil { 257 | return nil, err 258 | } 259 | 260 | // Create an ast.CommentMap from the ast.File's comments. 261 | // This helps keeping the association between comments 262 | // and AST nodes. 263 | cmap := ast.NewCommentMap(fset, f, f.Comments) 264 | 265 | funcDecls := make(map[string]FunctionDeclaration) 266 | 267 | // Walk the AST and look for all FuncDecl's that don't have a body. 268 | ast.Inspect(f, func(n ast.Node) bool { 269 | switch function := n.(type) { 270 | case *ast.FuncDecl: 271 | // If the body of this function is nil, then it's an assembly implemented function we are interested in 272 | if function.Body == nil { 273 | decl := FunctionDeclaration{} 274 | decl.Name = function.Name.Name 275 | 276 | // TODO: this is largely unimplemented, due to the large number of 277 | // different cases that need to be handled for the args/results 278 | 279 | // Iterate over the function arguments to gather information on the function args 280 | for _, arg := range function.Type.Params.List { 281 | switch z := arg.Type.(type) { 282 | case *ast.ArrayType: 283 | if z.Len == nil { 284 | // arg is a slice 285 | return true 286 | } else { 287 | if _, ok := z.Len.(*ast.BasicLit); ok { 288 | switch elemType := z.Elt.(type) { 289 | case *ast.StructType: 290 | if elemType.Incomplete { 291 | // fmt.Printf("arg type is array of incomplete structs with fields %#v and length %#v\n", elemType.Fields, length.Value) 292 | } else { 293 | // fmt.Printf("arg type is array of type struct with %d fields and length %#v\n", len(elemType.Fields.List), length.Value) 294 | } 295 | return true 296 | case *ast.Ident: 297 | // fmt.Printf("arg type is array of type %#v and length %#v\n", elemType.Name, length.Value) 298 | return true 299 | } 300 | } else { 301 | // Some error with this function declaration - just move onto the next ast node 302 | return true 303 | } 304 | } 305 | case *ast.Ident: 306 | } 307 | } 308 | 309 | // Next do a similar check on the results of the function 310 | // Note that the Results can be nil : https://golang.org/pkg/go/ast/#FuncType 311 | if function.Type.Results != nil { 312 | for _, res := range function.Type.Results.List { 313 | // Switch on the type of result 314 | switch z := res.Type.(type) { 315 | case *ast.ArrayType: 316 | if z.Len == nil { 317 | // res is a slice 318 | return true 319 | } else { 320 | // result is an array of a specific length 321 | if _, ok := z.Len.(*ast.BasicLit); ok { 322 | switch elemType := z.Elt.(type) { 323 | case *ast.StructType: 324 | // Then this result is returning a list of structs 325 | // TODO: support returning array of structs 326 | if elemType.Incomplete { 327 | // fmt.Printf("arg type is array of incomplete structs with fields %#v and length %#v\n", elemType.Fields, length.Value) 328 | } else { 329 | // fmt.Printf("arg type is array of type struct with %d fields and length %#v\n", len(elemType.Fields.List), length.Value) 330 | } 331 | return true 332 | case *ast.Ident: 333 | // This result is returning a concrete type of array of - determine what kind of type the array is 334 | 335 | } 336 | } else { 337 | // Some error with this function declaration - just move onto the next ast node 338 | return true 339 | } 340 | } 341 | case *ast.Ident: 342 | } 343 | } 344 | } 345 | 346 | // To get associated documentation comments for this function, we don't use function.Doc, as that won't pick up comments that have 347 | // a newline separating the 348 | var funcComments string 349 | for _, comment := range cmap.Filter(function).Comments() { 350 | funcComments += comment.Text() 351 | } 352 | decl.DocComments = funcComments 353 | 354 | // Get the full signature of this function from the source file using the pos + end 355 | // note that this works because there is no body - so this entire declaration consists of just the 356 | // signature 357 | decl.SignatureString, err = getStringFromFilePosition(fset, function.Pos(), function.End()) 358 | if err != nil { 359 | fmt.Println(err) 360 | return true 361 | } 362 | 363 | // Put this function declaration into the map 364 | funcDecls[decl.Name] = decl 365 | } 366 | } 367 | // we want to walk the entire AST, so always return true here 368 | return true 369 | }) 370 | 371 | return funcDecls, nil 372 | } 373 | 374 | // generate Plan9Assembly takes in a go declaration file, the output file and a mapping of symbol names to the corresponding instructions 375 | // It generates the wrapper function text around the assembly code by parsing information from the assoociated golang function in 376 | // the declaration file. This means that the name of the golang function must match exactly the name of the symbols in the compiled object file 377 | // Additionally, argument information isn't parsed to do anything with the instructions itself, but is used to populate the go comment above 378 | // the function implementation itself. If a symbol is deemed "interesting" (see comments in main() for explicit explanation of this creiterion), 379 | // but doesn't have a corresponding golang function, then no such export comment is generated for it and that symbol/function is assumed to be 380 | // just available inside the assembly file 381 | func generatePlan9Assembly(goDeclarationFile, outputFile, arch string, syms map[string][]assembler.MachineInstruction) error { 382 | 383 | // First make sure the goDeclarationFile exists 384 | if goDeclarationFile == "" { 385 | return fmt.Errorf("error: gofile must be specified") 386 | } 387 | if _, err := os.Stat(goDeclarationFile); err != nil { 388 | // doesn't exist or can't be opened 389 | return err 390 | } 391 | 392 | // Now parse function declarations for the declaration file 393 | decls, err := parseGoLangFileForFuncDecls(goDeclarationFile) 394 | if err != nil { 395 | return err 396 | } 397 | 398 | // Setup the output mechanism - we use tabbed writing for prettier formatted assembly 399 | // If the outputFile is an empty string, we just print to stdout 400 | var output io.Writer 401 | if outputFile == "" { 402 | output = os.Stdout 403 | } else { 404 | f, err := os.Create(outputFile) 405 | if err != nil { 406 | return err 407 | } 408 | 409 | defer f.Close() 410 | output = f 411 | } 412 | w := tabwriter.NewWriter(output, 0, 0, 1, ' ', 0) 413 | 414 | // Add a header to the file generated to show what command generated this file and also 415 | // always include the textflag.h include file for stuff like NOSPLIT, NOPTR, etc. 416 | fmt.Fprintf(w, `// Generated by asm2go %s DO NOT EDIT 417 | #include "textflag.h" 418 | 419 | `, strings.Join(os.Args[1:], " ")) 420 | 421 | // For each symbol in the list, which should only be functions, other types aren't yet supported 422 | // add the assembly TEXT signature 423 | for sym, instrs := range syms { 424 | funcDecl, ok := decls[sym] 425 | if !ok { 426 | // Then this symbol doesn't have a corresponding go function that calls it, so we can just insert it into the file 427 | // as a basic TEXT with reported stack size of 0 and no flags 428 | // TODO implement... 429 | return fmt.Errorf("error: symbol %s not found in go file declaration : %s", sym, goDeclarationFile) 430 | } 431 | 432 | // Calculate the total number of bytes for the args + results 433 | var totalBytes uintptr 434 | for _, argBytes := range funcDecl.ArgumentSizes { 435 | totalBytes += argBytes 436 | } 437 | for _, resBytes := range funcDecl.ResultSizes { 438 | totalBytes += resBytes 439 | } 440 | 441 | // TODO: get the golang function signature and include it in the assembly signature comment 442 | 443 | // Format the function signature 444 | fmt.Fprintf(w, 445 | `%s 446 | TEXT ·%s(SB), %s, $%d-8 447 | `, 448 | "// "+funcDecl.SignatureString, 449 | sym, 450 | // TODO: handle flags here 451 | "0", 452 | totalBytes, 453 | ) 454 | 455 | // NOTE: for arm64, currently the disassembler doesn't sync with the assembler 456 | // and so we shouldn't try to translate supported op codes because the dissassembler 457 | // produces syntax that the assembler doesn't understand 458 | trySupportedTranslation := true 459 | if arch == "arm64" { 460 | trySupportedTranslation = false 461 | } 462 | 463 | // Now output all of the instructions for this symbol 464 | for _, instr := range instrs { 465 | err := instr.WriteOutput(arch, w, trySupportedTranslation) 466 | if err != nil { 467 | return err 468 | } 469 | } 470 | 471 | // Finally for this symbol append a RET to the end 472 | // this handles all returns in all architectures 473 | fmt.Fprintln(w, " RET") 474 | } 475 | 476 | // Flush all output 477 | w.Flush() 478 | 479 | return nil 480 | } 481 | 482 | func main() { 483 | // Setup flags 484 | flag.Var(&assemblerOptions, "as-opts", "Assembler options to use") 485 | assemblerOpt := flag.String("as", "gas", "assembler to use") 486 | fileOpt := flag.String("file", "", "file to assemble") 487 | goFileOpt := flag.String("gofile", "", "go file with function declarations") 488 | outputFile := flag.String("out", "", "output file to place data in (empty uses stdout)") 489 | flag.Parse() 490 | 491 | file := *fileOpt 492 | 493 | // Check if the file exists 494 | _, err := os.Stat(file) 495 | switch { 496 | case err != nil: 497 | fmt.Printf("error checking file: %v\n", err) 498 | os.Exit(1) 499 | } 500 | 501 | // Check the assembler option 502 | assemblerString := strings.ToLower(*assemblerOpt) 503 | assemblerOnPath, _ := exec.LookPath(assemblerString) 504 | 505 | var as assembler.Assembler 506 | // First handle named assemblers, then check if the assembler specified is a file 507 | if assemblerString == "gas" || assemblerString == "as" || assemblerString == "gcc" { 508 | as, err = makeAssembler("gas", "") 509 | } else if assemblerString == "yasm" { 510 | // TODO 511 | } else if assemblerString == "armcc" { 512 | // TODO 513 | } else if _, statErr := os.Stat(*assemblerOpt); statErr == nil { 514 | // assembler is a valid file path 515 | as, err = makeAssembler("", *assemblerOpt) 516 | } else if _, statErr := os.Stat(assemblerOnPath); statErr == nil { 517 | // assembler is a file that exists on the $PATH 518 | as, err = makeAssembler("", assemblerOnPath) 519 | } else { 520 | fmt.Printf("assembler %s not supported\n", *assemblerOpt) 521 | os.Exit(1) 522 | } 523 | if err != nil { 524 | fmt.Printf("error finding assembler: %v\n", err) 525 | os.Exit(1) 526 | } 527 | 528 | // Now compile to object file + assembly listing using the assembly options specified by 529 | // the user 530 | objectFile, _, err := as.AssembleToMachineCode(file, assemblerOptions) 531 | if err != nil { 532 | fmt.Println(err) 533 | os.Exit(1) 534 | } 535 | 536 | // Now parse the object file to get all the symbols 537 | syms, err := as.ParseObjectSymbols(objectFile) 538 | if err != nil { 539 | fmt.Println(err) 540 | os.Exit(1) 541 | } 542 | 543 | // Iterate through the symbols and find the "useful" ones 544 | // Note to future maintainer : these criterion were somehwat arbitrary chosen and 545 | // may need to be changed, but currently is just: 546 | // - Not a Debugging symbol 547 | // - Not a Warning symbol 548 | // - Not a File symbol 549 | // - Section is not "*UND*" (i.e. it's not in an undefined section, i.e. another object file) 550 | // - Section is not "*ABS*" (i.e. it is a symbol associated with a particular section) 551 | usefulSymbolMap := make(map[string]assembler.Symbol) 552 | var usefulSymbolNames []string 553 | for _, sym := range syms { 554 | if !sym.Debugging && !sym.Warning && !sym.File && sym.Section != "*UND*" && sym.Section != "*ABS*" { 555 | usefulSymbolNames = append(usefulSymbolNames, sym.Name) 556 | usefulSymbolMap[sym.Name] = sym 557 | } 558 | } 559 | 560 | // fmt.Printf("useful symbols are : %#v\n", pretty.Formatter(usefulSymbolNames)) 561 | 562 | symsToInstructions, err := as.ProcessMachineCodeToInstructions(objectFile, usefulSymbolMap) 563 | if err != nil { 564 | fmt.Println(err) 565 | os.Exit(1) 566 | } 567 | 568 | // fmt.Printf("symbols + instructions: %#v\n", pretty.Formatter(symsToInstructions)) 569 | 570 | // Now that we have a complete symbol -> instructions map we can begin generating go/plan9 assembly code for 571 | // all of the functions 572 | err = generatePlan9Assembly(*goFileOpt, *outputFile, as.Architecture(), symsToInstructions) 573 | if err != nil { 574 | fmt.Println(err) 575 | os.Exit(1) 576 | } 577 | } 578 | -------------------------------------------------------------------------------- /cmd/asm2go/asm2go_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os/exec" 5 | "path/filepath" 6 | "runtime" 7 | "testing" 8 | 9 | "github.com/anonymouse64/asm2go/assembler" 10 | "github.com/anonymouse64/asm2go/assembler/gnu" 11 | ) 12 | 13 | type assemblerTest struct { 14 | as assembler.Assembler 15 | err error 16 | name string 17 | file string 18 | } 19 | 20 | func TestMakeAssembler(t *testing.T) { 21 | // Make sure we can find as on this system 22 | gasExec, err := exec.LookPath("as") 23 | if err != nil { 24 | t.Errorf("gnu as not available on the system, failing : %v.", err) 25 | } 26 | t.Logf("testing with gnu as : %s\n", gasExec) 27 | gasExecFolder, _ := filepath.Split(gasExec) 28 | tables := []assemblerTest{ 29 | {gnu.GnuAssembler{ 30 | AsExecutable: gasExec, 31 | Arch: runtime.GOARCH, 32 | BinToolsFolder: gasExecFolder, 33 | Prefix: "", 34 | }, 35 | nil, 36 | "gas", 37 | "", 38 | }, 39 | {gnu.GnuAssembler{ 40 | AsExecutable: gasExec, 41 | Arch: runtime.GOARCH, 42 | BinToolsFolder: gasExecFolder, 43 | Prefix: "", 44 | }, 45 | nil, 46 | "", 47 | gasExec, 48 | }, 49 | } 50 | 51 | armGas, err := exec.LookPath("arm-linux-gnueabihf-as") 52 | if err != nil { 53 | t.Logf("arm gnu as not available on the system, not testing") 54 | } else { 55 | t.Logf("testing with arm gnu as : %s\n", armGas) 56 | armExecFolder, _ := filepath.Split(armGas) 57 | tables = append(tables, 58 | []assemblerTest{ 59 | {gnu.GnuAssembler{ 60 | AsExecutable: armGas, 61 | Arch: "arm", 62 | BinToolsFolder: armExecFolder, 63 | Prefix: "arm-linux-gnueabihf-", 64 | }, 65 | nil, 66 | "", 67 | armGas, 68 | }, 69 | {gnu.GnuAssembler{ 70 | AsExecutable: armGas, 71 | Arch: "arm", 72 | BinToolsFolder: armExecFolder, 73 | Prefix: "arm-linux-gnueabihf-", 74 | }, 75 | nil, 76 | "arm-linux-gnueabihf-as", 77 | "", 78 | }, 79 | }...) 80 | } 81 | 82 | for _, table := range tables { 83 | as, err := makeAssembler(table.name, table.file) 84 | if !compareAsGnuAssemblers(as, table.as) || err != table.err { 85 | t.Errorf("Unable to make assembler of (name=%s, file=%s), got: (as=%#v, err=%v) want: (as=%#v, err=%v).", table.name, table.file, as, err, table.as, table.err) 86 | } 87 | } 88 | } 89 | 90 | func compareAsGnuAssemblers(as assembler.Assembler, g assembler.Assembler) bool { 91 | // cast g to a GnuAssembler 92 | if g2, ok := g.(gnu.GnuAssembler); ok { 93 | // cast the assembler to a GnuAssembler 94 | if gnuAs, ok := as.(gnu.GnuAssembler); ok { 95 | // make sure the fields match 96 | return gnuAs.Arch == g2.Arch && gnuAs.AsExecutable == g2.AsExecutable && gnuAs.BinToolsFolder == g2.BinToolsFolder && gnuAs.Prefix == g2.Prefix 97 | } 98 | } 99 | // it's not a GnuAssembler, so return false 100 | return false 101 | } 102 | -------------------------------------------------------------------------------- /snap/snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: asm2go 2 | version: '0.1' 3 | summary: Translate native assembly functions into Plan9 syntax 4 | description: | 5 | asm2go translates native assembly functions into a Plan9 syntax format usable with Go, without needing Cgo style linking requirements. 6 | Included in the amd64 snap are cross-compilers for ARM and ARM64 so no cross-compilers have to be installed into the host system. 7 | The ARM and ARM64 snap only have native compilers available to them. 8 | 9 | grade: stable 10 | confinement: strict 11 | 12 | apps: 13 | asm2go: 14 | command: bin/asm2go 15 | 16 | parts: 17 | go: 18 | source-tag: go1.10.2 19 | source-depth: 1 20 | asm2go: 21 | go-importpath: github.com/anonymouse64/asm2go 22 | after: [go] 23 | plugin: go 24 | source: . 25 | stage-packages: 26 | - on amd64: [gcc-arm-linux-gnueabihf, gcc-aarch64-linux-gnu] 27 | - build-essential 28 | override-build: | 29 | export GOPATH=$(dirname $PWD)/go 30 | go get -u github.com/kardianos/govendor 31 | export PATH="$GOPATH/bin:$PATH" 32 | cd $GOPATH/src/github.com/anonymouse64/asm2go 33 | govendor sync 34 | mkdir -p $SNAPCRAFT_PART_INSTALL/bin 35 | go build -o $SNAPCRAFT_PART_INSTALL/bin/asm2go ./cmd/asm2go/asm2go.go 36 | -------------------------------------------------------------------------------- /testdata/addition_amd64/add2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //go:generate asm2go -file src/addition.s -gofile addition/addition_amd64.go -out addition/addition_amd64.s 4 | 5 | import ( 6 | "fmt" 7 | 8 | "github.com/anonymouse64/asm2go/tests/addition_amd64/addition" 9 | ) 10 | 11 | func main() { 12 | fmt.Println(addition.Add2(2, 2)) 13 | } 14 | -------------------------------------------------------------------------------- /testdata/addition_amd64/addition/addition_amd64.go: -------------------------------------------------------------------------------- 1 | package addition 2 | 3 | //go:noescape 4 | // Add2 returns the sum of two numbers 5 | // This function is implemented in addition.s 6 | func Add2(x, y int) int 7 | -------------------------------------------------------------------------------- /testdata/addition_amd64/addition/addition_amd64.s: -------------------------------------------------------------------------------- 1 | // Generated by asm2go -file src/addition.s -gofile addition/addition_amd64.go -out addition/addition_amd64.s DO NOT EDIT 2 | #include "textflag.h" 3 | 4 | // func Add2(x, y int) int 5 | TEXT ·Add2(SB), NOSPLIT, $0-8 6 | BYTE $0x55; // push %rbp 7 | WORD $0x8948; BYTE $0xe5; // mov %rsp %rbp 8 | WORD $0x7d89; BYTE $0xfc; // mov %edi -0x4(%rbp) 9 | WORD $0x7589; BYTE $0xf8; // mov %esi -0x8(%rbp) 10 | WORD $0x558b; BYTE $0xfc; // mov -0x4(%rbp) %edx 11 | WORD $0x458b; BYTE $0xf8; // mov -0x8(%rbp) %eax 12 | WORD $0xd001; // add %edx %eax 13 | BYTE $0x5d; // pop %rbp 14 | BYTE $0xc3; // retq 15 | -------------------------------------------------------------------------------- /testdata/addition_amd64/src/addition.s: -------------------------------------------------------------------------------- 1 | .file "addition.c" 2 | .text 3 | .globl Add2 4 | .type Add2, @function 5 | Add2: 6 | .LFB0: 7 | .cfi_startproc 8 | pushq %rbp 9 | .cfi_def_cfa_offset 16 10 | .cfi_offset 6, -16 11 | movq %rsp, %rbp 12 | .cfi_def_cfa_register 6 13 | movl %edi, -4(%rbp) 14 | movl %esi, -8(%rbp) 15 | movl -4(%rbp), %edx 16 | movl -8(%rbp), %eax 17 | addl %edx, %eax 18 | popq %rbp 19 | .cfi_def_cfa 7, 8 20 | ret 21 | .cfi_endproc 22 | .LFE0: 23 | .size Add2, .-Add2 24 | .ident "GCC: (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0" 25 | .section .note.GNU-stack,"",@progbits 26 | -------------------------------------------------------------------------------- /testdata/keccak/keccak/keccak_arm.go: -------------------------------------------------------------------------------- 1 | //+build: arm 2 | 3 | package keccak 4 | 5 | // go:noescape 6 | // KeccakF1600 permutes the state using the provided permutation constants 7 | // This function is implemented in keccak_arm.s 8 | func KeccakF1600(state *[25]uint64, constants *[24]uint64) 9 | -------------------------------------------------------------------------------- /testdata/keccak/keccak/keccak_arm64.go: -------------------------------------------------------------------------------- 1 | //+build: arm64 2 | 3 | package keccak 4 | 5 | // go:noescape 6 | // KeccakF1600 permutes the state using the provided permutation constants 7 | // This function is implemented in keccak_arm64.s 8 | func KeccakF1600(state *[25]uint64, constants *[24]uint64) 9 | -------------------------------------------------------------------------------- /testdata/keccak/keccakcheck.go: -------------------------------------------------------------------------------- 1 | // example keccak assembly function usage on arm 2 | 3 | // generate plan9 asm sources for arm 4 | //go:generate asm2go -as arm-linux-gnueabihf-as -file src/keccak_arm_src.s -gofile keccak/keccak_arm.go -out keccak/keccak_arm.s -as-opts -march=armv7-a -as-opts -mfpu=neon-vfpv4 5 | 6 | // generate plan9 asm sources for arm64 7 | //go:generate asm2go -as aarch64-linux-gnu-as -file src/keccak_arm64_src.s -gofile keccak/keccak_arm64.go -out keccak/keccak_arm64.s 8 | 9 | package main 10 | 11 | import ( 12 | "fmt" 13 | "os" 14 | 15 | "github.com/anonymouse64/asm2go/testdata/keccak/keccak" 16 | ) 17 | 18 | // rc stores the round constants for use in the ι step. 19 | var rc = [24]uint64{ 20 | 0x0000000000000001, 21 | 0x0000000000008082, 22 | 0x800000000000808A, 23 | 0x8000000080008000, 24 | 0x000000000000808B, 25 | 0x0000000080000001, 26 | 0x8000000080008081, 27 | 0x8000000000008009, 28 | 0x000000000000008A, 29 | 0x0000000000000088, 30 | 0x0000000080008009, 31 | 0x000000008000000A, 32 | 0x000000008000808B, 33 | 0x800000000000008B, 34 | 0x8000000000008089, 35 | 0x8000000000008003, 36 | 0x8000000000008002, 37 | 0x8000000000000080, 38 | 0x000000000000800A, 39 | 0x800000008000000A, 40 | 0x8000000080008081, 41 | 0x8000000000008080, 42 | 0x0000000080000001, 43 | 0x8000000080008008, 44 | } 45 | 46 | func main() { 47 | // Initialize the 2 state vectors 48 | var state1 [25]uint64 49 | var state2 [25]uint64 50 | for i := range state1 { 51 | state1[i] = uint64(i) 52 | state2[i] = uint64(i) 53 | } 54 | 55 | // Run the generic method for the first state 56 | keccakF1600Generic(&state1) 57 | 58 | // Run the assembly implemented function for the second state 59 | // note that here we also have to pass in the round constants as well 60 | keccak.KeccakF1600(&state2, &rc) 61 | 62 | // Now check that the 2 state vectrors match 63 | for i, val1 := range state1 { 64 | if val1 != state2[i] { 65 | fmt.Printf("ERROR: %d != %d\n", state1[i], state2[i]) 66 | os.Exit(1) 67 | } 68 | } 69 | 70 | fmt.Println("Success!") 71 | } 72 | 73 | // This native go implementation copied from : https://github.com/golang/crypto/blob/master/sha3/keccakf.go 74 | 75 | // Copyright 2014 The Go Authors. All rights reserved. 76 | // Use of this source code is governed by a BSD-style 77 | // license that can be found in the LICENSE file in 78 | // the golang/crypto repository. 79 | 80 | // keccakF1600Generic applies the Keccak permutation to a 1600b-wide 81 | // state represented as a slice of 25 uint64s. 82 | func keccakF1600Generic(a *[25]uint64) { 83 | // Implementation translated from Keccak-inplace.c 84 | // in the keccak reference code. 85 | var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64 86 | 87 | for i := 0; i < 24; i += 4 { 88 | // Combines the 5 steps in each round into 2 steps. 89 | // Unrolls 4 rounds per loop and spreads some steps across rounds. 90 | 91 | // Round 1 92 | bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] 93 | bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] 94 | bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] 95 | bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] 96 | bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] 97 | d0 = bc4 ^ (bc1<<1 | bc1>>63) 98 | d1 = bc0 ^ (bc2<<1 | bc2>>63) 99 | d2 = bc1 ^ (bc3<<1 | bc3>>63) 100 | d3 = bc2 ^ (bc4<<1 | bc4>>63) 101 | d4 = bc3 ^ (bc0<<1 | bc0>>63) 102 | 103 | bc0 = a[0] ^ d0 104 | t = a[6] ^ d1 105 | bc1 = t<<44 | t>>(64-44) 106 | t = a[12] ^ d2 107 | bc2 = t<<43 | t>>(64-43) 108 | t = a[18] ^ d3 109 | bc3 = t<<21 | t>>(64-21) 110 | t = a[24] ^ d4 111 | bc4 = t<<14 | t>>(64-14) 112 | a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i] 113 | a[6] = bc1 ^ (bc3 &^ bc2) 114 | a[12] = bc2 ^ (bc4 &^ bc3) 115 | a[18] = bc3 ^ (bc0 &^ bc4) 116 | a[24] = bc4 ^ (bc1 &^ bc0) 117 | 118 | t = a[10] ^ d0 119 | bc2 = t<<3 | t>>(64-3) 120 | t = a[16] ^ d1 121 | bc3 = t<<45 | t>>(64-45) 122 | t = a[22] ^ d2 123 | bc4 = t<<61 | t>>(64-61) 124 | t = a[3] ^ d3 125 | bc0 = t<<28 | t>>(64-28) 126 | t = a[9] ^ d4 127 | bc1 = t<<20 | t>>(64-20) 128 | a[10] = bc0 ^ (bc2 &^ bc1) 129 | a[16] = bc1 ^ (bc3 &^ bc2) 130 | a[22] = bc2 ^ (bc4 &^ bc3) 131 | a[3] = bc3 ^ (bc0 &^ bc4) 132 | a[9] = bc4 ^ (bc1 &^ bc0) 133 | 134 | t = a[20] ^ d0 135 | bc4 = t<<18 | t>>(64-18) 136 | t = a[1] ^ d1 137 | bc0 = t<<1 | t>>(64-1) 138 | t = a[7] ^ d2 139 | bc1 = t<<6 | t>>(64-6) 140 | t = a[13] ^ d3 141 | bc2 = t<<25 | t>>(64-25) 142 | t = a[19] ^ d4 143 | bc3 = t<<8 | t>>(64-8) 144 | a[20] = bc0 ^ (bc2 &^ bc1) 145 | a[1] = bc1 ^ (bc3 &^ bc2) 146 | a[7] = bc2 ^ (bc4 &^ bc3) 147 | a[13] = bc3 ^ (bc0 &^ bc4) 148 | a[19] = bc4 ^ (bc1 &^ bc0) 149 | 150 | t = a[5] ^ d0 151 | bc1 = t<<36 | t>>(64-36) 152 | t = a[11] ^ d1 153 | bc2 = t<<10 | t>>(64-10) 154 | t = a[17] ^ d2 155 | bc3 = t<<15 | t>>(64-15) 156 | t = a[23] ^ d3 157 | bc4 = t<<56 | t>>(64-56) 158 | t = a[4] ^ d4 159 | bc0 = t<<27 | t>>(64-27) 160 | a[5] = bc0 ^ (bc2 &^ bc1) 161 | a[11] = bc1 ^ (bc3 &^ bc2) 162 | a[17] = bc2 ^ (bc4 &^ bc3) 163 | a[23] = bc3 ^ (bc0 &^ bc4) 164 | a[4] = bc4 ^ (bc1 &^ bc0) 165 | 166 | t = a[15] ^ d0 167 | bc3 = t<<41 | t>>(64-41) 168 | t = a[21] ^ d1 169 | bc4 = t<<2 | t>>(64-2) 170 | t = a[2] ^ d2 171 | bc0 = t<<62 | t>>(64-62) 172 | t = a[8] ^ d3 173 | bc1 = t<<55 | t>>(64-55) 174 | t = a[14] ^ d4 175 | bc2 = t<<39 | t>>(64-39) 176 | a[15] = bc0 ^ (bc2 &^ bc1) 177 | a[21] = bc1 ^ (bc3 &^ bc2) 178 | a[2] = bc2 ^ (bc4 &^ bc3) 179 | a[8] = bc3 ^ (bc0 &^ bc4) 180 | a[14] = bc4 ^ (bc1 &^ bc0) 181 | 182 | // Round 2 183 | bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] 184 | bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] 185 | bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] 186 | bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] 187 | bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] 188 | d0 = bc4 ^ (bc1<<1 | bc1>>63) 189 | d1 = bc0 ^ (bc2<<1 | bc2>>63) 190 | d2 = bc1 ^ (bc3<<1 | bc3>>63) 191 | d3 = bc2 ^ (bc4<<1 | bc4>>63) 192 | d4 = bc3 ^ (bc0<<1 | bc0>>63) 193 | 194 | bc0 = a[0] ^ d0 195 | t = a[16] ^ d1 196 | bc1 = t<<44 | t>>(64-44) 197 | t = a[7] ^ d2 198 | bc2 = t<<43 | t>>(64-43) 199 | t = a[23] ^ d3 200 | bc3 = t<<21 | t>>(64-21) 201 | t = a[14] ^ d4 202 | bc4 = t<<14 | t>>(64-14) 203 | a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+1] 204 | a[16] = bc1 ^ (bc3 &^ bc2) 205 | a[7] = bc2 ^ (bc4 &^ bc3) 206 | a[23] = bc3 ^ (bc0 &^ bc4) 207 | a[14] = bc4 ^ (bc1 &^ bc0) 208 | 209 | t = a[20] ^ d0 210 | bc2 = t<<3 | t>>(64-3) 211 | t = a[11] ^ d1 212 | bc3 = t<<45 | t>>(64-45) 213 | t = a[2] ^ d2 214 | bc4 = t<<61 | t>>(64-61) 215 | t = a[18] ^ d3 216 | bc0 = t<<28 | t>>(64-28) 217 | t = a[9] ^ d4 218 | bc1 = t<<20 | t>>(64-20) 219 | a[20] = bc0 ^ (bc2 &^ bc1) 220 | a[11] = bc1 ^ (bc3 &^ bc2) 221 | a[2] = bc2 ^ (bc4 &^ bc3) 222 | a[18] = bc3 ^ (bc0 &^ bc4) 223 | a[9] = bc4 ^ (bc1 &^ bc0) 224 | 225 | t = a[15] ^ d0 226 | bc4 = t<<18 | t>>(64-18) 227 | t = a[6] ^ d1 228 | bc0 = t<<1 | t>>(64-1) 229 | t = a[22] ^ d2 230 | bc1 = t<<6 | t>>(64-6) 231 | t = a[13] ^ d3 232 | bc2 = t<<25 | t>>(64-25) 233 | t = a[4] ^ d4 234 | bc3 = t<<8 | t>>(64-8) 235 | a[15] = bc0 ^ (bc2 &^ bc1) 236 | a[6] = bc1 ^ (bc3 &^ bc2) 237 | a[22] = bc2 ^ (bc4 &^ bc3) 238 | a[13] = bc3 ^ (bc0 &^ bc4) 239 | a[4] = bc4 ^ (bc1 &^ bc0) 240 | 241 | t = a[10] ^ d0 242 | bc1 = t<<36 | t>>(64-36) 243 | t = a[1] ^ d1 244 | bc2 = t<<10 | t>>(64-10) 245 | t = a[17] ^ d2 246 | bc3 = t<<15 | t>>(64-15) 247 | t = a[8] ^ d3 248 | bc4 = t<<56 | t>>(64-56) 249 | t = a[24] ^ d4 250 | bc0 = t<<27 | t>>(64-27) 251 | a[10] = bc0 ^ (bc2 &^ bc1) 252 | a[1] = bc1 ^ (bc3 &^ bc2) 253 | a[17] = bc2 ^ (bc4 &^ bc3) 254 | a[8] = bc3 ^ (bc0 &^ bc4) 255 | a[24] = bc4 ^ (bc1 &^ bc0) 256 | 257 | t = a[5] ^ d0 258 | bc3 = t<<41 | t>>(64-41) 259 | t = a[21] ^ d1 260 | bc4 = t<<2 | t>>(64-2) 261 | t = a[12] ^ d2 262 | bc0 = t<<62 | t>>(64-62) 263 | t = a[3] ^ d3 264 | bc1 = t<<55 | t>>(64-55) 265 | t = a[19] ^ d4 266 | bc2 = t<<39 | t>>(64-39) 267 | a[5] = bc0 ^ (bc2 &^ bc1) 268 | a[21] = bc1 ^ (bc3 &^ bc2) 269 | a[12] = bc2 ^ (bc4 &^ bc3) 270 | a[3] = bc3 ^ (bc0 &^ bc4) 271 | a[19] = bc4 ^ (bc1 &^ bc0) 272 | 273 | // Round 3 274 | bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] 275 | bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] 276 | bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] 277 | bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] 278 | bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] 279 | d0 = bc4 ^ (bc1<<1 | bc1>>63) 280 | d1 = bc0 ^ (bc2<<1 | bc2>>63) 281 | d2 = bc1 ^ (bc3<<1 | bc3>>63) 282 | d3 = bc2 ^ (bc4<<1 | bc4>>63) 283 | d4 = bc3 ^ (bc0<<1 | bc0>>63) 284 | 285 | bc0 = a[0] ^ d0 286 | t = a[11] ^ d1 287 | bc1 = t<<44 | t>>(64-44) 288 | t = a[22] ^ d2 289 | bc2 = t<<43 | t>>(64-43) 290 | t = a[8] ^ d3 291 | bc3 = t<<21 | t>>(64-21) 292 | t = a[19] ^ d4 293 | bc4 = t<<14 | t>>(64-14) 294 | a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+2] 295 | a[11] = bc1 ^ (bc3 &^ bc2) 296 | a[22] = bc2 ^ (bc4 &^ bc3) 297 | a[8] = bc3 ^ (bc0 &^ bc4) 298 | a[19] = bc4 ^ (bc1 &^ bc0) 299 | 300 | t = a[15] ^ d0 301 | bc2 = t<<3 | t>>(64-3) 302 | t = a[1] ^ d1 303 | bc3 = t<<45 | t>>(64-45) 304 | t = a[12] ^ d2 305 | bc4 = t<<61 | t>>(64-61) 306 | t = a[23] ^ d3 307 | bc0 = t<<28 | t>>(64-28) 308 | t = a[9] ^ d4 309 | bc1 = t<<20 | t>>(64-20) 310 | a[15] = bc0 ^ (bc2 &^ bc1) 311 | a[1] = bc1 ^ (bc3 &^ bc2) 312 | a[12] = bc2 ^ (bc4 &^ bc3) 313 | a[23] = bc3 ^ (bc0 &^ bc4) 314 | a[9] = bc4 ^ (bc1 &^ bc0) 315 | 316 | t = a[5] ^ d0 317 | bc4 = t<<18 | t>>(64-18) 318 | t = a[16] ^ d1 319 | bc0 = t<<1 | t>>(64-1) 320 | t = a[2] ^ d2 321 | bc1 = t<<6 | t>>(64-6) 322 | t = a[13] ^ d3 323 | bc2 = t<<25 | t>>(64-25) 324 | t = a[24] ^ d4 325 | bc3 = t<<8 | t>>(64-8) 326 | a[5] = bc0 ^ (bc2 &^ bc1) 327 | a[16] = bc1 ^ (bc3 &^ bc2) 328 | a[2] = bc2 ^ (bc4 &^ bc3) 329 | a[13] = bc3 ^ (bc0 &^ bc4) 330 | a[24] = bc4 ^ (bc1 &^ bc0) 331 | 332 | t = a[20] ^ d0 333 | bc1 = t<<36 | t>>(64-36) 334 | t = a[6] ^ d1 335 | bc2 = t<<10 | t>>(64-10) 336 | t = a[17] ^ d2 337 | bc3 = t<<15 | t>>(64-15) 338 | t = a[3] ^ d3 339 | bc4 = t<<56 | t>>(64-56) 340 | t = a[14] ^ d4 341 | bc0 = t<<27 | t>>(64-27) 342 | a[20] = bc0 ^ (bc2 &^ bc1) 343 | a[6] = bc1 ^ (bc3 &^ bc2) 344 | a[17] = bc2 ^ (bc4 &^ bc3) 345 | a[3] = bc3 ^ (bc0 &^ bc4) 346 | a[14] = bc4 ^ (bc1 &^ bc0) 347 | 348 | t = a[10] ^ d0 349 | bc3 = t<<41 | t>>(64-41) 350 | t = a[21] ^ d1 351 | bc4 = t<<2 | t>>(64-2) 352 | t = a[7] ^ d2 353 | bc0 = t<<62 | t>>(64-62) 354 | t = a[18] ^ d3 355 | bc1 = t<<55 | t>>(64-55) 356 | t = a[4] ^ d4 357 | bc2 = t<<39 | t>>(64-39) 358 | a[10] = bc0 ^ (bc2 &^ bc1) 359 | a[21] = bc1 ^ (bc3 &^ bc2) 360 | a[7] = bc2 ^ (bc4 &^ bc3) 361 | a[18] = bc3 ^ (bc0 &^ bc4) 362 | a[4] = bc4 ^ (bc1 &^ bc0) 363 | 364 | // Round 4 365 | bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] 366 | bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] 367 | bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] 368 | bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] 369 | bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] 370 | d0 = bc4 ^ (bc1<<1 | bc1>>63) 371 | d1 = bc0 ^ (bc2<<1 | bc2>>63) 372 | d2 = bc1 ^ (bc3<<1 | bc3>>63) 373 | d3 = bc2 ^ (bc4<<1 | bc4>>63) 374 | d4 = bc3 ^ (bc0<<1 | bc0>>63) 375 | 376 | bc0 = a[0] ^ d0 377 | t = a[1] ^ d1 378 | bc1 = t<<44 | t>>(64-44) 379 | t = a[2] ^ d2 380 | bc2 = t<<43 | t>>(64-43) 381 | t = a[3] ^ d3 382 | bc3 = t<<21 | t>>(64-21) 383 | t = a[4] ^ d4 384 | bc4 = t<<14 | t>>(64-14) 385 | a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+3] 386 | a[1] = bc1 ^ (bc3 &^ bc2) 387 | a[2] = bc2 ^ (bc4 &^ bc3) 388 | a[3] = bc3 ^ (bc0 &^ bc4) 389 | a[4] = bc4 ^ (bc1 &^ bc0) 390 | 391 | t = a[5] ^ d0 392 | bc2 = t<<3 | t>>(64-3) 393 | t = a[6] ^ d1 394 | bc3 = t<<45 | t>>(64-45) 395 | t = a[7] ^ d2 396 | bc4 = t<<61 | t>>(64-61) 397 | t = a[8] ^ d3 398 | bc0 = t<<28 | t>>(64-28) 399 | t = a[9] ^ d4 400 | bc1 = t<<20 | t>>(64-20) 401 | a[5] = bc0 ^ (bc2 &^ bc1) 402 | a[6] = bc1 ^ (bc3 &^ bc2) 403 | a[7] = bc2 ^ (bc4 &^ bc3) 404 | a[8] = bc3 ^ (bc0 &^ bc4) 405 | a[9] = bc4 ^ (bc1 &^ bc0) 406 | 407 | t = a[10] ^ d0 408 | bc4 = t<<18 | t>>(64-18) 409 | t = a[11] ^ d1 410 | bc0 = t<<1 | t>>(64-1) 411 | t = a[12] ^ d2 412 | bc1 = t<<6 | t>>(64-6) 413 | t = a[13] ^ d3 414 | bc2 = t<<25 | t>>(64-25) 415 | t = a[14] ^ d4 416 | bc3 = t<<8 | t>>(64-8) 417 | a[10] = bc0 ^ (bc2 &^ bc1) 418 | a[11] = bc1 ^ (bc3 &^ bc2) 419 | a[12] = bc2 ^ (bc4 &^ bc3) 420 | a[13] = bc3 ^ (bc0 &^ bc4) 421 | a[14] = bc4 ^ (bc1 &^ bc0) 422 | 423 | t = a[15] ^ d0 424 | bc1 = t<<36 | t>>(64-36) 425 | t = a[16] ^ d1 426 | bc2 = t<<10 | t>>(64-10) 427 | t = a[17] ^ d2 428 | bc3 = t<<15 | t>>(64-15) 429 | t = a[18] ^ d3 430 | bc4 = t<<56 | t>>(64-56) 431 | t = a[19] ^ d4 432 | bc0 = t<<27 | t>>(64-27) 433 | a[15] = bc0 ^ (bc2 &^ bc1) 434 | a[16] = bc1 ^ (bc3 &^ bc2) 435 | a[17] = bc2 ^ (bc4 &^ bc3) 436 | a[18] = bc3 ^ (bc0 &^ bc4) 437 | a[19] = bc4 ^ (bc1 &^ bc0) 438 | 439 | t = a[20] ^ d0 440 | bc3 = t<<41 | t>>(64-41) 441 | t = a[21] ^ d1 442 | bc4 = t<<2 | t>>(64-2) 443 | t = a[22] ^ d2 444 | bc0 = t<<62 | t>>(64-62) 445 | t = a[23] ^ d3 446 | bc1 = t<<55 | t>>(64-55) 447 | t = a[24] ^ d4 448 | bc2 = t<<39 | t>>(64-39) 449 | a[20] = bc0 ^ (bc2 &^ bc1) 450 | a[21] = bc1 ^ (bc3 &^ bc2) 451 | a[22] = bc2 ^ (bc4 &^ bc3) 452 | a[23] = bc3 ^ (bc0 &^ bc4) 453 | a[24] = bc4 ^ (bc1 &^ bc0) 454 | } 455 | } 456 | -------------------------------------------------------------------------------- /testdata/keccak/src/keccak_arm64_src.s: -------------------------------------------------------------------------------- 1 | // Implementation by Andre Moraes 2 | // 3 | // This file implements Keccak-p[1600] in a SnP-compatible way. 4 | // Please refer to SnP-documentation.h for more details. 5 | // 6 | // This implementation comes with KeccakP-1600-SnP.h in the same folder. 7 | // Please refer to LowLevel.build for the exact list of other files it must be combined with. 8 | 9 | // INFO: Tested on Cortex-A53(odroid-c2), using gcc. 10 | // WARNING: These functions work only on little endian CPU with ARMv8a + NEON architecture 11 | // WARNING: State must be 512 bit (64 bytes) aligned. 12 | // WARNING: Don't use V8-V15 or X19-X28 since we aren't saving them 13 | 14 | // Note that byte order, same as the Keyakv2 Convection: 15 | // v19 = A[0] || A[4] 16 | // v19.2d[0] = A[0] 17 | // v19.2d[1] = A[4] 18 | 19 | // Register-Lane Lookup 20 | // v19 = A[0] || A[4] 21 | // v20 = A[1] || A[5] 22 | // v21 = A[2] || A[6] 23 | // v22 = A[3] || A[7] 24 | 25 | // v23 = A[8] || A[12] 26 | // v24 = A[9] || A[13] 27 | // v25 = A[10] || A[14] 28 | // v26 = A[11] || A[15] 29 | 30 | // v27 = A[16] || A[20] 31 | // v28 = A[17] || A[21] 32 | // v29 = A[18] || A[22] 33 | // v30 = A[19] || A[23] 34 | 35 | // v31 = A[24] || ????? 36 | 37 | // Transpose 38 | // trn1 v0.2d, v19.2d, v20.2d 39 | // trn2 v2.2d, v19.2d, v20.2d 40 | // v0 = A[0] || A[1] 41 | // v1 = A[4] || A[5] 42 | 43 | // Extract 44 | // ext v0.16b, v19.16b, v20.16b, #8 45 | // v0 = A[4] || A[1] 46 | 47 | .macro RhoPi dst, src, sav, rot 48 | ror \src, \src, #64-\rot 49 | mov \sav, \dst 50 | mov \dst, \src 51 | .endm 52 | 53 | // NEON has no BIT-wise vector rotate operation 54 | .macro ROTL64 dst, src, rot 55 | .if (\rot & 7) != 0 // Bit-wise rotation 56 | shl \dst\().2d, \src\().2d, #\rot 57 | sri \dst\().2d, \src\().2d, #64-\rot 58 | .else // Byte-wise rotation, we can use EXT 59 | ext \dst\().16b, \src\().16b, \src\().16b, #\rot/8 60 | .endif 61 | .endm 62 | 63 | .macro KeccakRound 64 | // Theta - Build new lanes 65 | eor v0.16b, v19.16b, v25.16b // v0 = (A[0] ^ A[10]) || (A[4] ^ A[14]) 66 | eor v1.16b, v20.16b, v26.16b // v1 = (A[1] ^ A[11]) || (A[5] ^ A[15]) 67 | eor v2.16b, v21.16b, v28.16b // v2 = (A[2] ^ A[17]) || (A[6] ^ A[21]) 68 | eor v3.16b, v22.16b, v23.16b // v3 = (A[3] ^ A[8]) || (A[7] ^ A[12]) 69 | eor v4.16b, v24.16b, v30.16b // v4 = (A[9] ^ A[19]) || (A[13] ^ A[23]) 70 | 71 | eor v1.16b, v1.16b, v27.16b // v1 = (A[1] ^ A[11] ^ A[16]) || (A[5] ^ A[15] ^ A[20]) 72 | eor v3.16b, v3.16b, v29.16b // v3 = (A[3] ^ A[8] ^ A[18]) || (A[7] ^ A[12] ^ A[22]) 73 | 74 | trn1 v5.2d, v0.2d, v1.2d // v5 = (A[0] ^ A[10]) || (A[1] ^ A[11] ^ A[16]) 75 | trn2 v6.2d, v1.2d, v2.2d // v6 = (A[5] ^ A[15] ^ A[20]) || (A[6] ^ A[21]) 76 | eor v1.16b, v5.16b, v6.16b // v1 = B[0] || B[1] 77 | 78 | ext v5.16b, v4.16b, v2.16b, #8 // v5 = (A[13] ^ A[23]) || (A[2] ^ A[17]) 79 | eor v3.16b, v3.16b, v5.16b // v3 = B[3] || B[2] 80 | 81 | mov v5.2d[0], v0.2d[1] // v5 = (A[4] ^ A[14]) || ???? 82 | eor v4.16b, v4.16b, v5.16b // v4 = (A[9] ^ A[19] ^ A[4] ^ A[14]) || ???? 83 | eor v4.16b, v4.16b, v31.16b // v4 = B[4] || ???? 84 | 85 | ext v2.16b, v1.16b, v1.16b, #8 // v2 = B[1] || B[0] 86 | mov v4.2d[1], v3.2d[0] // v4 = B[4] || B[3] 87 | trn2 v0.2d, v3.2d, v1.2d // v0 = B[2] || B[1] 88 | 89 | ROTL64 v5, v2, 1 // v5 = ROTL64(B[1], 1) || ROTL64(B[0], 1) 90 | ROTL64 v6, v3, 1 // v6 = ROTL64(B[3], 1) || ROTL64(B[2], 1) 91 | ROTL64 v7, v4, 1 // v7 = ROTL64(B[4], 1) || ROTL64(B[3], 1) 92 | 93 | eor v18.16b, v4.16b, v5.16b // v18 = B[4] ^ ROTL64(B[1], 1) || B[3] ^ ROTL64(B[0], 1) 94 | eor v2.16b, v2.16b, v6.16b // v2 = B[1] ^ ROTL64(B[3], 1) || B[0] ^ ROTL64(B[2], 1) 95 | eor v0.16b, v0.16b, v7.16b // v0 = B[2] ^ ROTL64(B[4], 1) || B[1] ^ ROTL64(B[3], 1) 96 | 97 | ext v7.16b, v5.16b, v7.16b, #8 // v7 = ROTL64(B[0], 1) || ROTL64(B[4], 1) 98 | eor v7.16b, v3.16b, v7.16b // v7 = B[3] ^ ROTL64(B[0], 1) || B[2] ^ ROTL64(B[4], 1) 99 | 100 | ext v6.16b, v6.16b, v5.16b, #8 // v6 = ROTL64(B[2], 1) || ROTL64(B[1], 1) 101 | trn1 v4.2d, v1.2d, v4.2d // v4 = B[0] || B[4] 102 | eor v6.16b, v4.16b, v6.16b // v6 = B[0] ^ ROTL64(B[2], 1) || B[4] ^ ROTL64(B[1], 1) 103 | 104 | // Theta - Apply lanes 105 | eor v19.16b, v19.16b, v18.16b // A[0] ^= B[4] ^ ROTL64(B[1], 1), A[4] ^= B[3] ^ ROTL64(B[0], 1) 106 | eor v20.16b, v20.16b, v6.16b // A[1] ^= B[0] ^ ROTL64(B[2], 1), A[5] ^= B[4] ^ ROTL64(B[1], 1) 107 | eor v21.16b, v21.16b, v2.16b // A[2] ^= B[1] ^ ROTL64(B[3], 1), A[6] ^= B[0] ^ ROTL64(B[2], 1) 108 | eor v22.16b, v22.16b, v0.16b // A[3] ^= B[2] ^ ROTL64(B[4], 1), A[7] ^= B[1] ^ ROTL64(B[3], 1) 109 | eor v23.16b, v23.16b, v0.16b // A[8] ^= B[2] ^ ROTL64(B[4], 1), A[12] ^= B[1] ^ ROTL64(B[3], 1) 110 | eor v24.16b, v24.16b, v7.16b // A[9] ^= B[3] ^ ROTL64(B[0], 1), A[13] ^= B[2] ^ ROTL64(B[4], 1) 111 | eor v25.16b, v25.16b, v18.16b // A[10] ^= B[4] ^ ROTL64(B[1], 1), A[14] ^= B[3] ^ ROTL64(B[0], 1) 112 | eor v26.16b, v26.16b, v6.16b // A[11] ^= B[0] ^ ROTL64(B[2], 1), A[15] ^= B[4] ^ ROTL64(B[1], 1) 113 | eor v27.16b, v27.16b, v6.16b // A[16] ^= B[0] ^ ROTL64(B[2], 1), A[20] ^= B[4] ^ ROTL64(B[1], 1) 114 | eor v28.16b, v28.16b, v2.16b // A[17] ^= B[1] ^ ROTL64(B[3], 1), A[21] ^= B[0] ^ ROTL64(B[2], 1) 115 | eor v29.16b, v29.16b, v0.16b // A[18] ^= B[2] ^ ROTL64(B[4], 1), A[22] ^= B[1] ^ ROTL64(B[3], 1) 116 | eor v30.16b, v30.16b, v7.16b // A[19] ^= B[3] ^ ROTL64(B[0], 1), A[23] ^= B[2] ^ ROTL64(B[4], 1) 117 | eor v31.16b, v31.16b, v7.16b // A[24] ^= B[3] ^ ROTL64(B[0], 1), ???? 118 | 119 | // Rho Pi 120 | mov x11, v20.2d[0] // x11 = A[1] 121 | 122 | RhoPi v25.2d[0], x11, x10, 1 // A[10] = ROTL64(A[1], 1) 123 | RhoPi v22.2d[1], x10, x11, 3 // A[7] = ROTL64(A[10], 3) 124 | RhoPi v26.2d[0], x11, x10, 6 // A[11] = ROTL64(A[7], 6) 125 | RhoPi v28.2d[0], x10, x11, 10 // A[17] = ROTL64(A[11], 10) 126 | RhoPi v29.2d[0], x11, x10, 15 // A[18] = ROTL64(A[17], 15) 127 | RhoPi v22.2d[0], x10, x11, 21 // A[3] = ROTL64(A[18], 21) 128 | RhoPi v20.2d[1], x11, x10, 28 // A[5] = ROTL64(A[3], 28) 129 | RhoPi v27.2d[0], x10, x11, 36 // A[16] = ROTL64(A[5], 36) 130 | RhoPi v23.2d[0], x11, x10, 45 // A[8] = ROTL64(A[16], 45) 131 | RhoPi v28.2d[1], x10, x11, 55 // A[21] = ROTL64(A[8], 55) 132 | RhoPi v31.2d[0], x11, x10, 2 // A[24] = ROTL64(A[21], 2) 133 | RhoPi v19.2d[1], x10, x11, 14 // A[4] = ROTL64(A[24], 14) 134 | RhoPi v26.2d[1], x11, x10, 27 // A[15] = ROTL64(A[4], 27) 135 | RhoPi v30.2d[1], x10, x11, 41 // A[23] = ROTL64(A[15], 41) 136 | RhoPi v30.2d[0], x11, x10, 56 // A[19] = ROTL64(A[23], 56) 137 | RhoPi v24.2d[1], x10, x11, 8 // A[13] = ROTL64(A[19], 8) 138 | RhoPi v23.2d[1], x11, x10, 25 // A[12] = ROTL64(A[13], 25) 139 | RhoPi v21.2d[0], x10, x11, 43 // A[2] = ROTL64(A[12], 43) 140 | RhoPi v27.2d[1], x11, x10, 62 // A[20] = ROTL64(A[2], 62) 141 | RhoPi v25.2d[1], x10, x11, 18 // A[14] = ROTL64(A[20], 18) 142 | RhoPi v29.2d[1], x11, x10, 39 // A[22] = ROTL64(A[14], 39) 143 | RhoPi v24.2d[0], x10, x11, 61 // A[9] = ROTL64(A[22], 61) 144 | RhoPi v21.2d[1], x11, x10, 20 // A[6] = ROTL64(A[9], 20) 145 | 146 | ror x10, x10, #20 147 | mov v20.2d[0], x10 // A[1] = ROTL64(A[6], 44) 148 | 149 | // Chi - Some lanes are applied earlier so we can reuse registers 150 | ext v18.16b, v26.16b, v31.16b, #8 // v18 = A[15] || A[24] 151 | bic v6.16b, v27.16b, v18.16b // v6 = ~A[15] & A[16] || ~A[24] & A[20] 152 | 153 | ext v17.16b, v26.16b, v31.16b, #8 // v17 = A[15] || A[24] 154 | bic v5.16b, v17.16b, v30.16b // v5 = ~A[19] & A[15] || ~A[23] & A[24] 155 | 156 | bic v3.16b, v30.16b, v29.16b // v3 = ~A[18] & A[19] || ~A[22] & A[23] 157 | 158 | eor v30.16b, v30.16b, v6.16b // A[19] ^= ~A[15] & A[16], A[23] ^= ~A[24] & A[20] 159 | 160 | trn1 v18.2d, v26.2d, v25.2d // v18 = A[11] || A[10] 161 | ext v17.16b, v23.16b, v26.16b, #8 // v17 = A[12] || A[11] 162 | bic v7.16b, v17.16b, v18.16b // v7 = ~A[11] & A[12] || ~A[10] & A[11] 163 | 164 | trn2 v18.2d, v20.2d, v25.2d // v18 = A[5] || A[14] 165 | ext v17.16b, v21.16b, v25.16b, #8 // v17 = A[6] || A[10] 166 | bic v6.16b, v17.16b, v18.16b // v6 = ~A[5] & A[6] || ~A[14] & A[10] 167 | 168 | trn1 v18.2d, v20.2d, v19.2d // v18 = A[1] || A[0] 169 | trn1 v17.2d, v21.2d, v20.2d // v17 = A[2] || A[1] 170 | bic v1.16b, v17.16b, v18.16b // v1 = ~A[1] & A[2] || ~A[0] & A[1] 171 | 172 | ext v18.16b, v19.16b, v23.16b, #8 // v18 = A[4] || A[8] 173 | trn1 v17.2d, v19.2d, v24.2d // v17 = A[0] || A[9] 174 | bic v0.16b, v17.16b, v18.16b // v0 = ~A[4] & A[0] || ~A[8] & A[9] 175 | 176 | ext v18.16b, v23.16b, v27.16b, #8 // v18 = A[12] || A[16] 177 | ext v17.16b, v24.16b, v28.16b, #8 // v17 = A[13] || A[17] 178 | bic v4.16b, v17.16b, v18.16b // v4 = ~A[12] & A[13] || ~A[16] & A[17] 179 | 180 | mov v18.2d[0], v27.2d[1] // v18 = A[20] || ???? 181 | mov v17.2d[0], v28.2d[1] // v17 = A[21] || ???? 182 | bic v2.16b, v17.16b, v18.16b // v2 = ~A[20] & A[21] || ???? 183 | eor v31.16b, v31.16b, v2.16b // A[24] ^= ~A[20] & A[21], ???? 184 | 185 | bic v2.16b, v29.16b, v28.16b // v2 = ~A[17] & A[18] || ~A[21] & A[22] 186 | eor v27.16b, v27.16b, v2.16b // A[16] ^= ~A[17] & A[18], A[20] ^= ~A[21] & A[22] 187 | 188 | bic v2.16b, v22.16b, v21.16b // v2 = ~A[2] & A[3] || ~A[6] & A[7] 189 | 190 | eor v28.16b, v28.16b, v3.16b // A[17] ^= ~A[18] & A[19], A[21] ^= ~A[22] & A[23] 191 | eor v29.16b, v29.16b, v5.16b // A[18] ^= ~A[19] & A[15], A[22] ^= ~A[23] & A[24] 192 | 193 | ext v17.16b, v19.16b, v23.16b, #8 // v17 = A[4] || A[8] 194 | bic v3.16b, v17.16b, v22.16b // v3 = ~A[3] & A[4] || ~A[7] & A[8] 195 | 196 | trn2 v17.2d, v20.2d, v25.2d // v17 = A[5] || A[14] 197 | bic v5.16b, v17.16b, v24.16b // v5 = ~A[9] & A[5] || ~A[13] & A[14] 198 | 199 | // Chi - Apply remaining lanes 200 | eor v19.16b, v19.16b, v1.16b // A[0] ^= ~A[1] & A[2], A[4] ^= ~A[0] & A[1] 201 | eor v20.16b, v20.16b, v2.16b // A[1] ^= ~A[2] & A[3], A[5] ^= ~A[6] & A[7] 202 | eor v21.16b, v21.16b, v3.16b // A[2] ^= ~A[3] & A[4], A[6] ^= ~A[7] & A[8] 203 | eor v22.16b, v22.16b, v0.16b // A[3] ^= ~A[4] & A[0], A[7] ^= ~A[8] & A[9] 204 | eor v23.16b, v23.16b, v5.16b // A[8] ^= ~A[9] & A[5], A[12] ^= ~A[13] & A[14] 205 | eor v24.16b, v24.16b, v6.16b // A[9] ^= ~A[5] & A[6], A[13] ^= ~A[14] & A[10] 206 | eor v25.16b, v25.16b, v7.16b // A[10] ^= ~A[11] & A[12], A[14] ^= ~A[10] & A[11] 207 | eor v26.16b, v26.16b, v4.16b // A[11] ^= ~A[12] & A[13], A[15] ^= ~A[16] & A[17] 208 | 209 | // Iota 210 | ld1 { v16.d }[0], [x1], #8 211 | eor v19.16b, v19.16b, v16.16b 212 | .endm 213 | 214 | 215 | // ---------------------------------------------------------------------------- 216 | // 217 | // void KeccakF1600( void *states, void *constants ) 218 | // 219 | .align 8 220 | .global KeccakF1600 221 | .type KeccakF1600, %function; 222 | KeccakF1600: 223 | // state array is first argument on stack 224 | // constant array is the second argument on the stack 225 | ldr x0, [sp, #8] 226 | ldr x1, [sp, #16] 227 | // load the state 228 | ld4 { v19.2d, v20.2d, v21.2d, v22.2d }, [x0], #64 229 | ld4 { v23.2d, v24.2d, v25.2d, v26.2d }, [x0], #64 230 | ld4 { v27.2d, v28.2d, v29.2d, v30.2d }, [x0], #64 231 | ld1 { v31.d }[0], [x0], #8 232 | sub x0, x0, #200 233 | movi v16.2d, #0 234 | KeccakRound 235 | KeccakRound 236 | KeccakRound 237 | KeccakRound 238 | KeccakRound 239 | KeccakRound 240 | KeccakRound 241 | KeccakRound 242 | KeccakRound 243 | KeccakRound 244 | KeccakRound 245 | KeccakRound 246 | KeccakRound 247 | KeccakRound 248 | KeccakRound 249 | KeccakRound 250 | KeccakRound 251 | KeccakRound 252 | KeccakRound 253 | KeccakRound 254 | KeccakRound 255 | KeccakRound 256 | KeccakRound 257 | KeccakRound 258 | // store the state 259 | st4 { v19.2d, v20.2d, v21.2d, v22.2d }, [x0], #64 260 | st4 { v23.2d, v24.2d, v25.2d, v26.2d }, [x0], #64 261 | st4 { v27.2d, v28.2d, v29.2d, v30.2d }, [x0], #64 262 | st1 { v31.d }[0], [x0], #8 263 | 264 | -------------------------------------------------------------------------------- /testdata/keccak/src/keccak_arm_src.s: -------------------------------------------------------------------------------- 1 | @ 2 | @ Implementation by Ronny Van Keer, hereby denoted as "the implementer". 3 | @ 4 | @ For more information, feedback or questions, please refer to our website: 5 | @ https://keccak.team/ 6 | @ 7 | @ To the extent possible under law, the implementer has waived all copyright 8 | @ and related or neighboring rights to the source code in this file. 9 | @ http://creativecommons.org/publicdomain/zero/1.0/ 10 | @ 11 | @ --- 12 | @ 13 | @ This file implements Keccak-p[1600] in a SnP-compatible way. 14 | @ Please refer to SnP-documentation.h for more details. 15 | @ 16 | @ This implementation comes with KeccakP-1600-SnP.h in the same folder. 17 | @ Please refer to LowLevel.build for the exact list of other files it must be combined with. 18 | @ 19 | 20 | @ WARNING: These functions work only on little endian CPU with@ ARMv7A + NEON architecture 21 | @ WARNING: State must be 256 bit (32 bytes) aligned, best is 64-byte (cache alignment). 22 | @ INFO: Tested on Cortex-A8 (BeagleBone Black), using gcc. 23 | 24 | 25 | .text 26 | 27 | @ macros 28 | 29 | .macro RhoPi4 dst1, src1, rot1, dst2, src2, rot2, dst3, src3, rot3, dst4, src4, rot4 30 | .if (\rot1 & 7) != 0 31 | vshl.u64 \dst1, \src1, #\rot1 32 | .else 33 | vext.8 \dst1, \src1, \src1, #8-\rot1/8 34 | .endif 35 | .if (\rot2 & 7) != 0 36 | vshl.u64 \dst2, \src2, #\rot2 37 | .else 38 | vext.8 \dst2, \src2, \src2, #8-\rot2/8 39 | .endif 40 | .if (\rot3 & 7) != 0 41 | vshl.u64 \dst3, \src3, #\rot3 42 | .else 43 | vext.8 \dst3, \src3, \src3, #8-\rot3/8 44 | .endif 45 | .if (\rot4 & 7) != 0 46 | vshl.u64 \dst4, \src4, #\rot4 47 | .else 48 | vext.8 \dst4, \src4, \src4, #8-\rot4/8 49 | .endif 50 | .if (\rot1 & 7) != 0 51 | vsri.u64 \dst1, \src1, #64-\rot1 52 | .endif 53 | .if (\rot2 & 7) != 0 54 | vsri.u64 \dst2, \src2, #64-\rot2 55 | .endif 56 | .if (\rot3 & 7) != 0 57 | vsri.u64 \dst3, \src3, #64-\rot3 58 | .endif 59 | .if (\rot4 & 7) != 0 60 | vsri.u64 \dst4, \src4, #64-\rot4 61 | .endif 62 | .endm 63 | 64 | .macro KeccakRound 65 | 66 | @Prepare Theta 67 | veor.64 q13, q0, q5 68 | vst1.64 {q12}, [r0:128]! 69 | veor.64 q14, q1, q6 70 | vst1.64 {q4}, [r0:128]! 71 | veor.64 d26, d26, d27 72 | vst1.64 {q9}, [r0:128] 73 | veor.64 d28, d28, d29 74 | veor.64 d26, d26, d20 75 | veor.64 d27, d28, d21 76 | 77 | veor.64 q14, q2, q7 78 | veor.64 q15, q3, q8 79 | veor.64 q4, q4, q9 80 | veor.64 d28, d28, d29 81 | veor.64 d30, d30, d31 82 | veor.64 d25, d8, d9 83 | veor.64 d28, d28, d22 84 | veor.64 d29, d30, d23 85 | veor.64 d25, d25, d24 86 | sub r0, r0, #32 87 | 88 | @Apply Theta 89 | vadd.u64 d30, d27, d27 90 | vadd.u64 d24, d28, d28 91 | vadd.u64 d8, d29, d29 92 | vadd.u64 d18, d25, d25 93 | 94 | vsri.64 d30, d27, #63 95 | vsri.64 d24, d28, #63 96 | vsri.64 d8, d29, #63 97 | vsri.64 d18, d25, #63 98 | 99 | veor.64 d30, d30, d25 100 | veor.64 d24, d24, d26 101 | veor.64 d8, d8, d27 102 | vadd.u64 d27, d26, d26 @u 103 | veor.64 d18, d18, d28 104 | 105 | vmov.i64 d31, d30 106 | vmov.i64 d25, d24 107 | vsri.64 d27, d26, #63 @u 108 | vmov.i64 d9, d8 109 | vmov.i64 d19, d18 110 | 111 | veor.64 d20, d20, d30 112 | veor.64 d21, d21, d24 113 | veor.64 d27, d27, d29 @u 114 | veor.64 d22, d22, d8 115 | veor.64 d23, d23, d18 116 | vmov.i64 d26, d27 @u 117 | 118 | veor.64 q0, q0, q15 119 | veor.64 q1, q1, q12 120 | veor.64 q2, q2, q4 121 | veor.64 q3, q3, q9 122 | 123 | veor.64 q5, q5, q15 124 | veor.64 q6, q6, q12 125 | vld1.64 {q12}, [r0:128]! 126 | veor.64 q7, q7, q4 127 | vld1.64 {q4}, [r0:128]! 128 | veor.64 q8, q8, q9 129 | vld1.64 {q9}, [r0:128] 130 | veor.64 d24, d24, d26 @u 131 | sub r0, r0, #32 132 | veor.64 q4, q4, q13 @u 133 | veor.64 q9, q9, q13 @u 134 | 135 | @Rho Pi 136 | vmov.i64 d27, d2 137 | vmov.i64 d28, d4 138 | vmov.i64 d29, d6 139 | vmov.i64 d25, d8 140 | 141 | RhoPi4 d2, d3, 44, d4, d14, 43, d8, d24, 14, d6, d17, 21 @ 1 < 6, 2 < 12, 4 < 24, 3 < 18 142 | RhoPi4 d3, d9, 20, d14, d16, 25, d24, d21, 2, d17, d15, 15 @ 6 < 9, 12 < 13, 24 < 21, 18 < 17 143 | RhoPi4 d9, d22, 61, d16, d19, 8, d21, d7, 55, d15, d12, 10 @ 9 < 22, 13 < 19, 21 < 8, 17 < 11 144 | RhoPi4 d22, d18, 39, d19, d23, 56, d7, d13, 45, d12, d5, 6 @ 22 < 14, 19 < 23, 8 < 16, 11 < 7 145 | RhoPi4 d18, d20, 18, d23, d11, 41, d13, d1, 36, d5, d10, 3 @ 14 < 20, 23 < 15, 16 < 5, 7 < 10 146 | RhoPi4 d20, d28, 62, d11, d25, 27, d1, d29, 28, d10, d27, 1 @ 20 < 2, 15 < 4, 5 < 3, 10 < 1 147 | 148 | @Chi b+g 149 | vmov.i64 q13, q0 150 | vbic.64 q15, q2, q1 @ ba ^= ~be & bi 151 | veor.64 q0, q15 152 | vmov.i64 q14, q1 153 | vbic.64 q15, q3, q2 @ be ^= ~bi & bo 154 | veor.64 q1, q15 155 | vbic.64 q15, q4, q3 @ bi ^= ~bo & bu 156 | veor.64 q2, q15 157 | vbic.64 q15, q13, q4 @ bo ^= ~bu & ba 158 | vbic.64 q13, q14, q13 @ bu ^= ~ba & be 159 | veor.64 q3, q15 160 | veor.64 q4, q13 161 | 162 | @Chi k+m 163 | vmov.i64 q13, q5 164 | vbic.64 q15, q7, q6 @ ba ^= ~be & bi 165 | veor.64 q5, q15 166 | vmov.i64 q14, q6 167 | vbic.64 q15, q8, q7 @ be ^= ~bi & bo 168 | veor.64 q6, q15 169 | vbic.64 q15, q9, q8 @ bi ^= ~bo & bu 170 | veor.64 q7, q15 171 | vbic.64 q15, q13, q9 @ bo ^= ~bu & ba 172 | vbic.64 q13, q14, q13 @ bu ^= ~ba & be 173 | veor.64 q8, q15 174 | veor.64 q9, q13 175 | 176 | @Chi s 177 | vmov.i64 q13, q10 178 | vbic.64 d30, d22, d21 @ ba ^= ~be & bi 179 | vbic.64 d31, d23, d22 @ be ^= ~bi & bo 180 | veor.64 q10, q15 181 | vbic.64 d30, d24, d23 @ bi ^= ~bo & bu 182 | vbic.64 d31, d26, d24 @ bo ^= ~bu & ba 183 | vbic.64 d26, d27, d26 @ bu ^= ~ba & be 184 | veor.64 q11, q15 185 | vld1.64 d30, [r1:64]! @ Iota 186 | veor.64 d24, d26 187 | veor.64 d0, d0, d30 @ Iota 188 | .endm 189 | 190 | 191 | 192 | @ ---------------------------------------------------------------------------- 193 | @ 194 | @ void KeccakF1600( void *states, void *constants ) 195 | @ 196 | .align 8 197 | .global KeccakF1600 198 | .type KeccakF1600, %function; 199 | KeccakF1600: 200 | @ note that we don't store lr, as the plan9 assembler will insert that code for us 201 | @ sp+4 is taken as the start of the state array 202 | @ sp+8 is taken as the start of the constants 203 | ldr r0, [sp, #4] 204 | ldr r1, [sp, #8] 205 | vpush {q4-q7} 206 | @ load state - interleaving loads helps with pipelining 207 | vld1.64 d0, [r0:64]! 208 | vld1.64 d2, [r0:64]! 209 | vld1.64 d4, [r0:64]! 210 | vld1.64 d6, [r0:64]! 211 | vld1.64 d8, [r0:64]! 212 | vld1.64 d1, [r0:64]! 213 | vld1.64 d3, [r0:64]! 214 | vld1.64 d5, [r0:64]! 215 | vld1.64 d7, [r0:64]! 216 | vld1.64 d9, [r0:64]! 217 | vld1.64 d10, [r0:64]! 218 | vld1.64 d12, [r0:64]! 219 | vld1.64 d14, [r0:64]! 220 | vld1.64 d16, [r0:64]! 221 | vld1.64 d18, [r0:64]! 222 | vld1.64 d11, [r0:64]! 223 | vld1.64 d13, [r0:64]! 224 | vld1.64 d15, [r0:64]! 225 | vld1.64 d17, [r0:64]! 226 | vld1.64 d19, [r0:64]! 227 | vld1.64 { d20, d21 }, [r0:128]! 228 | vld1.64 { d22, d23 }, [r0:128]! 229 | vld1.64 d24, [r0:64] 230 | sub r0, r0, #24*8 231 | KeccakRound 232 | KeccakRound 233 | KeccakRound 234 | KeccakRound 235 | KeccakRound 236 | KeccakRound 237 | KeccakRound 238 | KeccakRound 239 | KeccakRound 240 | KeccakRound 241 | KeccakRound 242 | KeccakRound 243 | KeccakRound 244 | KeccakRound 245 | KeccakRound 246 | KeccakRound 247 | KeccakRound 248 | KeccakRound 249 | KeccakRound 250 | KeccakRound 251 | KeccakRound 252 | KeccakRound 253 | KeccakRound 254 | KeccakRound 255 | @ store state 256 | vst1.64 d0, [r0:64]! 257 | vst1.64 d2, [r0:64]! 258 | vst1.64 d4, [r0:64]! 259 | vst1.64 d6, [r0:64]! 260 | vst1.64 d8, [r0:64]! 261 | vst1.64 d1, [r0:64]! 262 | vst1.64 d3, [r0:64]! 263 | vst1.64 d5, [r0:64]! 264 | vst1.64 d7, [r0:64]! 265 | vst1.64 d9, [r0:64]! 266 | vst1.64 d10, [r0:64]! 267 | vst1.64 d12, [r0:64]! 268 | vst1.64 d14, [r0:64]! 269 | vst1.64 d16, [r0:64]! 270 | vst1.64 d18, [r0:64]! 271 | vst1.64 d11, [r0:64]! 272 | vst1.64 d13, [r0:64]! 273 | vst1.64 d15, [r0:64]! 274 | vst1.64 d17, [r0:64]! 275 | vst1.64 d19, [r0:64]! 276 | vst1.64 { d20, d21 }, [r0:128]! 277 | vst1.64 { d22, d23 }, [r0:128]! 278 | vst1.64 d24, [r0:64] 279 | vpop {q4-q7} 280 | @ note that bx isn't necessary - the plan9 assembler inserts this for us 281 | -------------------------------------------------------------------------------- /testdata/keccak/task.yaml: -------------------------------------------------------------------------------- 1 | summary: Test Keccak on ARM 2 | environment: 3 | GOARM/arm: 7 4 | GOARCH/arm: arm 5 | QEMU_EXEC/arm: qemu-arm-static 6 | GOARCH/arm64: arm64 7 | QEMU_EXEC/arm64: qemu-aarch64-static 8 | execute: | 9 | export GOPATH=$(go env GOPATH) 10 | export PATH="$GOPATH/bin:$PATH" 11 | go generate 12 | go build -o keccakcheck keccakcheck.go 13 | $QEMU_EXEC keccakcheck 14 | -------------------------------------------------------------------------------- /vendor/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "comment": "asm deps as vendored into go release 1.10.2, see https://go.googlesource.com/go/+/go1.10.2/src/cmd/vendor/vendor.json", 3 | "ignore": "", 4 | "package": [ 5 | { 6 | "checksumSHA1": "2EYTI2CI60aobceYiuO/7IUpeI0=", 7 | "path": "golang.org/x/arch/arm/armasm", 8 | "revision": "98fd8d9907002617e6000a77c0740a72947ca1c2" 9 | }, 10 | { 11 | "checksumSHA1": "WXTyiM5cOQdWzOycvvJk8iwCAfY=", 12 | "path": "golang.org/x/arch/arm64/arm64asm", 13 | "revision": "98fd8d9907002617e6000a77c0740a72947ca1c2" 14 | }, 15 | { 16 | "checksumSHA1": "eVw6jYpJoF1k/rudKPHpKslAtQQ=", 17 | "path": "golang.org/x/arch/x86/x86asm", 18 | "revision": "98fd8d9907002617e6000a77c0740a72947ca1c2" 19 | } 20 | ], 21 | "rootPath": "github.com/anonymouse64/asm2go" 22 | } 23 | --------------------------------------------------------------------------------