├── README.md ├── doc ├── randrect-chromium.png ├── svforth.md ├── zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-binary.png ├── zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-color.png ├── zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-grayscale.png ├── zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-binary.png ├── zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-color.png ├── zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-grayscale.png ├── zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-binary.png ├── zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-color.png ├── zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-grayscale.png ├── zeusbin_231ee964adea49da050c681f4127c893.ex0-binary.png ├── zeusbin_231ee964adea49da050c681f4127c893.ex0-color.png └── zeusbin_231ee964adea49da050c681f4127c893.ex0-grayscale.png ├── forth.js ├── forth.py ├── forth ├── binary.js ├── canvas.f ├── canvas.js ├── console.js ├── database.js ├── ds.js ├── node.js ├── rss.f ├── server.js └── url.js ├── index.html ├── lib ├── Ractive.min.js ├── __init__.py ├── forth-helpers.js ├── json.js └── pefile.py ├── malware.rss ├── package.json ├── rsrc └── svforth.css └── site.f /README.md: -------------------------------------------------------------------------------- 1 | svforth 2 | ======= 3 | 4 | SVFORTH - A Forth for Security Analysis and Visualization 5 | 6 | Documentation in the form of a paper is at: https://github.com/ephsec/svforth/blob/master/doc/svforth.md 7 | 8 | Slides for this is availble at: http://conference.hitb.org/hitbsecconf2013kul/materials/D1T3%20%20-%20Wes%20Brown%20-%20Malware%20Analysis%20Using%20Visualization.pdf 9 | 10 | GPLv3 licensed; other licenses available on negotiation. 11 | 12 | ``` 13 | GNU GENERAL PUBLIC LICENSE 14 | Version 3, 29 June 2007 15 | 16 | Copyright (C) 2007 Free Software Foundation, Inc. 17 | Everyone is permitted to copy and distribute verbatim copies 18 | of this license document, but changing it is not allowed. 19 | 20 | Preamble 21 | 22 | The GNU General Public License is a free, copyleft license for 23 | software and other kinds of works. 24 | 25 | The licenses for most software and other practical works are designed 26 | to take away your freedom to share and change the works. By contrast, 27 | the GNU General Public License is intended to guarantee your freedom to 28 | share and change all versions of a program--to make sure it remains free 29 | software for all its users. We, the Free Software Foundation, use the 30 | GNU General Public License for most of our software; it applies also to 31 | any other work released this way by its authors. You can apply it to 32 | your programs, too. 33 | 34 | When we speak of free software, we are referring to freedom, not 35 | price. Our General Public Licenses are designed to make sure that you 36 | have the freedom to distribute copies of free software (and charge for 37 | them if you wish), that you receive source code or can get it if you 38 | want it, that you can change the software or use pieces of it in new 39 | free programs, and that you know you can do these things. 40 | 41 | To protect your rights, we need to prevent others from denying you 42 | these rights or asking you to surrender the rights. Therefore, you have 43 | certain responsibilities if you distribute copies of the software, or if 44 | you modify it: responsibilities to respect the freedom of others. 45 | 46 | For example, if you distribute copies of such a program, whether 47 | gratis or for a fee, you must pass on to the recipients the same 48 | freedoms that you received. You must make sure that they, too, receive 49 | or can get the source code. And you must show them these terms so they 50 | know their rights. 51 | 52 | Developers that use the GNU GPL protect your rights with two steps: 53 | (1) assert copyright on the software, and (2) offer you this License 54 | giving you legal permission to copy, distribute and/or modify it. 55 | 56 | For the developers' and authors' protection, the GPL clearly explains 57 | that there is no warranty for this free software. For both users' and 58 | authors' sake, the GPL requires that modified versions be marked as 59 | changed, so that their problems will not be attributed erroneously to 60 | authors of previous versions. 61 | 62 | Some devices are designed to deny users access to install or run 63 | modified versions of the software inside them, although the manufacturer 64 | can do so. This is fundamentally incompatible with the aim of 65 | protecting users' freedom to change the software. The systematic 66 | pattern of such abuse occurs in the area of products for individuals to 67 | use, which is precisely where it is most unacceptable. Therefore, we 68 | have designed this version of the GPL to prohibit the practice for those 69 | products. If such problems arise substantially in other domains, we 70 | stand ready to extend this provision to those domains in future versions 71 | of the GPL, as needed to protect the freedom of users. 72 | 73 | Finally, every program is threatened constantly by software patents. 74 | States should not allow patents to restrict development and use of 75 | software on general-purpose computers, but in those that do, we wish to 76 | avoid the special danger that patents applied to a free program could 77 | make it effectively proprietary. To prevent this, the GPL assures that 78 | patents cannot be used to render the program non-free. 79 | 80 | The precise terms and conditions for copying, distribution and 81 | modification follow. 82 | 83 | TERMS AND CONDITIONS 84 | 85 | 0. Definitions. 86 | 87 | "This License" refers to version 3 of the GNU General Public License. 88 | 89 | "Copyright" also means copyright-like laws that apply to other kinds of 90 | works, such as semiconductor masks. 91 | 92 | "The Program" refers to any copyrightable work licensed under this 93 | License. Each licensee is addressed as "you". "Licensees" and 94 | "recipients" may be individuals or organizations. 95 | 96 | To "modify" a work means to copy from or adapt all or part of the work 97 | in a fashion requiring copyright permission, other than the making of an 98 | exact copy. The resulting work is called a "modified version" of the 99 | earlier work or a work "based on" the earlier work. 100 | 101 | A "covered work" means either the unmodified Program or a work based 102 | on the Program. 103 | 104 | To "propagate" a work means to do anything with it that, without 105 | permission, would make you directly or secondarily liable for 106 | infringement under applicable copyright law, except executing it on a 107 | computer or modifying a private copy. Propagation includes copying, 108 | distribution (with or without modification), making available to the 109 | public, and in some countries other activities as well. 110 | 111 | To "convey" a work means any kind of propagation that enables other 112 | parties to make or receive copies. Mere interaction with a user through 113 | a computer network, with no transfer of a copy, is not conveying. 114 | 115 | An interactive user interface displays "Appropriate Legal Notices" 116 | to the extent that it includes a convenient and prominently visible 117 | feature that (1) displays an appropriate copyright notice, and (2) 118 | tells the user that there is no warranty for the work (except to the 119 | extent that warranties are provided), that licensees may convey the 120 | work under this License, and how to view a copy of this License. If 121 | the interface presents a list of user commands or options, such as a 122 | menu, a prominent item in the list meets this criterion. 123 | 124 | 1. Source Code. 125 | 126 | The "source code" for a work means the preferred form of the work 127 | for making modifications to it. "Object code" means any non-source 128 | form of a work. 129 | 130 | A "Standard Interface" means an interface that either is an official 131 | standard defined by a recognized standards body, or, in the case of 132 | interfaces specified for a particular programming language, one that 133 | is widely used among developers working in that language. 134 | 135 | The "System Libraries" of an executable work include anything, other 136 | than the work as a whole, that (a) is included in the normal form of 137 | packaging a Major Component, but which is not part of that Major 138 | Component, and (b) serves only to enable use of the work with that 139 | Major Component, or to implement a Standard Interface for which an 140 | implementation is available to the public in source code form. A 141 | "Major Component", in this context, means a major essential component 142 | (kernel, window system, and so on) of the specific operating system 143 | (if any) on which the executable work runs, or a compiler used to 144 | produce the work, or an object code interpreter used to run it. 145 | 146 | The "Corresponding Source" for a work in object code form means all 147 | the source code needed to generate, install, and (for an executable 148 | work) run the object code and to modify the work, including scripts to 149 | control those activities. However, it does not include the work's 150 | System Libraries, or general-purpose tools or generally available free 151 | programs which are used unmodified in performing those activities but 152 | which are not part of the work. For example, Corresponding Source 153 | includes interface definition files associated with source files for 154 | the work, and the source code for shared libraries and dynamically 155 | linked subprograms that the work is specifically designed to require, 156 | such as by intimate data communication or control flow between those 157 | subprograms and other parts of the work. 158 | 159 | The Corresponding Source need not include anything that users 160 | can regenerate automatically from other parts of the Corresponding 161 | Source. 162 | 163 | The Corresponding Source for a work in source code form is that 164 | same work. 165 | 166 | 2. Basic Permissions. 167 | 168 | All rights granted under this License are granted for the term of 169 | copyright on the Program, and are irrevocable provided the stated 170 | conditions are met. This License explicitly affirms your unlimited 171 | permission to run the unmodified Program. The output from running a 172 | covered work is covered by this License only if the output, given its 173 | content, constitutes a covered work. This License acknowledges your 174 | rights of fair use or other equivalent, as provided by copyright law. 175 | 176 | You may make, run and propagate covered works that you do not 177 | convey, without conditions so long as your license otherwise remains 178 | in force. You may convey covered works to others for the sole purpose 179 | of having them make modifications exclusively for you, or provide you 180 | with facilities for running those works, provided that you comply with 181 | the terms of this License in conveying all material for which you do 182 | not control copyright. Those thus making or running the covered works 183 | for you must do so exclusively on your behalf, under your direction 184 | and control, on terms that prohibit them from making any copies of 185 | your copyrighted material outside their relationship with you. 186 | 187 | Conveying under any other circumstances is permitted solely under 188 | the conditions stated below. Sublicensing is not allowed; section 10 189 | makes it unnecessary. 190 | 191 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 192 | 193 | No covered work shall be deemed part of an effective technological 194 | measure under any applicable law fulfilling obligations under article 195 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 196 | similar laws prohibiting or restricting circumvention of such 197 | measures. 198 | 199 | When you convey a covered work, you waive any legal power to forbid 200 | circumvention of technological measures to the extent such circumvention 201 | is effected by exercising rights under this License with respect to 202 | the covered work, and you disclaim any intention to limit operation or 203 | modification of the work as a means of enforcing, against the work's 204 | users, your or third parties' legal rights to forbid circumvention of 205 | technological measures. 206 | 207 | 4. Conveying Verbatim Copies. 208 | 209 | You may convey verbatim copies of the Program's source code as you 210 | receive it, in any medium, provided that you conspicuously and 211 | appropriately publish on each copy an appropriate copyright notice; 212 | keep intact all notices stating that this License and any 213 | non-permissive terms added in accord with section 7 apply to the code; 214 | keep intact all notices of the absence of any warranty; and give all 215 | recipients a copy of this License along with the Program. 216 | 217 | You may charge any price or no price for each copy that you convey, 218 | and you may offer support or warranty protection for a fee. 219 | 220 | 5. Conveying Modified Source Versions. 221 | 222 | You may convey a work based on the Program, or the modifications to 223 | produce it from the Program, in the form of source code under the 224 | terms of section 4, provided that you also meet all of these conditions: 225 | 226 | a) The work must carry prominent notices stating that you modified 227 | it, and giving a relevant date. 228 | 229 | b) The work must carry prominent notices stating that it is 230 | released under this License and any conditions added under section 231 | 7. This requirement modifies the requirement in section 4 to 232 | "keep intact all notices". 233 | 234 | c) You must license the entire work, as a whole, under this 235 | License to anyone who comes into possession of a copy. This 236 | License will therefore apply, along with any applicable section 7 237 | additional terms, to the whole of the work, and all its parts, 238 | regardless of how they are packaged. This License gives no 239 | permission to license the work in any other way, but it does not 240 | invalidate such permission if you have separately received it. 241 | 242 | d) If the work has interactive user interfaces, each must display 243 | Appropriate Legal Notices; however, if the Program has interactive 244 | interfaces that do not display Appropriate Legal Notices, your 245 | work need not make them do so. 246 | 247 | A compilation of a covered work with other separate and independent 248 | works, which are not by their nature extensions of the covered work, 249 | and which are not combined with it such as to form a larger program, 250 | in or on a volume of a storage or distribution medium, is called an 251 | "aggregate" if the compilation and its resulting copyright are not 252 | used to limit the access or legal rights of the compilation's users 253 | beyond what the individual works permit. Inclusion of a covered work 254 | in an aggregate does not cause this License to apply to the other 255 | parts of the aggregate. 256 | 257 | 6. Conveying Non-Source Forms. 258 | 259 | You may convey a covered work in object code form under the terms 260 | of sections 4 and 5, provided that you also convey the 261 | machine-readable Corresponding Source under the terms of this License, 262 | in one of these ways: 263 | 264 | a) Convey the object code in, or embodied in, a physical product 265 | (including a physical distribution medium), accompanied by the 266 | Corresponding Source fixed on a durable physical medium 267 | customarily used for software interchange. 268 | 269 | b) Convey the object code in, or embodied in, a physical product 270 | (including a physical distribution medium), accompanied by a 271 | written offer, valid for at least three years and valid for as 272 | long as you offer spare parts or customer support for that product 273 | model, to give anyone who possesses the object code either (1) a 274 | copy of the Corresponding Source for all the software in the 275 | product that is covered by this License, on a durable physical 276 | medium customarily used for software interchange, for a price no 277 | more than your reasonable cost of physically performing this 278 | conveying of source, or (2) access to copy the 279 | Corresponding Source from a network server at no charge. 280 | 281 | c) Convey individual copies of the object code with a copy of the 282 | written offer to provide the Corresponding Source. This 283 | alternative is allowed only occasionally and noncommercially, and 284 | only if you received the object code with such an offer, in accord 285 | with subsection 6b. 286 | 287 | d) Convey the object code by offering access from a designated 288 | place (gratis or for a charge), and offer equivalent access to the 289 | Corresponding Source in the same way through the same place at no 290 | further charge. You need not require recipients to copy the 291 | Corresponding Source along with the object code. If the place to 292 | copy the object code is a network server, the Corresponding Source 293 | may be on a different server (operated by you or a third party) 294 | that supports equivalent copying facilities, provided you maintain 295 | clear directions next to the object code saying where to find the 296 | Corresponding Source. Regardless of what server hosts the 297 | Corresponding Source, you remain obligated to ensure that it is 298 | available for as long as needed to satisfy these requirements. 299 | 300 | e) Convey the object code using peer-to-peer transmission, provided 301 | you inform other peers where the object code and Corresponding 302 | Source of the work are being offered to the general public at no 303 | charge under subsection 6d. 304 | 305 | A separable portion of the object code, whose source code is excluded 306 | from the Corresponding Source as a System Library, need not be 307 | included in conveying the object code work. 308 | 309 | A "User Product" is either (1) a "consumer product", which means any 310 | tangible personal property which is normally used for personal, family, 311 | or household purposes, or (2) anything designed or sold for incorporation 312 | into a dwelling. In determining whether a product is a consumer product, 313 | doubtful cases shall be resolved in favor of coverage. For a particular 314 | product received by a particular user, "normally used" refers to a 315 | typical or common use of that class of product, regardless of the status 316 | of the particular user or of the way in which the particular user 317 | actually uses, or expects or is expected to use, the product. A product 318 | is a consumer product regardless of whether the product has substantial 319 | commercial, industrial or non-consumer uses, unless such uses represent 320 | the only significant mode of use of the product. 321 | 322 | "Installation Information" for a User Product means any methods, 323 | procedures, authorization keys, or other information required to install 324 | and execute modified versions of a covered work in that User Product from 325 | a modified version of its Corresponding Source. The information must 326 | suffice to ensure that the continued functioning of the modified object 327 | code is in no case prevented or interfered with solely because 328 | modification has been made. 329 | 330 | If you convey an object code work under this section in, or with, or 331 | specifically for use in, a User Product, and the conveying occurs as 332 | part of a transaction in which the right of possession and use of the 333 | User Product is transferred to the recipient in perpetuity or for a 334 | fixed term (regardless of how the transaction is characterized), the 335 | Corresponding Source conveyed under this section must be accompanied 336 | by the Installation Information. But this requirement does not apply 337 | if neither you nor any third party retains the ability to install 338 | modified object code on the User Product (for example, the work has 339 | been installed in ROM). 340 | 341 | The requirement to provide Installation Information does not include a 342 | requirement to continue to provide support service, warranty, or updates 343 | for a work that has been modified or installed by the recipient, or for 344 | the User Product in which it has been modified or installed. Access to a 345 | network may be denied when the modification itself materially and 346 | adversely affects the operation of the network or violates the rules and 347 | protocols for communication across the network. 348 | 349 | Corresponding Source conveyed, and Installation Information provided, 350 | in accord with this section must be in a format that is publicly 351 | documented (and with an implementation available to the public in 352 | source code form), and must require no special password or key for 353 | unpacking, reading or copying. 354 | 355 | 7. Additional Terms. 356 | 357 | "Additional permissions" are terms that supplement the terms of this 358 | License by making exceptions from one or more of its conditions. 359 | Additional permissions that are applicable to the entire Program shall 360 | be treated as though they were included in this License, to the extent 361 | that they are valid under applicable law. If additional permissions 362 | apply only to part of the Program, that part may be used separately 363 | under those permissions, but the entire Program remains governed by 364 | this License without regard to the additional permissions. 365 | 366 | When you convey a copy of a covered work, you may at your option 367 | remove any additional permissions from that copy, or from any part of 368 | it. (Additional permissions may be written to require their own 369 | removal in certain cases when you modify the work.) You may place 370 | additional permissions on material, added by you to a covered work, 371 | for which you have or can give appropriate copyright permission. 372 | 373 | Notwithstanding any other provision of this License, for material you 374 | add to a covered work, you may (if authorized by the copyright holders of 375 | that material) supplement the terms of this License with terms: 376 | 377 | a) Disclaiming warranty or limiting liability differently from the 378 | terms of sections 15 and 16 of this License; or 379 | 380 | b) Requiring preservation of specified reasonable legal notices or 381 | author attributions in that material or in the Appropriate Legal 382 | Notices displayed by works containing it; or 383 | 384 | c) Prohibiting misrepresentation of the origin of that material, or 385 | requiring that modified versions of such material be marked in 386 | reasonable ways as different from the original version; or 387 | 388 | d) Limiting the use for publicity purposes of names of licensors or 389 | authors of the material; or 390 | 391 | e) Declining to grant rights under trademark law for use of some 392 | trade names, trademarks, or service marks; or 393 | 394 | f) Requiring indemnification of licensors and authors of that 395 | material by anyone who conveys the material (or modified versions of 396 | it) with contractual assumptions of liability to the recipient, for 397 | any liability that these contractual assumptions directly impose on 398 | those licensors and authors. 399 | 400 | All other non-permissive additional terms are considered "further 401 | restrictions" within the meaning of section 10. If the Program as you 402 | received it, or any part of it, contains a notice stating that it is 403 | governed by this License along with a term that is a further 404 | restriction, you may remove that term. If a license document contains 405 | a further restriction but permits relicensing or conveying under this 406 | License, you may add to a covered work material governed by the terms 407 | of that license document, provided that the further restriction does 408 | not survive such relicensing or conveying. 409 | 410 | If you add terms to a covered work in accord with this section, you 411 | must place, in the relevant source files, a statement of the 412 | additional terms that apply to those files, or a notice indicating 413 | where to find the applicable terms. 414 | 415 | Additional terms, permissive or non-permissive, may be stated in the 416 | form of a separately written license, or stated as exceptions; 417 | the above requirements apply either way. 418 | 419 | 8. Termination. 420 | 421 | You may not propagate or modify a covered work except as expressly 422 | provided under this License. Any attempt otherwise to propagate or 423 | modify it is void, and will automatically terminate your rights under 424 | this License (including any patent licenses granted under the third 425 | paragraph of section 11). 426 | 427 | However, if you cease all violation of this License, then your 428 | license from a particular copyright holder is reinstated (a) 429 | provisionally, unless and until the copyright holder explicitly and 430 | finally terminates your license, and (b) permanently, if the copyright 431 | holder fails to notify you of the violation by some reasonable means 432 | prior to 60 days after the cessation. 433 | 434 | Moreover, your license from a particular copyright holder is 435 | reinstated permanently if the copyright holder notifies you of the 436 | violation by some reasonable means, this is the first time you have 437 | received notice of violation of this License (for any work) from that 438 | copyright holder, and you cure the violation prior to 30 days after 439 | your receipt of the notice. 440 | 441 | Termination of your rights under this section does not terminate the 442 | licenses of parties who have received copies or rights from you under 443 | this License. If your rights have been terminated and not permanently 444 | reinstated, you do not qualify to receive new licenses for the same 445 | material under section 10. 446 | 447 | 9. Acceptance Not Required for Having Copies. 448 | 449 | You are not required to accept this License in order to receive or 450 | run a copy of the Program. Ancillary propagation of a covered work 451 | occurring solely as a consequence of using peer-to-peer transmission 452 | to receive a copy likewise does not require acceptance. However, 453 | nothing other than this License grants you permission to propagate or 454 | modify any covered work. These actions infringe copyright if you do 455 | not accept this License. Therefore, by modifying or propagating a 456 | covered work, you indicate your acceptance of this License to do so. 457 | 458 | 10. Automatic Licensing of Downstream Recipients. 459 | 460 | Each time you convey a covered work, the recipient automatically 461 | receives a license from the original licensors, to run, modify and 462 | propagate that work, subject to this License. You are not responsible 463 | for enforcing compliance by third parties with this License. 464 | 465 | An "entity transaction" is a transaction transferring control of an 466 | organization, or substantially all assets of one, or subdividing an 467 | organization, or merging organizations. If propagation of a covered 468 | work results from an entity transaction, each party to that 469 | transaction who receives a copy of the work also receives whatever 470 | licenses to the work the party's predecessor in interest had or could 471 | give under the previous paragraph, plus a right to possession of the 472 | Corresponding Source of the work from the predecessor in interest, if 473 | the predecessor has it or can get it with reasonable efforts. 474 | 475 | You may not impose any further restrictions on the exercise of the 476 | rights granted or affirmed under this License. For example, you may 477 | not impose a license fee, royalty, or other charge for exercise of 478 | rights granted under this License, and you may not initiate litigation 479 | (including a cross-claim or counterclaim in a lawsuit) alleging that 480 | any patent claim is infringed by making, using, selling, offering for 481 | sale, or importing the Program or any portion of it. 482 | 483 | 11. Patents. 484 | 485 | A "contributor" is a copyright holder who authorizes use under this 486 | License of the Program or a work on which the Program is based. The 487 | work thus licensed is called the contributor's "contributor version". 488 | 489 | A contributor's "essential patent claims" are all patent claims 490 | owned or controlled by the contributor, whether already acquired or 491 | hereafter acquired, that would be infringed by some manner, permitted 492 | by this License, of making, using, or selling its contributor version, 493 | but do not include claims that would be infringed only as a 494 | consequence of further modification of the contributor version. For 495 | purposes of this definition, "control" includes the right to grant 496 | patent sublicenses in a manner consistent with the requirements of 497 | this License. 498 | 499 | Each contributor grants you a non-exclusive, worldwide, royalty-free 500 | patent license under the contributor's essential patent claims, to 501 | make, use, sell, offer for sale, import and otherwise run, modify and 502 | propagate the contents of its contributor version. 503 | 504 | In the following three paragraphs, a "patent license" is any express 505 | agreement or commitment, however denominated, not to enforce a patent 506 | (such as an express permission to practice a patent or covenant not to 507 | sue for patent infringement). To "grant" such a patent license to a 508 | party means to make such an agreement or commitment not to enforce a 509 | patent against the party. 510 | 511 | If you convey a covered work, knowingly relying on a patent license, 512 | and the Corresponding Source of the work is not available for anyone 513 | to copy, free of charge and under the terms of this License, through a 514 | publicly available network server or other readily accessible means, 515 | then you must either (1) cause the Corresponding Source to be so 516 | available, or (2) arrange to deprive yourself of the benefit of the 517 | patent license for this particular work, or (3) arrange, in a manner 518 | consistent with the requirements of this License, to extend the patent 519 | license to downstream recipients. "Knowingly relying" means you have 520 | actual knowledge that, but for the patent license, your conveying the 521 | covered work in a country, or your recipient's use of the covered work 522 | in a country, would infringe one or more identifiable patents in that 523 | country that you have reason to believe are valid. 524 | 525 | If, pursuant to or in connection with a single transaction or 526 | arrangement, you convey, or propagate by procuring conveyance of, a 527 | covered work, and grant a patent license to some of the parties 528 | receiving the covered work authorizing them to use, propagate, modify 529 | or convey a specific copy of the covered work, then the patent license 530 | you grant is automatically extended to all recipients of the covered 531 | work and works based on it. 532 | 533 | A patent license is "discriminatory" if it does not include within 534 | the scope of its coverage, prohibits the exercise of, or is 535 | conditioned on the non-exercise of one or more of the rights that are 536 | specifically granted under this License. You may not convey a covered 537 | work if you are a party to an arrangement with a third party that is 538 | in the business of distributing software, under which you make payment 539 | to the third party based on the extent of your activity of conveying 540 | the work, and under which the third party grants, to any of the 541 | parties who would receive the covered work from you, a discriminatory 542 | patent license (a) in connection with copies of the covered work 543 | conveyed by you (or copies made from those copies), or (b) primarily 544 | for and in connection with specific products or compilations that 545 | contain the covered work, unless you entered into that arrangement, 546 | or that patent license was granted, prior to 28 March 2007. 547 | 548 | Nothing in this License shall be construed as excluding or limiting 549 | any implied license or other defenses to infringement that may 550 | otherwise be available to you under applicable patent law. 551 | 552 | 12. No Surrender of Others' Freedom. 553 | 554 | If conditions are imposed on you (whether by court order, agreement or 555 | otherwise) that contradict the conditions of this License, they do not 556 | excuse you from the conditions of this License. If you cannot convey a 557 | covered work so as to satisfy simultaneously your obligations under this 558 | License and any other pertinent obligations, then as a consequence you may 559 | not convey it at all. For example, if you agree to terms that obligate you 560 | to collect a royalty for further conveying from those to whom you convey 561 | the Program, the only way you could satisfy both those terms and this 562 | License would be to refrain entirely from conveying the Program. 563 | 564 | 13. Use with the GNU Affero General Public License. 565 | 566 | Notwithstanding any other provision of this License, you have 567 | permission to link or combine any covered work with a work licensed 568 | under version 3 of the GNU Affero General Public License into a single 569 | combined work, and to convey the resulting work. The terms of this 570 | License will continue to apply to the part which is the covered work, 571 | but the special requirements of the GNU Affero General Public License, 572 | section 13, concerning interaction through a network will apply to the 573 | combination as such. 574 | 575 | 14. Revised Versions of this License. 576 | 577 | The Free Software Foundation may publish revised and/or new versions of 578 | the GNU General Public License from time to time. Such new versions will 579 | be similar in spirit to the present version, but may differ in detail to 580 | address new problems or concerns. 581 | 582 | Each version is given a distinguishing version number. If the 583 | Program specifies that a certain numbered version of the GNU General 584 | Public License "or any later version" applies to it, you have the 585 | option of following the terms and conditions either of that numbered 586 | version or of any later version published by the Free Software 587 | Foundation. If the Program does not specify a version number of the 588 | GNU General Public License, you may choose any version ever published 589 | by the Free Software Foundation. 590 | 591 | If the Program specifies that a proxy can decide which future 592 | versions of the GNU General Public License can be used, that proxy's 593 | public statement of acceptance of a version permanently authorizes you 594 | to choose that version for the Program. 595 | 596 | Later license versions may give you additional or different 597 | permissions. However, no additional obligations are imposed on any 598 | author or copyright holder as a result of your choosing to follow a 599 | later version. 600 | 601 | 15. Disclaimer of Warranty. 602 | 603 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 604 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 605 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 606 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 607 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 608 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 609 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 610 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 611 | 612 | 16. Limitation of Liability. 613 | 614 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 615 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 616 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 617 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 618 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 619 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 620 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 621 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 622 | SUCH DAMAGES. 623 | 624 | 17. Interpretation of Sections 15 and 16. 625 | 626 | If the disclaimer of warranty and limitation of liability provided 627 | above cannot be given local legal effect according to their terms, 628 | reviewing courts shall apply local law that most closely approximates 629 | an absolute waiver of all civil liability in connection with the 630 | Program, unless a warranty or assumption of liability accompanies a 631 | copy of the Program in return for a fee. 632 | 633 | END OF TERMS AND CONDITIONS 634 | 635 | How to Apply These Terms to Your New Programs 636 | 637 | If you develop a new program, and you want it to be of the greatest 638 | possible use to the public, the best way to achieve this is to make it 639 | free software which everyone can redistribute and change under these terms. 640 | 641 | To do so, attach the following notices to the program. It is safest 642 | to attach them to the start of each source file to most effectively 643 | state the exclusion of warranty; and each file should have at least 644 | the "copyright" line and a pointer to where the full notice is found. 645 | 646 | 647 | Copyright (C) 648 | 649 | This program is free software: you can redistribute it and/or modify 650 | it under the terms of the GNU General Public License as published by 651 | the Free Software Foundation, either version 3 of the License, or 652 | (at your option) any later version. 653 | 654 | This program is distributed in the hope that it will be useful, 655 | but WITHOUT ANY WARRANTY; without even the implied warranty of 656 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 657 | GNU General Public License for more details. 658 | 659 | You should have received a copy of the GNU General Public License 660 | along with this program. If not, see . 661 | 662 | Also add information on how to contact you by electronic and paper mail. 663 | 664 | If the program does terminal interaction, make it output a short 665 | notice like this when it starts in an interactive mode: 666 | 667 | Copyright (C) 668 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 669 | This is free software, and you are welcome to redistribute it 670 | under certain conditions; type `show c' for details. 671 | 672 | The hypothetical commands `show w' and `show c' should show the appropriate 673 | parts of the General Public License. Of course, your program's commands 674 | might be different; for a GUI interface, you would use an "about box". 675 | 676 | You should also get your employer (if you work as a programmer) or school, 677 | if any, to sign a "copyright disclaimer" for the program, if necessary. 678 | For more information on this, and how to apply and follow the GNU GPL, see 679 | . 680 | 681 | The GNU General Public License does not permit incorporating your program 682 | into proprietary programs. If your program is a subroutine library, you 683 | may consider it more useful to permit linking proprietary applications with 684 | the library. If this is what you want to do, use the GNU Lesser General 685 | Public License instead of this License. But first, please read 686 | . 687 | ``` 688 | -------------------------------------------------------------------------------- /doc/randrect-chromium.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/randrect-chromium.png -------------------------------------------------------------------------------- /doc/svforth.md: -------------------------------------------------------------------------------- 1 | SVFORTH - A Forth for Security Analysis and Visualization 2 | ========================================================= 3 | Wes Brown 4 | 5 | wes@ephemeralsecurity.com 6 | 7 | Ephemeral Security 8 | 9 | October 1, 2013 10 | 11 | Preamble 12 | -------- 13 | The author is conducting a workshop on using visualization to assist in malware, threat, and security analysis. A lot of the workshop will be running on the SVFORTH platform which is used to exhibit and share visualization and analysis techniques. This technical paper goes into detail on SVFORTH and the rationale behind it. 14 | 15 | SVFORTH is a [Forth \[0\]](http://en.wikipedia.org/wiki/Forth_(programming_language)) language environment written in JavaScript with primitives and functions that make it useful for security visualization and analysis work. It is intended to be run in a recent browser for the workshop and includes libraries for metadata and binary manipulation as well as image display. 16 | 17 | Forth? Really? 18 | -------------- 19 | The author is well known for his penchant for developing and using unusual domain specific languages such as Mosquito Lisp to explore and implement new ideas. Previous research has been conducted to apply [Forth as a first stage injection payload \[1\]](http://mtso.squarespace.com/chargen/2009/1/10/applicable-lessons-from-the-embedded-world-aka-forth-rules.html). The language of implementation shapes thought patterns, and disparate thought patterns in turn enable a variety of different modalities. Reframing the problem set with alternate modalities and non-standard paradigms is a time-tested technique for executing successful problem analysis. 20 | 21 | For example, Lisp and other functional languages that allow high order functions and lazy evaluations enable the passing of functions to customize the behavior of the function that is being passed to. The concept of equivalence between data and code allows for models of rapid development that sometimes yield surprisingly elegant and effective code. 22 | 23 | Similarly, Forth has a lot to offer in its stack oriented nature. Programming in a stack based manner is a paradigm shift similar to the difference between functional, object oriented, and procedural languages. Forth encourages a layered approach to programming due to the ease of defining short functions that operate on the stack. 24 | 25 | Much of the visualization and analysis work revolves around the manipluation of query results and sorting data to given criteria. These results tend to be linear, or in the form of multiple rows, lending itself very well to being operated on like a stack. 26 | 27 | In JavaScript? 28 | -------------- 29 | Forth is a very simple language to implement; the interpreter parses for the next word, using whitepace as a delimiter. When the parser encounters a word, it does a lookup against its dictionary to determine if there is code bound to that word. Forth words typically operate directly upon the stack, popping the values it needs off, and pushing the results on. 30 | 31 | This made it very trivial to implement a working Forth interpreter in JavaScript. Forth words have traditionally been either compiled Forth statements or assembly language. Similarly, by leveraging JavaScript's closures and anonymous functions, we are able to bind JavaScript functions in the Forth word dictionary. 32 | 33 | In SVFORTH, virtually all Forth words are bound to JavaScript functions, even the lowest level stack operators. Each Forth word is passed a callback function as its sole argument to execute upon completion of its task. Most Forth word operates upon the stack as the primary data source. 34 | 35 | By writing SVFORTH in JavaScript, several advantages immediately appear: 36 | 37 | * Much [leading edge research \[2\]](http://www.techrepublic.com/resource-library/whitepapers/bootstrapping-a-self-hosted-research-virtual-machine-for-javascript/) has been done in the area of JavaScript optimization and virtual machine design. 38 | * JavaScript can run virtually anywhere, including the data center and mobile devices. 39 | * There is a rich library of functionality available that is especially useful for the visualization and analysis work that SVFORTH is intended for. 40 | * [JavaScript's passing of closures \[3\]](http://lostechies.com/derekgreer/2012/02/17/javascript-closures-explained/) work very well for binding JavaScript functions to Forth words. 41 | * Writing more words is very easy in JavaScript allowing SVFORTH to be extensible for specific purposes. 42 | 43 | Quick SVFORTH Primer 44 | -------------------- 45 | 46 | Forth works as such: 47 | 48 | * `10 20 30 + *` -- this is entered in the REPL 49 | * `10`, `20`, `30` are individually pushed onto the stack, and the stack contents are: 50 | ``` 51 | 1. 30 52 | 2. 20 53 | 3. 10 54 | ``` 55 | * The `+` word is encountered, looked up in the dictionary, and executed. `+` pops the top two items, adds them together, and pushes the result back onto the stack: 56 | ``` 57 | 1. 50 58 | 2. 10 59 | ``` 60 | * At this point, the `*` word is encountered and executed similarly to `+`, resulting in: 61 | ``` 62 | 1. 500 63 | ``` 64 | 65 | Sometimes it can be more illuminating to illustrate in code than it is to explain. Below are some sample SVFORTH words implemented in JavaScript: 66 | 67 | ```javascript 68 | this.canvas = function(callback) { 69 | currCanvas = document.getElementById( stack.pop() ) 70 | currContext = currCanvas.getContext("2d") 71 | executeCallback(callback) 72 | } 73 | 74 | this.fillStyle = function(callback) { 75 | b = stack.pop() 76 | g = stack.pop() 77 | r = stack.pop() 78 | currContext.fillStyle = "rgb(" + [r,g,b].join(",") + ")" 79 | executeCallback(callback) 80 | } 81 | 82 | this.fillRect = function(callback) { 83 | y2 = stack.pop() 84 | x2 = stack.pop() 85 | y1 = stack.pop() 86 | x1 = stack.pop() 87 | currContext.fillRect(x1, y1, x2, y2) 88 | executeCallback(callback) 89 | } 90 | 91 | Word("pickcanvas", this.canvas) 92 | Word("fillcolor", this.fillStyle) 93 | Word("rect", this.fillRect) 94 | ``` 95 | 96 | As mentioned earlier, all SVFORTH words operate upon the stack. To pass arguments to SVFORTH words, the user has to push them onto the stack. These specific examples do not push results back, but instead operate upon the HTML canas. Once the JavaScript functions are defined, they are bound and stored in the SVFORTH dictionary using the `Word()` helper. 97 | 98 | Below is an example of an actual SVFORTH program, `randrect` that randomly splashes different color rectangles as fast as possible. 99 | 100 | ``` 101 | : pickcolor 102 | 0 255 rand 0 255 rand 0 255 rand ( red, green, blue ) 103 | fillcolor ; ( set our color ) 104 | 105 | : putrect 106 | 0 800 rand 0 600 rand ( upper left coordinates ) 107 | 0 800 rand 0 600 rand ( lower right coordinates ) 108 | rect ; ( actually draw the rectangle ) 109 | 110 | : randrect 111 | canvas pickcanvas ( we find our canvas on our HTML page ) 112 | 200 tokenresolution ( how many tokens before setTimeout ) 113 | begin 114 | pickcolor ( pick and set a random color ) 115 | putrect ( draw a rectangle in a random ) 116 | again ; 117 | ``` 118 | 119 | ![randrect in chromium](randrect-chromium.png) 120 | 121 | _Figure 1: randrect running in Chromium_ 122 | 123 | In SVFORTH, words written in Forth are treated the same as words written in JavaScript; as the token interpreter is concerned, there is no difference between the two with the exception that writing and binding a JavaScript word from within the Forth environment is not implemented for security reasons. 124 | 125 | The `randrect` code shows how to define a Forth word; `:` puts the interpreter in a special definition mode which is stored when ';' is encountered. The definition block is tokenized and compiled before being stored in the dictionary keyed to the word. 126 | 127 | Forth as a Query Language 128 | ------------------------- 129 | Due to the ability to define words that operate upon datasets as well as the stack based nature of Forth, SVFORTH lends itself very well to being a data query and filtering language. 130 | 131 | By layering words, a query can be constructed that pulls data from a database or a data source. Forth words that are filters that iterate through the stack can remove items that do not match their criteria. There can also be Forth words that transform the data in an useful way. 132 | 133 | In an actual production application of SVFORTH, queries like the following can be made: 134 | 135 | ``` 136 | twitter 500 from #anonymous filter 137 | ``` 138 | 139 | That specific instance of SVFORTH supports an 'easy mode' where queries can be made in prefix rather than postfix notation: 140 | 141 | ``` 142 | from twitter 500 filter #anonymous 143 | ``` 144 | 145 | `from` is a Forth word that takes as arguments from the stack the data type to pull, and the amount to pull. If all goes well, and we have at least five hundred Twitter posts in our data source, our stack will be filled with JavaScript data structures, one for each Twitter post. 146 | 147 | SVFORTH leverages JavaScript in it's native support for JSON and JavaScript data structures. SVFORTH supports storing these structures as elements on the stack as a datatype beyond the integers that classical Forth supports. 148 | 149 | The useful thing about this is that `from` can be arbitrarily redefined as needed for different types of data sources, such as a text file, a SQLite database, a server request over HTTP, or even straight from a Postgres/MySQL server. 150 | 151 | Once the stack is populated with the results of the execution of `from`, the `filter` word is then applied removing all items from the stack that does not contain the argument in question, `#anonymous`. 152 | 153 | By applying filters, the user then has all Twitter posts that mention the `#anonymous` hashtag out of the results. It is trivial at this point to drill down and narrow the scope as subsequent filters will remove items from the stack until the desired data is found. 154 | 155 | For example, `loic filter` can be invoked on the results of `anonymous filter` to find all `#anonymous` hashtags that mention their Low Orbit Ion Cannon. This can also be stringed together as such: 156 | 157 | ``` 158 | twitter 500 from #anonymous filter loic filter 159 | ``` 160 | 161 | Due to the ease of defining words in Forth, an analyst can define a vocabulary of special purpose words that conduct queries and refine the results. An useful example would be a custom algorithm that sorts the results by sentiment value, iterating through the stack and pushing up and down elements as needed. 162 | 163 | Furthering the use of this capability, these filtering and sorting words can be written in native JavaScript. The `filter` word itself is written in JavaScript, though it treats the data in a very Forth-like fashion by rotating the stack: 164 | 165 | ```javascript 166 | this.filter = function(callback) { 167 | filterTerm = stack.pop(); 168 | depth = stack.depth(); 169 | for (var count=0; count < depth; count++) { 170 | examine = stack.pop(); 171 | if ('data' in examine) { 172 | if (examine.data.search(filterTerm) > 0) { 173 | stack.push(examine); 174 | } 175 | } 176 | stack.rot(); 177 | } 178 | executeCallback(callback); 179 | } 180 | 181 | Word( "filter", this.filter ); 182 | ``` 183 | 184 | Stack Views 185 | ----------- 186 | The next piece that makes SVFORTH useful for the domain of security analysis and visualization is the support for different views of the stack. Each artifact that is stored in the stack has metadata associated with it that may be useful for different contexts such as timestamp, source, type, and origin. 187 | 188 | An illustrative example in the area of malware analysis is visualization of assembler opcodes or aligned binaries. JavaScript's recent support for Typed Arrays allows binary data to be stored directly in memory; this allows for far more performant access and manipulation of this data than the old method of working with Arrays and using `chr()`. 189 | 190 | Binary data can be viewed in many ways such as a hexadecimal view, a disassembly view, or more usefully, an entropy and binary visualization map. The artifact data in the stack remains the same when switching between different views of the same binaries and metadata; this is a key point of how SVFORTH represents the data. If it is filtered via some mechanism, pivoting on a view will not reset the filter. 191 | 192 | Users intuitively see a stack as being top to bottom, and vertically oriented. For this reason, binary artifacts are shown oriented counterclockwise 90 degrees to make the most of horizontal screen space. A 76.8K binary file can be represented as a 128x600 wide map, if a pixel is allocated to represent each byte. 193 | 194 | Below are examples of different views of the same binary, a Zeus trojan variant: 195 | 196 | ![binary view of zeus variant](zeusbin_231ee964adea49da050c681f4127c893.ex0-binary.png) 197 | 198 | _Figure 2: mapping 8-bit aligned values to grayscale_ 199 | 200 | ![opcode view of zeus variant](zeusbin_231ee964adea49da050c681f4127c893.ex0-grayscale.png) 201 | 202 | _Figure 3: Zeus binary, mapping only opcodes to grayscale_ 203 | 204 | ![opcode and PE section view of zeus variant](zeusbin_231ee964adea49da050c681f4127c893.ex0-color.png) 205 | 206 | _Figure 4: Zeus binary, overlaying color for each PE section_ 207 | 208 | 209 | The above figures illustrate the usefulness of different views of the same binary data. The opcode view is dramatically different from the pure binary view; the colorized opcode view is useful for comparing data based on section, but it obscures the binary details themselves. 210 | 211 | The below sequence shows three different Zeus binaries next to each other: 212 | 213 | ![zeus 1 - binary](zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-binary.png) 214 | ![zeus 2 - binary](zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-binary.png) 215 | ![zeus 3 - binary](zeusbin_231ee964adea49da050c681f4127c893.ex0-binary.png) 216 | 217 | _Figure 5: Binary view of three Zeus samples_ 218 | 219 | ![zeus 1 - opcode](zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-grayscale.png) 220 | ![zeus 2 - opcode](zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-grayscale.png) 221 | ![zeus 3 - opcode](zeusbin_231ee964adea49da050c681f4127c893.ex0-grayscale.png) 222 | 223 | _Figure 6: Opcode view of three Zeus samples_ 224 | 225 | ![zeus 1 - opcode](zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-color.png) 226 | ![zeus 2 - opcode](zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-color.png) 227 | ![zeus 3 - opcode](zeusbin_231ee964adea49da050c681f4127c893.ex0-color.png) 228 | 229 | _Figure 6: Opcode view of three Zeus samples overlaid with section colors_ 230 | 231 | Despite the first two Zeus samples being of different sizes, 95K and 141K respectively, there are definite structural similarities visible to an analyst when scaled next to each other. 232 | 233 | SVFORTH allows the sorting of these artifacts according to criteria given interactively; changes in the stack will automatically update the views. One of the key advantagess of SVFORTH running locally on the browser is the latency between intent and response is minimized. 234 | 235 | By using metadata on the artifacts, such as timestamps, SVFORTH is able to provide the analyst useful tools such as frequency analysis and a histogram of occurrences or spotting. When clustering similar variants with each other, tags can then be applied to each; once tagged, the view can be resorted according tag groups. 236 | 237 | Other Applications of SVFORTH 238 | ------------------------------ 239 | 240 | In production and experimental usage, SVFORTH has been used to: 241 | 242 | * Analyze MacOS X Crash Dumps from Pastebin to be analyzed by Crash Analyzer to direct exploit research 243 | * Search and query intelligence artifacts in a database for further analysis and filtering. These artifacts are from multiple data sources and different types but SVFORTH is able to unify them on the same stack. 244 | * Build relationship maps based on monitored Twitter conversations 245 | * Perform ordering of binaries in the stack based on similarity criteria based on hashes, entropy, and [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) to cluster malware variants 246 | 247 | Implementation Details 248 | ---------------------- 249 | The central two objects in SVFORTH is the `Stack` and the `Dictionary`. The `Stack` contains an `Array()` as a private variable, and exposes stack functions such as `pop`, `push`, `dup`, and `swap`. It should be noted that even essential primitive operators such as these are found as words in the Dictionary() and are themselves JavaScript closures. 250 | 251 | ```javascript 252 | // push - [ d ], ( a b c ) -> ( a b c d ) 253 | this.push = function(item, callback) { 254 | __stack.push(item); 255 | executeCallback(callback); 256 | } 257 | 258 | // drop - ( a b c ) -> ( a b ), [] 259 | this.drop = function(callback) { 260 | __stack.pop(); 261 | executeCallback(callback); 262 | } 263 | ``` 264 | 265 | Due to the nature of interacting with JavaScript in an asynchronous fashion, every Forth word needs to take the callback as its sole argument and execute it when done. This callback is typically to the `nextToken()` function to advance the Forth parser's execution, and is passed in as an anonymous closure. This causes the execution of the Forth program to be synchronous, only moving on to the next token once the current token has completed executing. 266 | 267 | The calls to `nextToken()` are wrapped in a function that counts tokens. When a certain amount of tokens have executed, `setTimeout()` is called. The single-threaded nature of JavaScript requires this, or the browser will lock up while VSFORTH is interpreting tokens. 268 | 269 | ```javascript 270 | function nbNextToken(tokens) { 271 | tokenCount += 1 272 | if ( ( tokenCount % self.tokenResolution ) != 0 ) { 273 | nextToken( tokens ) 274 | } else { 275 | setTimeout(function () { nextToken( tokens ) }, 0) 276 | } 277 | } 278 | ``` 279 | 280 | There is no loop construct in the core interpreter driving execution; instead, the intepreter is recursively called using `nextToken()` passed to the Forth words as callbacks. 281 | 282 | ```javascript 283 | function nextToken(tokens) { 284 | ... 285 | if ( typeof currToken == 'function' ) { 286 | currToken( function () { nbNextToken(tokens) } ) 287 | // We check the dictonary to see if our current token matches a word. 288 | } else if (currToken in dictionary.definitions) { 289 | word = dictionary.getWord( currToken ) 290 | if ( typeof( word ) == 'function' ) { 291 | word( function () { nbNextToken(tokens) } ) 292 | } else { 293 | self.parse( word, function () { nbNextToken(tokens) } ) 294 | } 295 | ... 296 | ``` 297 | 298 | A sharp-eyed reader might note that the token stream can have JavaScript functions embedded in them. This is due to the compilation ability of SVFORTH where frequently called functions such as those in a word definition or a loop are tokenized and word lookups performed ahead of time, storing JavaScript functions directly into the token array. 299 | 300 | ```javascript 301 | this.compile = function (tokens) { 302 | for (var tokenIndex in tokens) { 303 | if ( typeof(tokens[tokenIndex]) == 'string' ) { 304 | token = tokens[tokenIndex] 305 | 306 | if ( tokens[tokenIndex] in dictionary.definitions ) { 307 | tokens[tokenIndex] = dictionary.getWord( token ) 308 | } else if ( tokens[tokenIndex] == "" ) { 309 | tokens.splice(tokenIndex, 1) 310 | tokenIndex = tokenIndex - 1 311 | } else if ( !isNaN(tokens[tokenIndex]) ) { 312 | tokenInt = parseInt(tokens[tokenIndex]) 313 | tokenFloat = parseFloat(tokens[tokenIndex]) 314 | if ( tokenInt == tokenFloat ) { 315 | tokens[tokenIndex] = tokenInt 316 | } else { 317 | tokens[tokenIndex] = tokenFloat 318 | } 319 | } else if ( token == "(" ) { 320 | tokens.splice(tokenIndex, tokens.indexOf( ")" ) - tokenIndex + 1) 321 | tokenIndex = tokenIndex - 1 322 | } 323 | } 324 | } 325 | return tokens 326 | } 327 | ``` 328 | 329 | When the compiler is called upon a token stream, for each token found, it does a dictionary lookup on the token; if there is a match, the string is replaced with the corresponding JavaScript function object. Also replaced are strings that are numbers, with either a `Float()` or `Int()`. Tokens following blocks begun by `(` are discarded until a `)` token is hit. This process is very similar to classical Forth's compilation of Forth words into assembler; doing all the dictionary lookups ahead of time and inserting JavaScript closures in place of tokens has been observed to dramatically increase the speed of VSFORTH in loops. 330 | 331 | Much of VSFORTH's functionality is split up into modules that the user can import as needed. Simply importing `vsforth.js` will set up the `Dictionary` and `Stack`; importing further modules such as `vsforth/canvas.js` will automatically add new words to the `vsforth.js` namespace. This allows the user to import only modules that are needed, and offers the ability to easily extend the VSFORTH environment. 332 | 333 | Possible Futures for SVFORTH 334 | ----------------------------- 335 | Forth was originally designed to allow for defining words in assembly, and compiling definitions to assembly. SVFORTH works similarly in allowing JavaScript functions to be stored in the dictionary. But what if SVFORTH could really permit assembler like the tradititonal Forths? 336 | 337 | This is where `asm.js` steps in. `asm.js` is a subset of JavaScript that can be compiled to machine assembler by an ahead-of-time engine. Because it is JavaScript, it can run in browsers and environments that do not natively support `asm.js`. Currently, Mozilla's Spidermonkey engine is the only one that supports this, and will execute `asm.js` much more quickly. 338 | 339 | While `asm.js` was intended to be a compile target rather than as a platform, SVFORTH can be rewritten into `asm.js` with the assembler heap taking the place of the current JavaScript `Array()`. 340 | 341 | Another possible avenue of future research is implementing WebGL visualization, and leveraging GPUs to speed up the visualization rendering even more. This would open up avenues of exploration into 3D visualization for this particular problem space. 342 | 343 | Source Code 344 | ----------- 345 | The non-proprietary bits of SVFORTH are available via the GPL license via GitHub at: 346 | 347 | [4] 348 | 349 | Many Thanks To 350 | -------------- 351 | * Daniel Clemens of [PacketNinjas](http://www.packetninjas.com) [5] for giving the author a playground to develop the concepts that this paper discusses 352 | * Daniel Nowak of [Spectral Security](http://www.spectralsecurity.com) [6] for reviewing and feedback 353 | 354 | References 355 | ---------- 356 | 357 | 0. 358 | 1. 359 | 2. 360 | 3. 361 | 4. 362 | 5. 363 | 6. 364 | -------------------------------------------------------------------------------- /doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-binary.png -------------------------------------------------------------------------------- /doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-color.png -------------------------------------------------------------------------------- /doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-grayscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_0038fd97d96fb8e2beb339be68fc462d.ex0-grayscale.png -------------------------------------------------------------------------------- /doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-binary.png -------------------------------------------------------------------------------- /doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-color.png -------------------------------------------------------------------------------- /doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-grayscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00b8dc506258fa25a5c7203ce1e70780.ex0-grayscale.png -------------------------------------------------------------------------------- /doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-binary.png -------------------------------------------------------------------------------- /doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-color.png -------------------------------------------------------------------------------- /doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-grayscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_00d00711a868a686f8490dad3ad1c9fe.ex0-grayscale.png -------------------------------------------------------------------------------- /doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-binary.png -------------------------------------------------------------------------------- /doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-color.png -------------------------------------------------------------------------------- /doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-grayscale.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/doc/zeusbin_231ee964adea49da050c681f4127c893.ex0-grayscale.png -------------------------------------------------------------------------------- /forth.js: -------------------------------------------------------------------------------- 1 | // Method to support various mechanisms to load a library depending on 2 | // environment. 3 | function importJSLibrary(library) { 4 | // If window is undefined, then it's probably a node.js instance which 5 | // imports using 'require'. 6 | console.log( "Loading JavaScript file:", library ) 7 | if (typeof window == 'undefined') { 8 | require("./" + library) 9 | } else { 10 | // We're probably a browser, so we inject our script load into the DOM. 11 | var xhrObj = new XMLHttpRequest(); 12 | xhrObj.open('GET', library, false); 13 | xhrObj.send(''); 14 | 15 | var body = document.body; 16 | var script = document.createElement('script'); 17 | script.type = 'text/javascript'; 18 | script.text = xhrObj.responseText; 19 | 20 | body.appendChild(script); 21 | } 22 | } 23 | 24 | // We have a much more secure and sane way to deal with JSON parsing that 25 | // doesn't use eval(). 26 | // importJSLibrary( 'lib/json.js' ) 27 | 28 | // Make object creation in JavaScript much more sane by adding a create 29 | // function. 30 | if (typeof Object.create !== 'function') { 31 | Object.create = function(o) { 32 | var F = function() {}; 33 | F.prototype = o; 34 | return new F(); 35 | } 36 | } 37 | 38 | // Various methods to obtain a file and put it onto the stack, depending on the 39 | // JavaScript environment. 40 | if ( typeof window === 'undefined' ) { 41 | fs = require( 'fs' ); 42 | var getFile = function( path, context, loadCallback ) { 43 | fs.readFile( path, function ( err, data ) { 44 | if (err) throw err; 45 | context.stack.push( new String( data ) ); 46 | loadCallback( context ); 47 | } ); 48 | } 49 | } else { 50 | var getFile = function( path, context, loadCallback ) { 51 | function responseIntoStack() { 52 | if (this.readyState == 4) { 53 | context.stack.push( req.responseText ); 54 | loadCallback( context ); 55 | } 56 | } 57 | 58 | var req = new XMLHttpRequest(); 59 | req.onload = responseIntoStack; 60 | req.open( "GET", path, true ); 61 | req.send(); 62 | } 63 | } 64 | 65 | // Allows us to call Forth functions from JavaScript space, and to 66 | // bind Forth functions from JavaScript. 67 | function call(symbol, inputContext) { 68 | // If we were not passed an input context, we obtain our context 69 | // from the current JavaScript scope. 70 | if ( typeof( inputContext ) !== 'undefined' ) { 71 | context = inputContext; 72 | } 73 | 74 | // We obtain out function by a symbol lookup against our current context. 75 | var fn = context.dictionary.getWord( symbol ); 76 | 77 | // Make sure our return value is undefined. 78 | context.returnValue = undefined; 79 | 80 | // Then finally, we call out function on our current context. 81 | fn( context ); 82 | } 83 | 84 | // Our context object contains the current context, with the dictionary, tokens, 85 | // and stack state. We can have multiple contexts running, sharing any or none 86 | // of the states between contexts. 87 | // 88 | // For example, we can have separate contexts that share the same stack, and 89 | // have different token states for an implementation of coroutines. 90 | // 91 | // Our spec can be another context object, if we want to clone it and then 92 | // replace some or all of the elements of the context. 93 | var createContext = function( spec ) { 94 | if ( typeof spec === 'undefined' ) { spec = {} }; 95 | if ( 'dictionary' in spec ) { var dictionary = spec.dictionary } 96 | else { var dictionary = createDictionary() }; 97 | if ( 'coros' in spec ) { var coros = spec.coros } 98 | else { var coros = [] }; 99 | if ( 'tokens' in spec ) { var tokens = spec.tokens } 100 | else { var tokens = [] }; 101 | if ( 'console' in spec ) { var console = spec.console } 102 | else { var console = {} }; 103 | 104 | var returnValue = spec.returnValue; 105 | var callback = spec.callback; 106 | 107 | var context = {}; 108 | 109 | context.dictionary = dictionary 110 | context.tokens = tokens 111 | context.returnValue = returnValue 112 | context.callback = callback 113 | context.console = console 114 | 115 | if ( 'stacks' in spec ) { var stacks = spec.stacks } 116 | else { var stacks = { "@global": createStack( "@global", context ) } }; 117 | if ( 'stack' in spec ) { var stack = spec.stack } 118 | else { var stack = stacks[ "@global" ] }; 119 | if ( 'writeStack' in spec ) { var writeStack = spec.writeStack } 120 | else { var writeStack = stacks[ "@global" ] }; 121 | 122 | context.stack = stack 123 | context.writeStack = writeStack 124 | context.stacks = stacks 125 | 126 | 127 | return( context ); 128 | } 129 | 130 | // Our Dictionary object creator function. 131 | var createDictionary = function( spec ) { 132 | if ( typeof spec === 'undefined' ) { spec = {} }; 133 | if ( 'dictionary' in spec ) { var dictionary = spec.dictionary } 134 | else { var dictionary = {} }; 135 | // Sets of dictionaries containing Forth words to integrate into this 136 | // dictionary. 137 | if ( 'forthWords' in spec ) { var forthWordSets = spec.forthWords } 138 | else { var forthWordSets = [] }; 139 | // if we were passed definitions, because we were passed a dictionary 140 | // as a spec object rather than a spec, we set this accordingly. 141 | if ( 'definitions' in spec ) { dictionary.definitions = spec.definitions }; 142 | // we still don't have a definitions, so we set an empty definitions. 143 | if ( !( 'definitions' in dictionary) ) { dictionary.definitions = {} }; 144 | 145 | // Add a new word to our dictionary. 146 | dictionary.register = function( tokenString, fn ) { 147 | this.definitions[ tokenString ] = fn; 148 | } 149 | 150 | // Given a JS dictionary, register all the words in it onto ourself. 151 | dictionary.registerWords = function( functionDict ) { 152 | for (var word in functionDict) { 153 | this.register( word, functionDict[ word ] ); 154 | }; 155 | } 156 | 157 | // Remove our dictionary definition. 158 | dictionary.remove = function( tokenString ) { 159 | delete( this.definitions[ tokenString ] ); 160 | } 161 | 162 | // The heart of soul, definition retrieval from our dictionary. 163 | dictionary.getWord = function( tokenString ) { 164 | var word = this.definitions[ tokenString ]; 165 | 166 | // if we have a precompiled word, we return the tokens as a new array, 167 | // to ensure that the original precompiled word isn't sliced away 168 | if ( Object.prototype.toString.call( word ) === '[object Array]' ) { 169 | return( word.slice(0) ); 170 | } else { 171 | return( word ); 172 | }; 173 | } 174 | 175 | // Now that we've defined our dictionary methods, we recurse through the 176 | // word sets provided as part of the specs and register them. 177 | for ( var forthWordSet in forthWordSets ) { 178 | dictionary.registerWords( forthWordSets[ forthWordSet ] ); 179 | } 180 | 181 | // Finally, our new dictionary object. 182 | return( dictionary ); 183 | 184 | } 185 | 186 | // Our Forth parser and execution routines; given a context object, we add 187 | // the execution and parser routines to this. In a future refactor, this 188 | // should be functions used with apply() rather than being re-passed context 189 | // to itself. 190 | var applyExecutionContext = function( context ) { 191 | 192 | this.preprocessInput = function( input, context ) { 193 | if ( typeof input === 'undefined' ) { 194 | // We were not passed any input to execute, so we execute the tokens that 195 | // are already set in the current context. 196 | var input = context.tokens; 197 | }; 198 | 199 | // console.log( input ); 200 | 201 | if ( typeof( input ) === "string" ) { 202 | // If we're a string, we split along a whitespace delimiter, for crude 203 | // 'tokenization'. 204 | var tokens = input.split( /\s/ ); 205 | } else if ( typeof( input ) == "object" ) { 206 | // We were passed an array, so we want to make a copy of the array rather 207 | // than operate directly on the array. Operating on a definition would 208 | // be very bad, and break us. 209 | if ( 'slice' in input ) { 210 | var tokens = input.slice(0); 211 | } else { 212 | var tokens = [ input ]; 213 | } 214 | } else { 215 | // We don't know what the hell we were passed. 216 | throw( "Invalid input to execution parser." ); 217 | } 218 | 219 | return( tokens ); 220 | } 221 | 222 | this.execute = function( input, returnContext ) { 223 | // This is the only function that doesn't take context as an argument, 224 | // instead leveraging the fact that we're a context object ourself; this 225 | // segues into apply() very well. 226 | 227 | 228 | var tokens = this.preprocessInput( input ); 229 | 230 | // Rather than replace the tokens, we inject our execution *before* the 231 | // currently existing tokens in the stream. 232 | this.tokens = tokens.concat( this.tokens ); 233 | 234 | // console.log( "Execute called:", this.tokens, this.stack ); 235 | 236 | // If we reach the end of execution of this context, we can return to a 237 | // different context. 238 | if ( typeof( returnContext ) !== 'undefined' ) { 239 | this.returnContext = returnContext; 240 | } 241 | 242 | // console.log( "TOKEN STREAM:", this.tokens ) 243 | 244 | // Kick off our execution parser on our current context. 245 | this.nextToken(); 246 | return; 247 | } 248 | 249 | // Advance to the next token in our input stream. This is really a wrapper 250 | // for parseNextToken which is a counter, and calls out to setTimeout() 251 | // as appropriate to allow the browser to actually breathe. 252 | this.nextToken = function() { 253 | if ( typeof currTokenCount !== 'undefined' ) { 254 | currTokenCount = currTokenCount + 1 255 | } else { 256 | currTokenCount = 1 257 | } 258 | 259 | if ( ( currTokenCount % tokenresolution ) === 0 ) { 260 | // We've hit our speedbump, so call setTimeout. 261 | var nextCall = function(context) { return( function() { 262 | context.parseNextToken(); 263 | } ) }; 264 | setTimeout( nextCall( this ), 0 ); 265 | } else { 266 | // Full speed ahead. 267 | this.parseNextToken(); 268 | } 269 | } 270 | 271 | this.parseNextToken = function() { 272 | // Nothing more to parse, so we're done and return. 273 | if ( this.tokens.length == 0 ) { 274 | // if ( this.stack.coros.length !== 0 ) { 275 | // this.tokens = context.stack.coros.shift(); 276 | // this.nextToken.apply( this ); 277 | //} else { 278 | // this.stack.running = false; 279 | //} 280 | if ( typeof this.returnContext !== 'undefined' ) { 281 | // We have another context to return to, so we execute the callback 282 | // on the old context to return control to it. 283 | // console.log( "Execution done, returning context.", this ) 284 | var returnContext = this.returnContext; 285 | this.executeCallback( returnContext ); 286 | return 287 | } else { 288 | // Ensure that we're not called again, ending the token execution 289 | // loop. 290 | // console.log( "Execution done.", this ) 291 | this.callback = undefined; 292 | return; 293 | } 294 | } 295 | 296 | // Before we do anything, set our callback on the current context to 297 | // advance to the next token. All Forth functions should be calling the 298 | // callback to complete, allowing the parser state to advance. 299 | this.callback = this.nextToken; 300 | 301 | // We move onto the next token by assigning the new token to currToken 302 | // and dropping it from the current token stream. 303 | var currToken = this.tokens.shift(); 304 | 305 | // We're a string, so we need to evaluate it. 306 | if ( typeof( currToken ) == 'string' ) { 307 | // Null string due to extra whitespace, ignore it. 308 | if ( currToken == "" ) { 309 | this.nextToken.apply( this ); 310 | return; 311 | } else if (currToken in this.dictionary.definitions) { 312 | // We're in the dictionary, so we do a lookup and retrieve the 313 | // definition. 314 | var word = this.dictionary.getWord( currToken ); 315 | if ( typeof( word ) == 'function' ) { 316 | // We found a JavaScript function or closure stored in the definition, 317 | // so we execute it, with the callback to move onto the next token. 318 | word( this ); 319 | } else if ( typeof( word ) === 'string' ) { 320 | // We found a definition that only contains a string, so we need 321 | // to execute it as an input stream. 322 | var word = this.compile( word.split(/\s/) ); 323 | this.tokens = word.concat( this.tokens ); 324 | this.nextToken.apply( this ); 325 | return; 326 | } else { 327 | // The definition contained an array, so we insert this definition 328 | // into our current stream at the beginning. 329 | 330 | // We splice to copy the word to ensure that the original definition 331 | // do not get tampered with. 332 | var copyWord = word.splice(0); 333 | this.tokens = copyWord.concat( this.tokens ); 334 | this.nextToken.apply( this ); 335 | return; 336 | } 337 | // Check if our token is a number so that we properly push it onto the 338 | // stack as an int or a float. 339 | } else if ( !isNaN( currToken ) ) { 340 | this.stack.push( parseFloat( currToken ) ); 341 | this.nextToken.apply( this ); 342 | return; 343 | } else { 344 | // We don't appear to be anything that we need to execute, so we 345 | // push ourself as a string onto the stack. 346 | this.stack.push( currToken ); 347 | this.nextToken.apply( this ); 348 | return; 349 | } 350 | } else if ( typeof( currToken ) == 'function' ) { 351 | // We're a closure, so invoke it directly. 352 | currToken( this ); 353 | } else if ( typeof( currToken ) !== 'undefined' ) { 354 | // We're not a string or a function, so push ourself onto the stack. 355 | this.stack.push( currToken ); 356 | this.nextToken.apply( this ); 357 | return; 358 | } 359 | } 360 | 361 | // We are called at the end of every Forth function; this is usually 362 | // a callback to advance to the next token state, but can be a different 363 | // function or closure as needed. 364 | this.executeCallback = function( context ) { 365 | if( typeof context.callback != 'undefined' ) { 366 | context.callback( context ); 367 | } 368 | } 369 | 370 | this.scanUntil = function( token, context ) { 371 | var next = context.tokens.indexOf( token ); 372 | if ( next != -1 ) { 373 | context.tokens.splice( next, 1 ); 374 | return( context.tokens.splice( 0, next ) ); 375 | } else { 376 | // We don't fail here, but undefined should be handled by whoever 377 | // called this as a failure, or to handle appropriately. 378 | return( undefined ); 379 | } 380 | } 381 | 382 | this.compile = function( tokens ) { 383 | var tokenIndex = 0; 384 | 385 | // Check if we've been compiled in the past. 386 | if ( 'compiled' in tokens ) { 387 | return( tokens ); 388 | } 389 | 390 | while ( tokenIndex <= tokens.length-1 ) { 391 | // We found a string in our token stream, so let's examine it. 392 | if ( typeof( tokens[ tokenIndex ] ) == 'string' ) { 393 | var token = tokens[ tokenIndex ]; 394 | // We are a begin comment; we don't want comments in our compiled 395 | // output, so we discard them. 396 | if ( token == "(" ) { 397 | tokens.splice( tokenIndex, tokens.indexOf( ")" ) - tokenIndex + 1 ); 398 | // We skip blocks. 399 | } else if ( token == "[" ) { 400 | var endBlock = tokens.indexOf( "]", tokenIndex ) 401 | if ( !( endBlock ) ) { 402 | throw( "COMPILE ERROR: No terminating ] found for [ block." ); 403 | }; 404 | var wordLookup = this.dictionary.getWord( "[" ); 405 | tokens[ tokenIndex ] = wordLookup; 406 | tokenIndex = tokens.indexOf( "]", tokenIndex ) + 1; 407 | // We do a lookup in our dictionary for the token string. 408 | } else if ( token == '."' ) { 409 | var endString = tokens.indexOf( '"' ); 410 | // We insert our entire string as an object in the token stream. 411 | if ( endString ) { 412 | // Convert our stream of tokens into a string. 413 | tokens[ tokenIndex ] = tokens.splice( 414 | tokenIndex + 1, // ." 415 | endString - tokenIndex - 1 ) // " 416 | .join( " " ); // finally, string 417 | tokens.splice( tokenIndex + 1, 1 ); // remove trailing " 418 | } else { 419 | throw( 'COMPILE ERROR: No terminating " found for ." string.' ); 420 | } 421 | } else if ( tokens[tokenIndex] in this.dictionary.definitions ) { 422 | // We found it, so insert the definition directly into the token 423 | // stream in place of the word. This can be a JavaScript function, 424 | // or it can be a compiled array of tokens obtained from a definition 425 | // written in Forth. 426 | var wordLookup = this.dictionary.getWord( token ); 427 | // If we're a string, we want to keep the string lookup rather than 428 | // attempt to inject the string directly into the stream. 429 | if ( typeof( wordLookup ) === 'function' ) { 430 | wordLookup.tokenName = token; 431 | tokens[ tokenIndex ] = wordLookup; 432 | } else { 433 | wordLookup.tokenName = token; 434 | tokens[ tokenIndex ] = token; 435 | } 436 | tokenIndex += 1; 437 | } else if ( tokens[tokenIndex] == "" ) { 438 | // Null token to discard, caused by extra whitespaces. 439 | tokens.splice( tokenIndex, 1 ); 440 | } else if ( !isNaN(tokens[tokenIndex]) ) { 441 | tokens[ tokenIndex ] = parseFloat( tokens[ tokenIndex ] ); 442 | tokenIndex += 1; 443 | } else { 444 | // We were a string, but we're not anything, so we skip over this 445 | // token untouched. 446 | tokenIndex += 1; 447 | } 448 | } else { 449 | // We're not a string, so this token is already compiled or a 450 | // non-string object. 451 | tokenIndex += 1; 452 | } 453 | } 454 | // Set our compiled flag to true, so that we don't attempt to recompile. 455 | tokens.compiled = true; 456 | return( tokens ); 457 | } 458 | 459 | this.startCoro = function( context, items, coro ) { 460 | var coroContext = Object.create( context ); 461 | coroContext.tokens = []; 462 | coroStackId = '#'+Math.floor(Math.random()*16777215).toString(16) 463 | coroContext.stacks[ coroStackId ] = []; 464 | coroContext.stack = coroContext.stacks[ coroStackId ]; 465 | coroContext.writeStack = coroContext.stack; 466 | coroContext.stack.name = coroStackId; 467 | 468 | // Insert our items to work upon onto our temporary channel stack. 469 | [].push.apply( coroContext.stack, items ); 470 | 471 | // We execute our channel code on our channelContext. 472 | coroContext.execute( coro.slice(0) ); 473 | 474 | // And finally, we return the context after the coro run has 475 | // completed so that the caller can inspect the results if need be. 476 | return( coroContext ); 477 | } 478 | 479 | this.showTokens = function( context ) { 480 | var tokenOutput = ""; 481 | var tokenRep = undefined; 482 | for (tokenIndex in context.tokens) { 483 | var token = context.tokens[ tokenIndex ]; 484 | if ( typeof( token ) === 'undefined' ) { 485 | tokenRep = 'undefined'; 486 | } else if ( token.hasOwnProperty( 'tokenName' ) ) { 487 | tokenRep = "[ " + token.tokenName + " ]"; 488 | } else { 489 | tokenRep = token; 490 | } 491 | tokenOutput = tokenOutput + tokenRep + " "; 492 | } 493 | console.log( tokenOutput ); 494 | }; 495 | 496 | // Load a Forth file into our current execution context. 497 | this.load = function( path ) { 498 | loadCallback = function( context ) { 499 | console.log( "Loading Forth file: ", path ); 500 | var fileContents = context.stack.pop(); 501 | var tokenizedContents = fileContents.split( /\s/ ); 502 | context.execute( tokenizedContents ); 503 | } 504 | getFile( path, this, loadCallback ); 505 | } 506 | 507 | // We return our context object enhanced with our execution functions. 508 | return( this ); 509 | } 510 | 511 | ForthFns = { 512 | // : word ... ; -- our Forth word definitions. 513 | ":": function( context ) { 514 | var defineBlock = context.scanUntil( ";", context ) 515 | var definition = undefined; 516 | var newWord = undefined; 517 | 518 | if ( defineBlock != undefined ) { 519 | // Our new word to define and put in the Dictionary. 520 | newWord = defineBlock[0]; 521 | // Our definition for the word is the rest of the statement up to ';' 522 | definition = defineBlock.splice( 1, defineBlock.length ); 523 | // We compile our definition before storing it -- this speeds up 524 | // execution by replacing strings with function references in the 525 | // token array where appropriate. 526 | definition = context.compile( definition ); 527 | // Actually define our word, just like JavaScript and Python does. 528 | context.dictionary.register( newWord, definition ) 529 | context.executeCallback( context ) 530 | return 531 | } else { 532 | raise( "No terminating ';' found for word definition." ); 533 | } }, 534 | 535 | // Comments. 536 | '(': function( context ) { 537 | context.scanUntil( ")", context ); 538 | context.executeCallback( context ); 539 | return 540 | }, 541 | 542 | // Forth loader exposed into Forth space. 543 | 'load-forth': function( context ) { 544 | var path = context.stack.pop( context ); 545 | context.load( path ); 546 | } 547 | }; 548 | 549 | // Core stack functions in Forth 550 | createStack = function(name, context) { 551 | var channelFired = false; 552 | var stack = []; 553 | stack.name = name; 554 | stack.filters = []; 555 | stack.subscriptions = []; 556 | stack.coros = []; 557 | stack.running = false; 558 | stack.ignoreRedirect = false; 559 | stack.popSubscriptions = []; 560 | 561 | stack.pop = function() { 562 | var popItem = [].pop.apply( this, arguments ); 563 | 564 | if ( this.popSubscriptions.length ) { 565 | for ( subscription in this.popSubscriptions ) { 566 | context.startCoro( context, 567 | [ popItem ], 568 | this.popSubscriptions[ subscription ].slice(0) ); 569 | } 570 | } 571 | 572 | return( popItem ); 573 | } 574 | 575 | stack.splice = function() { 576 | var spliceItems = [].splice.apply( this, arguments ); 577 | 578 | if ( this.popSubscriptions.length ) { 579 | for ( subscription in this.popSubscriptions ) { 580 | context.startCoro( context, 581 | spliceItems, 582 | this.popSubscriptions[ subscription ].slice(0) ); 583 | } 584 | } 585 | 586 | return( spliceItems ); 587 | } 588 | 589 | stack.popMany = function(indices) { 590 | var popItems = []; 591 | 592 | var count = 0; 593 | while ( indices.length > 0 ) { 594 | var index = indices.shift(); 595 | var item = [].splice.apply( this, [ index - count, 1 ] )[0]; 596 | popItems.push( item ); 597 | count += 1; 598 | } 599 | 600 | // If we have any subscribers interested in removal events, we iterate 601 | // through them and execute each as a coroutine. 602 | if ( this.popSubscriptions.length ) { 603 | for ( subscription in this.popSubscriptions ) { 604 | context.startCoro( context, 605 | popItems, 606 | this.popSubscriptions[ subscription ].slice(0) ); 607 | } 608 | } 609 | } 610 | 611 | stack.push = function() { 612 | if ( arguments.length > 1 ) { 613 | var args = Array.prototype.slice.call(arguments); 614 | } else { 615 | var args = [ arguments[0] ]; 616 | } 617 | 618 | // We sometimes want to redirect a stack write to another stack, in the case 619 | // of a pipe. 620 | if ( context.hasOwnProperty( 'writeStack' ) && !( stack.ignoreRedirect ) ) { 621 | if ( context.writeStack.name !== this.name ) { 622 | context.writeStack.push.apply( context.writeStack, args ); 623 | return 624 | } 625 | } 626 | 627 | // If we have any subscribers interested in removal events, we iterate 628 | // through them and execute each as a coroutine. 629 | if ( this.subscriptions.length ) { 630 | for ( subscription in this.subscriptions ) { 631 | context.startCoro( context, 632 | args, 633 | this.subscriptions[ subscription ].slice(0) ); 634 | } 635 | }; 636 | 637 | if ( this.filters.length ) { 638 | for ( filter in this.filters ) { 639 | // We create a new context each time we call a channel on a stack, 640 | // with a temporary local stack. 641 | filterContext = context.startCoro( context, 642 | args, 643 | this.filters[ filter ].slice(0) ); 644 | 645 | // We then copy the temporary stack contents into the stack that the 646 | // channel was associated with. 647 | [].push.apply( this, filterContext.stack ); 648 | }; 649 | 650 | return; 651 | }; 652 | 653 | [].push.apply( this, args ); 654 | 655 | }; 656 | 657 | return( stack ); 658 | } 659 | 660 | StackFns = { 661 | 'filter': function( context ) { 662 | var blockToExecute = context.stack.pop(); 663 | var stackToWatch = context.stack.pop(); 664 | 665 | if ( !( stackToWatch in context.stacks ) ) { 666 | context.stacks[ stackToWatch ] = createStack( stackToWatch, context ); 667 | }; 668 | var stackToWatch = context.stacks[ stackToWatch ]; 669 | stackToWatch.filters.push( context.compile( blockToExecute ) ); 670 | context.executeCallback( context ); 671 | }, 672 | 673 | 'subscribe': function( context ) { 674 | var blockToExecute = context.stack.pop(); 675 | var stackToWatch = context.stack.pop(); 676 | 677 | if ( !( stackToWatch in context.stacks ) ) { 678 | context.stacks[ stackToWatch ] = createStack( stackToWatch, context ); 679 | }; 680 | 681 | var stackToWatch = context.stacks[ stackToWatch ]; 682 | stackToWatch.subscriptions.push( context.compile( blockToExecute ) ); 683 | context.executeCallback( context ); 684 | }, 685 | 686 | 'popsub': function( context ) { 687 | var blockToExecute = context.stack.pop(); 688 | var stackToWatch = context.stack.pop(); 689 | 690 | if ( !( stackToWatch in context.stacks ) ) { 691 | context.stacks[ stackToWatch ] = createStack( stackToWatch, context ); 692 | }; 693 | 694 | var stackToWatch = context.stacks[ stackToWatch ]; 695 | stackToWatch.popSubscriptions.push( context.compile( blockToExecute ) ); 696 | context.executeCallback( context ); 697 | }, 698 | 699 | 'pipe': function( context ) { 700 | var desiredStack = context.stack.pop(); 701 | if ( !( desiredStack in context.stacks ) ) { 702 | context.stacks[ desiredStack ] = createStack( desiredStack, context ); 703 | }; 704 | context.writeStack = context.stacks[ desiredStack ]; 705 | context.executeCallback( context ); 706 | }, 707 | 708 | 'cancel-pipe': function( context ) { 709 | context.writeStack = context.stacks[ '@global' ]; 710 | }, 711 | 712 | 'switch-stack': function( context ) { 713 | var desiredStack = context.stack.pop(); 714 | if ( !( desiredStack in context.stacks ) ) { 715 | context.stacks[ desiredStack ] = createStack( desiredStack, context ); 716 | } 717 | context.stack = context.stacks[ desiredStack ]; 718 | context.executeCallback( context ); 719 | }, 720 | 721 | // pop - ( a b c ) -> ( a b ), [ c ] 722 | 'pop': function( context ) { 723 | context.returnValue = context.stack.pop(); 724 | context.executeCallback( context ); 725 | }, 726 | 727 | 'pop-stack': function( context ) { 728 | var sourceStack = context.stacks[ context.stack.pop() ]; 729 | context.stack.push( sourceStack.pop() ); 730 | context.executeCallback( context ); 731 | }, 732 | 733 | // push - [ d ], ( a b c ) -> ( a b c d ) 734 | 'push': function(item, context) { 735 | context.stack.push( item ); 736 | context.executeCallback( context ); 737 | }, 738 | 739 | 'push-stack': function( context ) { 740 | var target = context.stack.pop(); 741 | if ( !( target in context.stacks ) ) { 742 | context.stacks[ target ] = createStack( target, context ); 743 | }; 744 | var value = context.stack.pop(); 745 | 746 | var targetStack = context.stacks[ target ]; 747 | //console.log( "V:", value, "T:", targetStack.name, 748 | // "W:", context.writeStack.name, "S:", context.stack.name ); 749 | targetStack.ignoreRedirect = true; 750 | targetStack.push.apply( targetStack, [ value ] ); 751 | targetStack.ignoreRedirect = false; 752 | }, 753 | 754 | // clear stack 755 | 'cls': function( context ) { 756 | while (context.stack.length > 0) { 757 | context.stack.pop(); 758 | } 759 | context.executeCallback( context ); 760 | }, 761 | 762 | // drop - ( a b c ) -> ( a b ), [] 763 | 'drop': function( context ) { 764 | context.stack.pop(); 765 | context.executeCallback( context ); 766 | }, 767 | 768 | // dup - ( a b c ) -> ( a b c c ), [] 769 | 'dup': function( context ) { 770 | var item = context.stack[ context.stack.length - 1 ]; 771 | context.stack.push( item ); 772 | context.executeCallback( context ); 773 | }, 774 | 775 | // swap - ( a b c ) -> ( a c b ), [] 776 | 'swap': function( context ) { 777 | context.stack.push( context.stack.pop(), context.stack.pop() ); 778 | context.executeCallback( context ); 779 | }, 780 | 781 | // nip - ( a b c d ) -> ( a b d ) 782 | 'nip': function( context ) { 783 | var top = context.stack.pop(); 784 | context.stack.pop(); 785 | context.stack.push( top ); 786 | context.executeCallback( context ); 787 | }, 788 | 789 | // rot -- ( a b c ) -> ( b a c ) 790 | 'rot': function( context ) { 791 | var first = context.stack.pop(); 792 | var second = context.stack.pop(); 793 | var third = context.stack.pop(); 794 | context.stack.push( second, third, first ); 795 | context.executeCallback( context ); 796 | }, 797 | 798 | // min_rot -- ( a b c ) -> ( c a b ) 799 | '-rot': function( context ) { 800 | var first = context.stack.pop(); 801 | var second = context.stack.pop(); 802 | var third = context.stack.pop(); 803 | context.stack.push( first, third, second ); 804 | context.executeCallback( context ); 805 | }, 806 | 807 | // push_many -- [ e f g ] ( a b c d ) -> ( a b c d e f g ) 808 | 'push_many': function( items, context ) { 809 | context.stack = context.stack.concat( items ) 810 | context.executeCallback( context ); 811 | }, 812 | 813 | // Output our stack onto the console. 814 | '.s': function( context ) { 815 | // console.log( "CONSOLE:", context ); 816 | for (var s=0; s": function( context ) { 998 | conditional( context.stack.pop() != context.stack.pop(), context ); 999 | }, 1000 | "<": function( context ) { 1001 | conditional( context.stack.pop() < context.stack.pop(), context ); 1002 | }, 1003 | ">": function( context ) { 1004 | conditional( context.stack.pop() > context.stack.pop(), context ); 1005 | }, 1006 | "<=": function( context ) { 1007 | conditional( context.stack.pop() <= context.stack.pop(), context ); 1008 | }, 1009 | ">=": function( context ) { 1010 | conditional( context.stack.pop() >= context.stack.pop(), context ); 1011 | }, 1012 | "0=": function( context ) { 1013 | conditional( context.stack.pop() == 0, context ); 1014 | }, 1015 | "0<>": function( context ) { 1016 | conditional( context.stack.pop() != 0, context ); 1017 | }, 1018 | "0>=": function( context ) { 1019 | conditional( context.stack.pop() < 0, context ); 1020 | }, 1021 | "0<=": function( context ) { 1022 | conditional( context.stack.pop() > 0, context ); 1023 | }, 1024 | "true": function( context ) { 1025 | stack.push( -1 ); 1026 | context.executeCallback( context ); 1027 | }, 1028 | "false": function( context ) { 1029 | stack.push( 0 ); 1030 | context.executeCallback( context ); 1031 | }, 1032 | "between": function( context ) { 1033 | num = context.stack.pop(); 1034 | low = context.stack.pop(); 1035 | high = context.stack.pop(); 1036 | conditional( low <= num <= high, context ); 1037 | }, 1038 | "within": function( context ) { 1039 | num = context.stack.pop(); 1040 | low = context.stack.pop(); 1041 | high = context.stack.pop(); 1042 | conditional( low <= num < high, context ); 1043 | }, 1044 | "if": function( context ) { 1045 | elseBlock = context.scanUntil( "else", context ); 1046 | thenBlock = context.scanUntil( "then", context ); 1047 | 1048 | if ( thenBlock == undefined ) { 1049 | raise( "Syntax error: IF without THEN" ); 1050 | } else if ( context.stack.pop() != 0 ) { 1051 | thenBlock = context.compile( thenBlock ); 1052 | context.tokens = thenBlock.concat( context.tokens ); 1053 | } else if ( typeof elseBlock != undefined ) { 1054 | context.compile( elseBlock ); 1055 | context.tokens = elseBlock.concat( context.tokens ); 1056 | } 1057 | context.executeCallback( context ); 1058 | } 1059 | }; 1060 | 1061 | LoopFns = { 1062 | // begin .. again -- our loop functions, which really needs to be enhanced 1063 | // to allow for conditionals. 1064 | 'begin': function( context ) { 1065 | var againBlock = context.scanUntil( "again", context ); 1066 | 1067 | if ( againBlock != undefined ) { 1068 | var block = context.compile( againBlock ); 1069 | context.tokens = block.concat( [ "begin" ], block, [ "again" ] ); 1070 | context.executeCallback( context ); 1071 | } else { 1072 | throw( "BEGIN loop without AGAIN."); 1073 | } 1074 | } 1075 | }; 1076 | 1077 | 1078 | 1079 | 1080 | ExecutionFns = { 1081 | // Our resolution of tokens to allow the browser to breathe. 1082 | 'tokenresolution': function( context ) { 1083 | tokenresolution = context.stack.pop(); 1084 | context.executeCallback( context ); 1085 | }, 1086 | 1087 | // Define an execution block, which is a JavaScript array. 1088 | '[': function( context ) { 1089 | var executionBlock = context.scanUntil( "]", context ); 1090 | if ( executionBlock != undefined ) { 1091 | // Do some typing of our AoT, particularly for numerics. We don't 1092 | // want to compile these, as these in particular may be run in another 1093 | // context entirely that may resolve the symbols differently, like 1094 | // an RPC call to a remote Python implementation. 1095 | for (var index in executionBlock) { 1096 | var currToken = executionBlock[ index ]; 1097 | if ( currToken !== '' && !isNaN(currToken) ) { 1098 | var tokenFloat = parseFloat( currToken ); 1099 | executionBlock[ index ] = tokenFloat; 1100 | } 1101 | } 1102 | // The executionBlock is pushed onto the stack as a distinct 1103 | // individual object. 1104 | context.stack.push( executionBlock ); 1105 | context.executeCallback( context ); 1106 | } else { 1107 | throw( "No closing ']' found for execution block.") 1108 | } 1109 | }, 1110 | 1111 | // Execute Forth block, this is currently run asynchronously now that loops 1112 | // inject more tokens into the stream rather than execute a new context. 1113 | '|': function( context ) { 1114 | var forthCoro = context.stack.pop(); 1115 | 1116 | newContext = applyExecutionContext.apply( createContext( context ) ); 1117 | newContext.execute( forthCoro ); 1118 | context.executeCallback( context ); 1119 | }, 1120 | 1121 | // A Forth RPC -- we can send a Forth execution block to a server to 1122 | // execute on our behalf. 1123 | '#': function( context ) { 1124 | var forthExecutionBlock = context.stack.pop(); 1125 | 1126 | // We actually block the main execution thread until we complete getting 1127 | // a response back. Server responses are encoded in JSON, with an array 1128 | // item for each stack item returned. 1129 | function responseIntoContext(context) { 1130 | // Here, we actually return a function that does the job, to work around 1131 | // scoping issues. 1132 | return( function() { 1133 | if (this.readyState == 4) { 1134 | // Anyone who uses a JSON parse fn that uses exec() is batshit insane. 1135 | response = jsonParse( myRequest.responseText ); 1136 | context.stack.push.apply(context.stack, response ); 1137 | context.executeCallback( context ); 1138 | } 1139 | } ); 1140 | } 1141 | 1142 | // Our RPC call is made via XMLHttpRequest asynchronously, though we 1143 | // force this execution thread to wait until this completes. The contents 1144 | // of the execution block are sent to the server in JSON. 1145 | var myRequest = new XMLHttpRequest(); 1146 | myRequest.onload = responseIntoContext( context ); 1147 | myRequest.open( "POST", "", true ); 1148 | myRequest.setRequestHeader( "Content-Type", "text/plain" ); 1149 | myRequest.send( JSON.stringify( forthExecutionBlock ) ); 1150 | 1151 | } 1152 | } 1153 | 1154 | ExtraFns = { 1155 | "time": function(context) { 1156 | context.stack.push( new Date().getTime() ); 1157 | context.executeCallback( context ); 1158 | }, 1159 | "print": function(context) { 1160 | console.log( context.stack.pop() ) 1161 | context.executeCallback( context ); 1162 | }, 1163 | "clear-localstorage": function(context) { 1164 | console.log( "Clearing local storage.") 1165 | localStorage.clear() 1166 | } 1167 | } 1168 | 1169 | currTokenCount = 0; 1170 | tokenresolution = 200; 1171 | 1172 | // Set up our initial Forth context with dictionary, stack, and then the 1173 | // context containing all of them. 1174 | initialDictionary = createDictionary( 1175 | { forthWords: [ ForthFns, 1176 | StackFns, 1177 | ArithmeticFns, 1178 | StringFns, 1179 | ConditionalFns, 1180 | LoopFns, 1181 | ExecutionFns, 1182 | ExtraFns, 1183 | DebugFns ] } ); 1184 | initialContext = createContext( { dictionary: initialDictionary } ); 1185 | executionContext = applyExecutionContext.apply( initialContext ); 1186 | 1187 | // If we have 'module', we export our class instances, as we're likely 1188 | // Node.js. 1189 | if (typeof module != 'undefined' ) { 1190 | module.exports.applyExecutionContext = applyExecutionContext; 1191 | module.exports.createContext = createContext; 1192 | module.exports.initialDictionary = initialDictionary; 1193 | } 1194 | -------------------------------------------------------------------------------- /forth.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | from __future__ import print_function 3 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer, test 4 | from SocketServer import ThreadingMixIn 5 | from collections import OrderedDict 6 | import os 7 | import json 8 | import cgi 9 | import urllib2 10 | import lib.pefile as pefile 11 | import base64 12 | import binascii 13 | 14 | # Empty function for typing tests 15 | def function(): pass 16 | 17 | class ForthDictionary(): 18 | def __init__(self): 19 | self.__forthdictionary = {} 20 | 21 | def register(self, identifier, function): 22 | self.__forthdictionary[ unicode( identifier ) ] = function 23 | 24 | def remove(self, identifier): 25 | del self.__forthdictionary[token] 26 | 27 | def getWord(self, identifier): 28 | if unicode( identifier ) in self.__forthdictionary: 29 | return( self.__forthdictionary.get( unicode( identifier ) ) ) 30 | 31 | def hasWord(self, identifier): 32 | if unicode( identifier ) in self.__forthdictionary: 33 | return( True ) 34 | 35 | def registerFns(self, fnsToRegister): 36 | for forthWord, function in fnsToRegister: 37 | print( forthWord, "registered" ) 38 | self.register( forthWord, function ) 39 | 40 | def printKeys(self): 41 | print( self.__forthdictionary.keys() ) 42 | 43 | class ParserError(Exception): pass 44 | 45 | class Parser(): 46 | def __init__(self, dictionary): 47 | self.dictionary = dictionary 48 | 49 | def execute(self, input, context): 50 | if ( isinstance( input, basestring ) ) : 51 | tokens = input.split(" ") 52 | context.tokens = tokens 53 | elif ( isinstance(input, Tokens) or type(input) == type([]) ): 54 | context.tokens = input 55 | else: 56 | raise ParserError( "Invalid input to execution parser." ) 57 | 58 | self.nextToken( context ) 59 | 60 | def nextToken(self, context): 61 | stack = context.stack 62 | tokens = context.tokens 63 | dictionary = self.dictionary 64 | 65 | if len( tokens ) == 0: 66 | return 67 | currToken = context.tokens.pop(0) 68 | 69 | if ( isinstance( currToken, basestring ) ): 70 | if ( currToken == "" ): self.nextToken(context) 71 | elif dictionary.hasWord( currToken ): 72 | word = dictionary.getWord( currToken ) 73 | if ( type(word) == type( function ) ): 74 | #print( "Executing ", word ) 75 | word( context ) 76 | elif ( isinstance( word, basestring ) ): 77 | self.execute( word, context ) 78 | elif ( type( word ) == type( [] ) ): 79 | context.tokens.extend( word ) 80 | else: 81 | try: 82 | if int( currToken ): 83 | if float( currToken ) != int( currToken ): 84 | stack.push( float( currToken ) ) 85 | else: 86 | stack.push( int( currToken ) ) 87 | elif currToken == "0": 88 | stack.push( 0 ) 89 | except: 90 | stack.push( currToken ) 91 | elif ( type( currToken ) == type( function ) ): 92 | currToken( context ) 93 | else: 94 | stack.push( currToken ) 95 | 96 | self.nextToken( context ) 97 | 98 | class Stack(list): 99 | def __init__(self, *args, **kwargs): 100 | super(Stack, self).__init__(args[0]) 101 | 102 | def push(self, item): 103 | self.append( item ) 104 | 105 | class Tokens(list): 106 | def __init__(self, *args, **kwargs): 107 | super(Tokens, self).__init__(args[0]) 108 | 109 | def scanUntil(self, token): 110 | try: 111 | next = self.index( token ) 112 | except ValueError: 113 | return( None ) 114 | returnBlock = self[0:next] 115 | self[0:next+1] = [] 116 | return( returnBlock ) 117 | 118 | ############################################################################### 119 | # stack functions -- core to Forth 120 | ############################################################################### 121 | 122 | StackFns = [ 123 | ( "push", lambda (item, context): context.stack.push( item ) ), 124 | ( "clearstack", lambda (context): setattr( context.stack, [] ) ), 125 | # drop - ( a b c ) -> ( a b ), [] 126 | ( "drop", lambda (context): context.stack.pop() ), 127 | # dup - ( a b c ) -> ( a b c c ), [] 128 | ( "dup", lambda (context): context.stack.push( context.stack[-1] ) ), 129 | # swap - ( a b c ) -> ( a c b ), [] 130 | ( "swap", lambda (context): context.stack.extend( [ context.stack.pop(), 131 | context.stack.pop() ] ) ), 132 | ( "nip", lambda (context): context.stack.pop(-2) ), 133 | ( "rot", lambda (context): context.stack.push( context.stack.pop(0) ) ), 134 | ( "-rot", lambda (context): 135 | context.stack.insert( 0, context.stack.pop() ) ), 136 | ( ".s", lambda (context): map( print, context.stack ) ), 137 | # depth -- ( a b c ) -> ( a b c 3 ) 138 | ( "depth", lambda (context): 139 | context.stack.push( context.stack.length() ) ), 140 | # peek -- ( a b c d 2 ) -> ( a b c d b ) 141 | ( "peek", lambda (context): 142 | context.stack.push( context.stack[ context.stack.pop() ] ) ) ] 143 | 144 | ############################################################################### 145 | # arithmetic functions in Forth 146 | ############################################################################### 147 | 148 | ArithmeticFns = [ 149 | # ( a b ) -> a + b 150 | ( "+", lambda (context): 151 | context.stack.push( context.stack.pop() + context.stack.pop() ) ), 152 | # ( a b ) -> a - b 153 | ( "-", lambda (context): 154 | context.stack.push( context.stack.pop(-1) - context.stack.pop() ) ), 155 | # ( a b ) -> a * b 156 | ( "*", lambda (context): 157 | context.stack.push( context.stack.pop() * context.stack.pop() ) ), 158 | # ( a b ) -> a / b 159 | ( "/", lambda (context): 160 | context.stack.push( context.stack.pop(-1) / context.stack.pop() ) ), 161 | # ( a ) -> rand * a 162 | ( "rand", lambda (context): 163 | context.stack.push( int( random.random() * context.stack.pop() ) ) ) ] 164 | 165 | ############################################################################### 166 | # conditional functions in Forth and supporting functions in Python 167 | ############################################################################### 168 | 169 | def conditional(result, context): 170 | if result: context.stack.push(-1) 171 | else: context.stack.push(1) 172 | 173 | def ifthenelse(context): 174 | element = context.stack.pop() 175 | elseBlock = context.tokens.scanUntil( "else" ) 176 | thenBlock = context.tokens.scanUntil( "then" ) 177 | 178 | if ( thenBlock == None ): 179 | raise( "Syntax error: IF without THEN" ) 180 | elif ( element != 0 ): 181 | blockToExecute = thenBlock 182 | elif ( elseBlock != None ): 183 | blockToExecute = elseBlock 184 | 185 | newContext = context.spawn() 186 | newContext.parser.execute(blockToExecute, newContext) 187 | 188 | ConditionalFns = [ 189 | ( "=", lambda (context): 190 | conditional( context.stack.pop() == context.stack.pop() ) ), 191 | ( "<>", lambda (context): 192 | conditional( context.stack.pop() != context.stack.pop() ) ), 193 | ( "<", lambda (context): 194 | conditional( context.stack.pop() < context.stack.pop() ) ), 195 | ( ">", lambda (context): 196 | conditional( context.stack.pop() > context.stack.pop() ) ), 197 | ( "<=", lambda (context): 198 | conditional( context.stack.pop() <= context.stack.pop() ) ), 199 | ( ">=", lambda (context): 200 | conditional( context.stack.pop() >= context.stack.pop() ) ), 201 | ( "0=", lambda (context): 202 | conditional( context.stack.pop() == 0 ) ), 203 | ( "0<>", lambda (context): 204 | conditional( context.stack.pop() != 0 ) ), 205 | ( "0<=", lambda (context): 206 | conditional( context.stack.pop() <= 0 ) ), 207 | ( "true", [ -1 ] ), 208 | ( "false", [ 0 ] ), 209 | ( "between", lambda (context): 210 | conditional( context.stack.pop(-1) <= context.stack.pop() <= 211 | context.stack.pop() ) ), 212 | ( "within", lambda (context): 213 | conditional( context.stack.pop(-1) <= context.stack.pop() < 214 | context.stack.pop() ) ), 215 | ( "if", ifthenelse ) 216 | ] 217 | 218 | ############################################################################### 219 | # loop functions in Forth and supporting functions in Python 220 | ############################################################################### 221 | 222 | def beginLoop(context): 223 | againBlock = context.tokens.scanUntil( "again" ) 224 | if ( againBlock != None ): 225 | while True: 226 | # Here, we make a copy of the code block to execute upon, as 227 | # executing against a set of tokens is destructive. 228 | executeBlock = againBlock[:] 229 | newContext = context.spawn() 230 | newContext.parser.execute(executeBlock, newContext) 231 | 232 | LoopFns = [ 233 | ( "begin", beginLoop ) 234 | ] 235 | 236 | class Context(): 237 | def __init__(self, dictionary=ForthDictionary()): 238 | self.stack = Stack([]) 239 | self.tokens = Tokens([]) 240 | self.dictionary = dictionary 241 | self.parser = Parser(dictionary) 242 | 243 | def spawn(self, stack=None, tokens=None): 244 | childContext = Context(dictionary=self.dictionary) 245 | if stack is not None: 246 | childContext.stack = stack 247 | else: 248 | childContext.stack = self.stack 249 | if tokens is not None: 250 | childContext.tokens = tokens 251 | else: 252 | childContext.tokens = self.tokens 253 | return( childContext ) 254 | 255 | ############################################################################### 256 | # functions to interact with HTTP servers 257 | ############################################################################### 258 | 259 | def getHttp(context): 260 | url = context.stack.pop() 261 | rawData = urllib2.urlopen( url ).read() 262 | context.stack.push( rawData.decode( 'latin-1' ).encode( 'utf-8' ) ) 263 | print( url, "fetched" ) 264 | 265 | HTTPClientFns = [ 266 | ( "get-http", getHttp ) ] 267 | 268 | ############################################################################### 269 | # binary analysis functions 270 | ############################################################################### 271 | 272 | def loadBinary(context): 273 | path = context.stack.pop() 274 | context.stack.push( base64.encodestring( open(path,'r').read() ) ) 275 | 276 | def getPEInfo(context): 277 | rawData = context.stack.pop() 278 | try: 279 | rawData = base64.decodestring( rawData ) 280 | except binascii.Error: 281 | pass 282 | 283 | pe = pefile.PE(data=rawData) 284 | sections = [] 285 | for section in pe.sections: 286 | sections.append( OrderedDict( [ 287 | ( 'section-name', section.Name ), 288 | ( 'section-rawdata-begin', section.PointerToRawData ), 289 | ( 'section-rawdata-size', section.SizeOfRawData ) ] ) ) 290 | context.stack.push( sections ) 291 | 292 | BinaryFns = [ 293 | ( "get-binary-peinfo", getPEInfo ), 294 | ( "load-binary", loadBinary ) ] 295 | 296 | ############################################################################### 297 | # Initialize our startup Forth environment 298 | ############################################################################### 299 | global forthdictionary 300 | forthdictionary = ForthDictionary() 301 | forthdictionary.registerFns( StackFns ) 302 | forthdictionary.registerFns( ArithmeticFns ) 303 | forthdictionary.registerFns( ConditionalFns ) 304 | forthdictionary.registerFns( LoopFns ) 305 | forthdictionary.registerFns( HTTPClientFns ) 306 | forthdictionary.registerFns( BinaryFns ) 307 | 308 | context = Context(dictionary=forthdictionary) 309 | 310 | ############################################################################### 311 | # Our HTTP server to serve up client-side SVFORTH files and provide an RPC 312 | # environment for them. 313 | ############################################################################### 314 | 315 | class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): 316 | pass 317 | 318 | class HTTPHandler(BaseHTTPRequestHandler): 319 | def do_GET(self): 320 | if ( self.path == "/" ): 321 | filePath = "index.html" 322 | elif ( self.path[0:4] == "/%22"): 323 | # Neat side effect is that if we have HTML in the stack 324 | # and evaluate it, it gets sent to the server to retrieve. 325 | filePath = self.path[4:-4] 326 | else: 327 | filePath = self.path[1:] 328 | 329 | # Poor man's proxy for now, which can be a gaping security hole. 330 | if filePath[0:4] == "http": 331 | print( filePath ) 332 | rawData = None 333 | try: 334 | rawData = urllib2.urlopen( filePath ).read() 335 | except: 336 | self.send_response( 404 ) 337 | if rawData: 338 | self.wfile.write( rawData ) 339 | else: 340 | self.send_response( 404 ) 341 | 342 | elif not os.path.isfile( filePath ): 343 | self.send_response(404) 344 | self.end_headers() 345 | else: 346 | self.send_response(200) 347 | self.send_header("Content-type", "text/html") 348 | self.end_headers() 349 | outFile = open(filePath) 350 | self.wfile.write( outFile.read() ) 351 | 352 | def do_POST(self): 353 | global forthdictionary 354 | postSize = self.headers.dict[ 'content-length' ] 355 | inputTokens = json.loads( self.rfile.read( int( postSize ) ) ) 356 | httpSessionDictionary = forthdictionary 357 | httpSessionContext = Context(dictionary=httpSessionDictionary) 358 | print( "GOT RPC REQUEST: %s" % inputTokens ) 359 | try: 360 | httpSessionContext.parser.execute( inputTokens, httpSessionContext ) 361 | except Exception as err: 362 | httpSessionContext.stack.push( "SERVER ERROR: %s" % err ) 363 | self.send_response(200) 364 | self.send_header("Content-type", 'text/data') 365 | self.end_headers() 366 | self.wfile.write( json.dumps( httpSessionContext.stack ) ) 367 | 368 | def HTTPLoop(HandlerClass=HTTPHandler, ServerClass=ThreadedHTTPServer): 369 | test(HandlerClass, ServerClass) 370 | 371 | HTTPLoop() 372 | 373 | running = True 374 | 375 | while running: 376 | userinput = raw_input(">>") 377 | tokens = Tokens( userinput.split(" ") ) 378 | if tokens[0]: 379 | context.parser.execute( tokens, context ) 380 | -------------------------------------------------------------------------------- /forth/binary.js: -------------------------------------------------------------------------------- 1 | // TODO: make this work in node.js 2 | 3 | // RegExp to determine if the string we're looking at is base64 encoded 4 | var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}" + 5 | "==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$"); 6 | 7 | BinaryFns = { 8 | "get-binary": function(context) { 9 | var url = context.stack.pop(); 10 | 11 | function responseIntoStack() { 12 | if (this.readyState == 4) { 13 | if ( typeof(binReq.response !== "undefined") ) { 14 | arrayBuffer = binReq.response; 15 | context.stack.push( arrayBuffer ); 16 | } else if ( typeof(binReq.responseText !== "undefined" ) ) { 17 | // Sometimes the JavaScript environment we're in doesn't understand 18 | // how to work with ArrayBuffers, so we have to deal with it as a 19 | // string object. 20 | arrayBuffer = binReq.responseText; 21 | context.stack.push( arrayBuffer ); 22 | } 23 | } 24 | context.executeCallback( context ); 25 | } 26 | 27 | var binReq = new XMLHttpRequest(); 28 | binReq.onload = responseIntoStack; 29 | binReq.open("GET", url, true); 30 | binReq.responseType = "arraybuffer"; 31 | binReq.send(); 32 | }, 33 | 34 | "get-binary-peinfo": function(context) { 35 | var binary = context.stack.pop(); 36 | context.stack.push( [ binary, "get-binary-peinfo" ] ); 37 | context.tokens = [ '#' ].concat( context.tokens ); 38 | context.executeCallback( context ); 39 | }, 40 | 41 | "ensure-base64": function(context) { 42 | var toBeBase64 = context.stack.pop(); 43 | 44 | // Below functions are from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding#Solution_.232_.E2.80.93_rewriting_atob()_and_btoa()_using_TypedArrays_and_UTF-8 45 | // We are forced to do this, as Safari's window.btoa uses the string 46 | // representation of the ByteArray object i.e. [object ByteArray] rather 47 | // than the actual contents themselves. 48 | function uint6ToB64 (nUint6) { 49 | return nUint6 < 26 ? 50 | nUint6 + 65 51 | : nUint6 < 52 ? 52 | nUint6 + 71 53 | : nUint6 < 62 ? 54 | nUint6 - 4 55 | : nUint6 === 62 ? 56 | 43 57 | : nUint6 === 63 ? 58 | 47 59 | : 60 | 65; 61 | } 62 | 63 | function ab2base64(ba) { 64 | aBytes = new Uint8Array( ba ); 65 | 66 | var nMod3, sB64Enc = ""; 67 | 68 | for (var nLen=aBytes.length, nUint24 =0, nIdx=0; nIdx < nLen; nIdx++) { 69 | nMod3 = nIdx % 3; 70 | //if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } 71 | nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); 72 | if (nMod3 === 2 || aBytes.length - nIdx === 1) { 73 | sB64Enc += String.fromCharCode( 74 | uint6ToB64(nUint24 >>> 18 & 63), 75 | uint6ToB64(nUint24 >>> 12 & 63), 76 | uint6ToB64(nUint24 >>> 6 & 63), 77 | uint6ToB64(nUint24 & 63)); 78 | nUint24 = 0; 79 | } 80 | } 81 | 82 | return( sB64Enc.replace(/A(?=A$|$)/g, "=") ); 83 | } 84 | 85 | console.log( toBeBase64 ); 86 | 87 | if ( base64Matcher.test( toBeBase64 ) ) { 88 | // already base64, looks like, so ignore 89 | context.stack.push( toBeBase64 ); 90 | } else { 91 | // TODO: needs a node.js equivalent 92 | if ( toBeBase64.hasOwnProperty('byteLength') ) { 93 | context.stack.push( ab2base64( toBeBase64 ) ); 94 | } else { 95 | context.stack.push( window.btoa( toBeBase64 ) ); 96 | } 97 | } 98 | context.executeCallback( context ); 99 | }, 100 | 101 | "ensure-binary": function(context) { 102 | // the object to ensure is binary 103 | var toBeBinary = context.stack.pop() 104 | 105 | // we might have received a base64 encoded string, so we need to check 106 | // and convert to a base256 string if needed. 107 | if ( base64Matcher.test( toBeBinary ) ) { 108 | // looks like we've been passed a base64 string, so we convert it 109 | toBeBinary = window.atob( toBeBinary ) 110 | } 111 | 112 | // takes a string and returns an UInt ArrayBuffer version 113 | function str2ab(str) { 114 | var buf = new ArrayBuffer(str.length); // 2 bytes for each char 115 | var bufView = new Uint8Array(buf); 116 | for (var i=0, strLen=str.length; i ( canv.width * canv.height ) ) { 44 | limit=canv.width * canv.height; 45 | } else { 46 | limit=plane.byteLength; 47 | } 48 | return( limit ) 49 | } 50 | 51 | // *********************************************************************** 52 | // JavaScript functions for Forth words 53 | // *********************************************************************** 54 | 55 | // select our HTML canvas to draw on 56 | this.canvas = function(context) { 57 | this.currCanvas = document.getElementById( context.stack.pop() ) 58 | this.currContext = currCanvas.getContext("2d") 59 | context.executeCallback( context ) 60 | } 61 | 62 | // Set our fill color for shapes 63 | this.fillStyle = function(context) { 64 | b = context.stack.pop() 65 | g = context.stack.pop() 66 | r = context.stack.pop() 67 | this.currContext.fillStyle = "rgb(" + [r,g,b].join(",") + ")" 68 | // console.log( "COLOR SET TO:", r, g, b ) 69 | context.executeCallback( context ) 70 | } 71 | 72 | // Draw a rectangle 73 | this.fillRect = function(context) { 74 | y2 = context.stack.pop() 75 | x2 = context.stack.pop() 76 | y1 = context.stack.pop() 77 | x1 = context.stack.pop() 78 | this.currContext.fillRect(x1, y1, x2, y2); 79 | // console.log( "FILL RECT CALLED", this.currContext ); 80 | context.executeCallback( context ); 81 | } 82 | 83 | // Convert HSV float values into UInt RGB values 84 | this.HSVtoRGB = function(context) { 85 | v = context.stack.pop(); 86 | s = context.stack.pop(); 87 | h = context.stack.pop(); 88 | 89 | console.log(h, s, v); 90 | 91 | var r, g, b, i, f, p, q, t; 92 | 93 | i = Math.floor(h * 6); 94 | f = h * 6 - i; 95 | p = v * (1 - s); 96 | q = v * (1 - f * s); 97 | t = v * (1 - (1 - f) * s); 98 | 99 | switch (i % 6) { 100 | case 0: r = v, g = t, b = p; break; 101 | case 1: r = q, g = v, b = p; break; 102 | case 2: r = p, g = v, b = t; break; 103 | case 3: r = p, g = q, b = v; break; 104 | case 4: r = t, g = p, b = v; break; 105 | case 5: r = v, g = p, b = q; break; 106 | } 107 | 108 | context.stack.push( Math.floor( r*255 ) ); 109 | context.stack.push( Math.floor( g*255 ) ); 110 | context.stack.push( Math.floor( b*255 ) ); 111 | 112 | context.executeCallback( context ); 113 | } 114 | 115 | // given three Strings or TypedArray, we draw them onto the current canvas 116 | // as RGB values 117 | this.paintPlanes = function(context) { 118 | b = coerceByteArray( context.stack.pop() ); 119 | g = coerceByteArray( context.stack.pop() ); 120 | r = coerceByteArray( context.stack.pop() ); 121 | 122 | width = currCanvas.width; 123 | height = currCanvas.height; 124 | 125 | redUintArray = new Uint8Array( r ); 126 | greenUintArray = new Uint8Array( g ); 127 | blueUintArray = new Uint8Array( b ); 128 | 129 | limit = getMaxLength( currCanvas, redUintArray ); 130 | 131 | var imageData = currContext.getImageData( 0, 0, width, height ); 132 | var data = imageData.data; 133 | 134 | // Note that we are treating the array as a 1D plane rather than 135 | // calculating the 1D location based on X and Y coordinates for speed. 136 | for (index=0, binIndex=0; index<=(limit * 4); index++) { 137 | data[index] = redUintArray[ binIndex ]; // red 138 | data[++index] = greenUintArray[ binIndex ]; // green 139 | data[++index] = blueUintArray[ binIndex ]; // blue 140 | data[++index] = 255; // alpha 141 | binIndex++; 142 | } 143 | 144 | this.currContext.putImageData(imageData, 0, 0); 145 | 146 | context.executeCallback(context); 147 | } 148 | 149 | // A wrapper function that takes a single object and duplicates it onto 150 | // the stack three times for callout to paint-rgb for a grayscale image. 151 | this.paintBinary = function(context) { 152 | input = context.stack.pop(); 153 | 154 | // We push a *copy* of the input object, using slice() -- doing otherwise 155 | // yields some interesting side effects. 156 | context.stack.push(input.slice(0)); 157 | context.stack.push(input.slice(0)); 158 | context.stack.push(input.slice(0)); 159 | 160 | // Directly call paint-rgb rather than injecting the object onto the 161 | // Forth execution stack. 162 | this.paintPlanes( context ); 163 | } 164 | 165 | // If our HTML document has a 'canvas' element, we select it on 166 | // initialization to make things easier on us. 167 | if ( document.getElementById( 'canvas' ) ) { 168 | currCanvas = document.getElementById( 'canvas' ) 169 | currContext = currCanvas.getContext( "2d" ) 170 | } 171 | } 172 | 173 | canvas = new Canvas(); 174 | 175 | CanvasFns = { 176 | "set-canvas": canvas.canvas, 177 | "set-fill-color": canvas.fillStyle, 178 | "draw-rect": canvas.fillRect, 179 | "paint-grayscale": canvas.paintBinary, 180 | "paint-rgb": canvas.paintPlanes, 181 | "hsv-to-rgb": canvas.HSVtoRGB, 182 | "red": "127 0 0", 183 | "green": "0 127 0", 184 | "blue": "0 0 127" 185 | } 186 | 187 | if (typeof initialDictionary !== 'undefined') { 188 | initialDictionary.registerWords( CanvasFns ); 189 | } -------------------------------------------------------------------------------- /forth/console.js: -------------------------------------------------------------------------------- 1 | if ( typeof(Ractive) == 'undefined') { 2 | importJSLibrary('lib/Ractive.min.js'); 3 | } 4 | 5 | function sanitizeForJSON(toJSON) { 6 | var i = 0; 7 | 8 | return function(key, value) { 9 | if( i !== 0 && typeof( toJSON ) === 'object' && typeof( value ) == 'object' 10 | && toJSON == value ) { 11 | return '[Circular]'; 12 | } 13 | 14 | ++i; 15 | 16 | return( value ); 17 | } 18 | } 19 | 20 | function wrapBuffer(outString, buffer) { 21 | wrapArray = []; 22 | 23 | while ( outString.length > buffer.maxWidth ) { 24 | wrapArray.push( outString.slice(0, buffer.maxWidth) ); 25 | outString = outString.slice(buffer.maxWidth); 26 | } 27 | wrapArray.push( outString ); 28 | return( wrapArray ); 29 | 30 | } 31 | 32 | // Handy JavaScript to meature the size taken to render the supplied text; 33 | // you can supply additional style information too if you have it to hand. 34 | 35 | function measureText(pText, pFontSize, pStyle) { 36 | var lDiv = document.createElement('lDiv'); 37 | 38 | document.body.appendChild(lDiv); 39 | 40 | if (pStyle != null) { 41 | lDiv.style = pStyle; 42 | } 43 | lDiv.style.fontSize = "" + pFontSize + "px"; 44 | lDiv.style.position = "absolute"; 45 | lDiv.style.left = -1000; 46 | lDiv.style.top = -1000; 47 | 48 | lDiv.innerHTML = pText; 49 | 50 | var lResult = { 51 | width: lDiv.clientWidth, 52 | height: lDiv.clientHeight 53 | }; 54 | 55 | document.body.removeChild(lDiv); 56 | lDiv = null; 57 | 58 | return lResult; 59 | } 60 | 61 | function ForthConsole() { 62 | // *********************************************************************** 63 | // JavaScript functions for Forth words 64 | // *********************************************************************** 65 | 66 | var that = this; 67 | 68 | function createForthHooks(screenBuffer, forthBuffer, terminalContainer) { 69 | var forthConsole = {}; 70 | 71 | forthConsole.createOutputHandler = function() { return( 72 | function(item) { 73 | if( screenBuffer.maxLines == screenBuffer.length && 74 | ( screenBuffer.length > 1) ) { 75 | screenBuffer.shift(); 76 | } 77 | if (typeof item == "object") { 78 | outputString = JSON.stringify( item, sanitizeForJSON(item) ) 79 | } else { 80 | outputString = item 81 | } 82 | 83 | wrappedLines = wrapBuffer( outputString, screenBuffer ) 84 | for ( line in wrappedLines ) { 85 | while ( screenBuffer.maxLines - 1 < screenBuffer.length ) { 86 | screenBuffer.shift(); 87 | } 88 | screenBuffer.push( wrappedLines[ line ] ); 89 | forthBuffer.push( wrappedLines[ line ] ); 90 | } 91 | 92 | } ) } ; 93 | 94 | forthConsole.createPrintHandler = function() { return( 95 | function(context) { 96 | item = context.stack.pop(); 97 | if( screenBuffer.maxLines == screenBuffer.length && ( screenBuffer.length > 1 ) ) { 98 | screenBuffer.shift(); 99 | } 100 | if (typeof item == "object") { 101 | outputString = JSON.stringify( item, sanitizeForJSON(item) ) 102 | } else { 103 | outputString = item 104 | } 105 | 106 | wrappedLines = wrapBuffer( outputString, screenBuffer ) 107 | for ( line in wrappedLines ) { 108 | while ( screenBuffer.maxLines - 1 < screenBuffer.length && ( screenBuffer.length > 1 ) ) { 109 | screenBuffer.shift(); 110 | } 111 | screenBuffer.push( wrappedLines[ line ] ); 112 | forthBuffer.push( wrappedLines[ line ] ); 113 | } 114 | context.executeCallback( context ); 115 | } ) }; 116 | 117 | forthConsole.createClearScreenHandler = function() { return( 118 | function(context) { 119 | while( consoleBuffer.length > 0 ) { 120 | consoleBuffer.pop() 121 | } 122 | context.executeCallback( context ); 123 | } ) }; 124 | 125 | forthConsole.createPeekHandler = function() { return( 126 | function(context) { 127 | item = context.stack[context.stack.length-1] 128 | if (typeof screenBuffer != "undefined") { 129 | if( screenBuffer.maxLines == screenBuffer.length ) { 130 | screenBuffer.shift() 131 | } 132 | if (typeof item == "object") { 133 | screenBuffer.push(JSON.stringify(item, censor(item))); 134 | } else { 135 | screenBuffer.push(item); 136 | } 137 | } else { 138 | console.log(item); 139 | } 140 | context.executeCallback( context ); 141 | } ) }; 142 | 143 | forthConsole.createTerminalResizer = 144 | function(forthBuffer, screenBuffer, terminalContainer) { return( 145 | function(context) { 146 | resizeTerminal(screenBuffer, terminalContainer); 147 | while ( screenBuffer.length != 0 ) { 148 | screenBuffer.shift(); 149 | } 150 | 151 | var beginForthBufferRange = ( forthBuffer.length - 152 | screenBuffer.maxLines - 1 ); 153 | 154 | var lineNum = 0; 155 | for ( var lineIndex = beginForthBufferRange; 156 | lineIndex < forthBuffer.length; 157 | lineIndex++ ) { 158 | if ( forthBuffer[ lineIndex ] != undefined ) { 159 | screenBuffer.push( forthBuffer[ lineIndex ] ); 160 | } 161 | lineNum += 1; 162 | } 163 | console.log( screenBuffer ); 164 | }) 165 | }; 166 | 167 | return( forthConsole ); 168 | } 169 | 170 | function registerInputHandler(inputId, screenBuffer, forthBuffer, 171 | commandHistory) { 172 | var handlerId = "Console" + inputId + "Handler" 173 | window[handlerId] = function() { 174 | forthInput = document.getElementById( "ConsoleInput" + inputId ); 175 | 176 | // We create an execution handler based off our startup 177 | // context, initialContext. 178 | newContext = createContext( initialContext ); 179 | newExecutionContext = applyExecutionContext.apply( newContext ); 180 | if ((screenBuffer.maxLines - 1 ) < screenBuffer.length) { 181 | screenBuffer.shift() 182 | } 183 | screenBuffer.push( '$ ' + forthInput.value ); 184 | forthBuffer.push( '$ ' + forthInput.value ); 185 | commandHistory.push( forthInput.value ); 186 | newExecutionContext.execute( forthInput.value ); 187 | forthInput.value = ""; 188 | } 189 | return( handlerId ); 190 | } 191 | 192 | function resizeTerminal(screenBuffer, terminalContainer) { 193 | domObject = document.getElementById( terminalContainer ); 194 | fontSize = domObject.style.pFontSize; 195 | fontFamily = domObject.style.fontFamily; 196 | 197 | fontMeasurements = measureText( "x", fontSize, { 198 | 'font-family': fontFamily } ); 199 | fontWidth = fontMeasurements.width; 200 | fontHeight = fontMeasurements.height; 201 | 202 | screenBuffer.maxCols = Math.floor( 203 | domObject.clientWidth / ( fontWidth ) ) - 1 204 | screenBuffer.maxLines = Math.floor( 205 | domObject.clientHeight / ( fontHeight ) ) - 1 206 | 207 | console.log( "Terminal initialized with size:", 208 | screenBuffer.maxCols, screenBuffer.maxLines ); 209 | } 210 | 211 | function registerTerminalContext(context, screenBuffer, forthBuffer, 212 | terminalContainer ) { 213 | forthConsole = createForthHooks( screenBuffer, forthBuffer, 214 | terminalContainer ); 215 | context.dictionary.registerWords( { 216 | "print": forthConsole.createPrintHandler(), 217 | ".": forthConsole.createPeekHandler(), 218 | "clearscreen": forthConsole.createClearScreenHandler(), 219 | "resize-terminal": forthConsole.createTerminalResizer(forthBuffer, 220 | screenBuffer, terminalContainer ) } ); 221 | context.console = { 'output': forthConsole.createOutputHandler() }; 222 | } 223 | 224 | this.createTerminal = function(context) { 225 | var terminalContainer = context.stack.pop(); 226 | var screenBuffer = context.stack.pop(); 227 | var forthBuffer = []; 228 | 229 | var terminalId = Math.floor((Math.random() * 65536)); 230 | 231 | var commandHistory = []; 232 | 233 | // Register output Forth words in our context to the screenBuffer 234 | // in question. 235 | registerTerminalContext( context, screenBuffer, forthBuffer, 236 | terminalContainer ); 237 | handlerId = registerInputHandler( terminalId, screenBuffer, forthBuffer, 238 | commandHistory ); 239 | 240 | var ractiveParams = {}; 241 | var ractiveData = {}; 242 | ractiveParams[ 'el' ] = terminalContainer; 243 | ractiveParams[ 'template' ] = 244 | [ "", 246 | "", 247 | "{{#Console", terminalId, "}}", 248 | "", 251 | "{{/Console", terminalId, "}}", 252 | "", 253 | "", 257 | "", 258 | "", 259 | "
", 249 | "{{{ . }}}", 250 | "
", 254 | "
" ].join(""); 260 | ractiveData[ 'Console' + terminalId ] = screenBuffer; 261 | ractiveParams[ 'data' ] = ractiveData; 262 | 263 | var terminalReactor = new Ractive(ractiveParams); 264 | 265 | // We figure out the size of our terminal container to determine 266 | // the number of columns and rows. 267 | resizeTerminal( screenBuffer, terminalContainer ); 268 | 269 | context.executeCallback( context ); 270 | 271 | } 272 | } 273 | 274 | forthConsole = new ForthConsole(); 275 | 276 | ConsoleFns = { 277 | 'create-terminal': forthConsole.createTerminal 278 | } 279 | 280 | if (typeof initialDictionary !== 'undefined') { 281 | initialDictionary.registerWords( ConsoleFns ); 282 | } 283 | -------------------------------------------------------------------------------- /forth/database.js: -------------------------------------------------------------------------------- 1 | var pg = require( 'pg' ); 2 | 3 | // database connection object, takes: 4 | // { connParams: connection parameters, usually a connection string 5 | // connType: 'pg' only for now 6 | // connObject: we can use a previous connection object as a spec as well } 7 | // 8 | // This is intended to be inserted onto the stack and used by db query 9 | // functions. As these are objects, duplicating the object is effectively 10 | // reuse of the same database connection. 11 | function createDSObject(spec) { 12 | DSObject = {}; 13 | 14 | if ( 'connParams' in spec ) { DSObject.connParams = spec.connParams } else 15 | { throw( "No 'connParams' in createDSObject spec." ) }; 16 | if ( 'connType' in spec ) { DSObject.connType = spec.connType } else 17 | { DSObject.connType = 'pg' }; 18 | if ( 'connObject' in spec ) { DSObject.connObject = spec.connObject } else 19 | { DSObject.connObject = new pg.Client( DSObject.connParams ); 20 | DSObject.connObject.connect(); }; 21 | 22 | DSObject.query = function(context) { 23 | var currTime = new Date().getTime() / 1000; 24 | 25 | inParameters = context.stack.pop(); 26 | inQuery = context.stack.pop(); 27 | 28 | var currQuery = this.connObject.query( 29 | { text: inQuery, 30 | values: inParameters }, 31 | function(err, result) { 32 | }); 33 | 34 | // For each row, we insert into the stack. 35 | currQuery.on('row', function( row ) { 36 | // row.beginRowTime = new Date().getTime() / 1000; 37 | context.stack.push( row ); 38 | // row.endRowTime = new Date().getTime() / 1000; 39 | // console.log( "Row processed in " + \ 40 | // ( row.endRowTime - row.beginRowTime ) + "s" ); 41 | }); 42 | 43 | // Once we're done, we close up and return execution to Forth. 44 | currQuery.on('end', function() { 45 | endTime = new Date().getTime() / 1000; 46 | console.log( "Query done in " + 47 | (endTime - currTime) + "seconds" ) 48 | context.executeCallback( context ); 49 | }); 50 | } 51 | 52 | return( DSObject ); 53 | }; 54 | 55 | DatabaseFns = { 56 | // create-dbconn ( $connection-string -- dbConnObject ) 57 | // 58 | // given a Postgres connection string such as 'postgres://user@dbhost/DB' 59 | // create a dbConnection object and insert it into the stack. 60 | "create-dbconn": function(context) { 61 | connParams = context.stack.pop(); 62 | context.stack.push( createDSObject( { connParams: connParams } ) ); 63 | context.executeCallback( context ); 64 | }, 65 | 66 | // query-db ( $query [ parameters ] dbConnObject -- row0 .. rowN ) 67 | // 68 | // given a SQL query in a string, the parameters for the query in an array, 69 | // and a database connection object, execute the query and return rows. 70 | "query-db": function(context) { 71 | dbObject = context.stack.pop(); 72 | dbObject.query(context); 73 | } 74 | }; 75 | 76 | // direct SQL DB access from the browser? you're smoking crack. 77 | // 78 | // if (typeof initialDictionary !== 'undefined') { 79 | // initialDictionary.registerWords( DatabaseFns ); 80 | // } 81 | 82 | if (typeof module != 'undefined' ) { 83 | module.exports.DatabaseFns = DatabaseFns; 84 | } 85 | 86 | -------------------------------------------------------------------------------- /forth/ds.js: -------------------------------------------------------------------------------- 1 | if ( typeof DOMParser === undefined ) { 2 | var DOMParser = require('xmldom').DOMParser; 3 | } 4 | 5 | // Method to support various mechanisms to load a library depending on 6 | // environment. 7 | function importJSLibrary(library) { 8 | // If window is undefined, then it's probably a node.js instance which 9 | // imports using 'require'. 10 | if (typeof window == 'undefined') { 11 | require("./" + library) 12 | } else { 13 | // We're probably a browser, so we inject our script load into the DOM. 14 | var body = document.body; 15 | var script = document.createElement('script'); 16 | script.type = 'text/javascript'; 17 | script.src = library; 18 | body.appendChild(script); 19 | } 20 | } 21 | 22 | // We have a much more secure and sane way to deal with JSON parsing that 23 | // doesn't use eval(). 24 | importJSLibrary( '../lib/json.js' ) 25 | 26 | // Given an XML DOM object, we convert it to a JavaScript data structure 27 | function xml2js(node) { 28 | var data = {}; 29 | 30 | // append a value 31 | function Add(name, value) { 32 | if (data[name]) { 33 | if (data[name].constructor != Array) { 34 | data[name] = [data[name]]; 35 | } 36 | data[name][data[name].length] = value; 37 | } 38 | else { 39 | data[name] = value; 40 | } 41 | }; 42 | 43 | // element attributes 44 | var c, cn; 45 | for (c = 0; cn = node.attributes[c]; c++) { 46 | Add(cn.name, cn.value); 47 | } 48 | 49 | // child elements 50 | for (c = 0; cn = node.childNodes[c]; c++) { 51 | if (cn.nodeType == 1) { 52 | if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) { 53 | // text value 54 | Add(cn.nodeName, cn.firstChild.nodeValue); 55 | } 56 | else { 57 | // sub-object 58 | Add(cn.nodeName, xml2js(cn)); 59 | } 60 | } 61 | } 62 | 63 | return( data ); 64 | } 65 | 66 | DataStructureFns = { 67 | // xml-to-ds ( xml-string -- js-ds ) 68 | // 69 | // Given an XML string, convert it and push onto the stack a JavaScript 70 | // data structure representation. 71 | "xml-to-ds": function( context ) { 72 | xml = new DOMParser().parseFromString( context.stack.pop(), 'text/xml' ); 73 | ds = xml2js( xml.documentElement ); 74 | context.stack.push( ds ); 75 | context.executeCallback( context ); 76 | }, 77 | 78 | // ds-length ( js-ds -- length ) 79 | // 80 | // Given an DS, get the length of the element, whether it's an array, or 81 | // a string and push it onto the stack. 82 | "ds-length": function( context ) { 83 | item = context.stack.pop() 84 | context.stack.push( item.length ) 85 | context.executeCallback( context ); 86 | }, 87 | 88 | // ds-get ( js-ds index -- item ) 89 | // 90 | // Given a DS, get the item at index, and push it onto the stack. 91 | // 92 | // Examples: 93 | // [ 'a' 'b' ] 1 ds-get --> 'b' 94 | // { a: 0, b: 1 } a ds-get --> 0 95 | // 96 | "ds-get": function( context ) { 97 | index = context.stack.pop() 98 | item = context.stack.pop() 99 | context.stack.push( item[ index ] ) 100 | context.executeCallback( context ); 101 | }, 102 | 103 | // ds-put ( js-ds index item -- js-ds ) 104 | // Given a DS, put the item at the index. 105 | // 106 | // Examples: 107 | // [ 'a' 'b' ] c 2 ds-put --> [ 'a' 'b' 'c' ] 108 | // { a: 0, b: 1 } 2 c ds-put --> { a: 0, b: 1, c: 2 } 109 | 110 | "ds-put": function( context ) { 111 | index = context.stack.pop(); 112 | item = context.stack.pop(); 113 | ds = context.stack.pop(); 114 | ds[ index ] = item; 115 | context.stack.push( ds ); 116 | context.executeCallback( context ); 117 | }, 118 | 119 | 120 | // ds-get-all ( js-ds -- item0 item1 ... ) 121 | // 122 | // Given a DS, iterate through the DS and fetch the element contained 123 | // at each item. 124 | // 125 | // Examples: 126 | // [ { a: 0, b: 1 } { a: 1, b: 2 } { a: 'x', b: 3 } ] 'a' ds-get-all --> 127 | // 0 1 'x' 128 | // 129 | "ds-get-all": function( context ) { 130 | index = context.stack.pop(); 131 | item = context.stack.pop(); 132 | for (var i in item) { 133 | try { 134 | context.stack.push( item[i][index] ); 135 | } 136 | catch(e) { 137 | // If we don't find the index, we just skip this error. 138 | } 139 | } 140 | context.executeCallback( context ); 141 | }, 142 | 143 | // push-array ( array item -- array ) 144 | // 145 | // Given a DS, push the item off the stack onto the array 146 | "push-array": function( context ) { 147 | item = context.stack.pop(); 148 | arr = context.stack.pop(); 149 | arr.push( item ); 150 | context.stack.push( arr ); 151 | context.executeCallback( context ); 152 | }, 153 | 154 | // json-to-ds ( json -- ds ) 155 | "json-to-ds": function( context ) { 156 | jsonItem = context.stack.pop(); 157 | context.stack.push( jsonParse( jsonItem ) ); 158 | context.executeCallback( context ); 159 | } 160 | 161 | } 162 | 163 | if (typeof initialDictionary !== 'undefined') { 164 | initialDictionary.registerWords( DataStructureFns ); 165 | } 166 | 167 | if (typeof module != 'undefined' ) { 168 | module.exports.DataStructureFns = DataStructureFns; 169 | } -------------------------------------------------------------------------------- /forth/node.js: -------------------------------------------------------------------------------- 1 | process.stdin.resume(); 2 | process.stdin.setEncoding('utf8'); 3 | 4 | var forth = require( '../forth.js' ); 5 | var ds = require( './ds.js' ); 6 | var url = require( './url.js' ); 7 | var database = require( './database.js' ); 8 | var server = require( './server.js' ); 9 | 10 | forth.initialDictionary.registerWords( ds.DataStructureFns ); 11 | forth.initialDictionary.registerWords( url.URLFns ); 12 | forth.initialDictionary.registerWords( database.DatabaseFns ); 13 | forth.initialDictionary.registerWords( server.ServerFns ); 14 | 15 | initialContext = forth.createContext( { dictionary: forth.initialDictionary } ); 16 | executionContext = forth.applyExecutionContext.apply( initialContext ); 17 | executionContext.load( 'forth/rss.f' ); 18 | executionContext.load( 'site.f' ); 19 | 20 | console.log( forth.initialDictionary.definitions ); 21 | 22 | function parseInput(data) { 23 | executionContext.execute(data); 24 | process.stdout.write(">> "); 25 | } 26 | 27 | function prompt(callback) { 28 | process.stdout.write(">> "); 29 | process.stdin.on('data', function(data) { 30 | data = data.toString().trim(); 31 | callback(data); 32 | }); 33 | } 34 | 35 | prompt(parseInput); 36 | -------------------------------------------------------------------------------- /forth/rss.f: -------------------------------------------------------------------------------- 1 | ( get-rss url -- ds 2 | given a RSS feed URL, we fetch and parse the XML dom into DS ) 3 | : get-rss 4 | get-http ( fetch our RSS XML feed into the stack ) 5 | xml-to-ds ( convert our RSS into JS DS ) 6 | ; 7 | 8 | ( get-rss-links url -- link1 link2 .. 9 | given a RSS feed URL, we fetch and parse the links within onto the stack ) 10 | : get-rss-links 11 | get-rss ( get our RSS feed as a JS DS ) 12 | channel ds-get ( extract the 'channel' subelement ) 13 | item ds-get ( extract the 'item' subelement ) 14 | link ds-get-all ( extract all 'link' subelements ) 15 | ; -------------------------------------------------------------------------------- /forth/server.js: -------------------------------------------------------------------------------- 1 | var http = require('http'); 2 | var jsonParse = require('../lib/json.js'); 3 | var forth = require('../forth.js'); 4 | 5 | function createPipeFunction(dest) { 6 | return( function(context) { 7 | dest.write( JSON.stringify( context.stack ) ) 8 | dest.end() 9 | } ); 10 | }; 11 | 12 | ServerFns = { "start-server": function(context) { 13 | http.createServer(function (request, response) { 14 | response.writeHead(200, { 'Access-Control-Allow-Origin': '*'} ) 15 | request.on('data', function(data) { 16 | console.log(jsonParse.jsonParse(data.toString())); 17 | 18 | newContext = forth.createContext( context ); 19 | newExecutionContext = forth.applyExecutionContext.apply( newContext ); 20 | 21 | pipeArtifacts = createPipeFunction( response ); 22 | 23 | // Each RPC call starts with a new stack. 24 | newContext.stack = []; 25 | // We inject our callback into the token stream. 26 | newContext.tokens = [ pipeArtifacts ]; 27 | 28 | newExecutionContext.execute( jsonParse.jsonParse( data.toString() ) ); 29 | }); 30 | if ( request.method === "GET" ) { 31 | if ( request.url === "/" ) { 32 | filePath = "index.html"; 33 | } else { 34 | filePath = "./" + request.url; 35 | } 36 | content = fs.createReadStream( filePath ); 37 | content.on( 'data', function (data) { 38 | response.write( data ); 39 | }); 40 | content.on( 'end', function () { 41 | response.end(); 42 | }); 43 | }; 44 | console.log( request.url, request.method ); 45 | } ).listen(8000, '127.0.0.1'); 46 | console.log( "Server started." ); 47 | context.executeCallback( context ); 48 | } 49 | } 50 | 51 | if (typeof module != 'undefined' ) { 52 | module.exports.ServerFns = ServerFns; 53 | } -------------------------------------------------------------------------------- /forth/url.js: -------------------------------------------------------------------------------- 1 | URLFns = { 2 | "get-url": function( context ) { 3 | function responseIntoStack() { 4 | if (this.readyState == 4) { 5 | context.stack.push( req.responseText ); 6 | } 7 | context.executeCallback( context ); 8 | } 9 | 10 | url = context.stack.pop(); 11 | 12 | var req = new XMLHttpRequest(); 13 | req.onload = responseIntoStack; 14 | req.open( "GET", url, true ); 15 | req.send(); 16 | }, 17 | 18 | // get-http ( url get-http -- object ) 19 | // 20 | // This is where things get interesting -- we pick what function the Forth 21 | // word 'get-url' is associated with depending on if we're a browser 22 | // environment or a node.js environment. 23 | // we have to do this remotely as Cross-Browser Origin Reference policies 24 | // do not let us fetch URLs ourselves. 25 | "get-http": function( context ) { 26 | url = context.stack.pop(); 27 | 28 | // context.execute( [ "[", url, "get-http", "]", "#" ] ); 29 | 30 | context.tokens = [ [ url, "get-http" ], "#" ].concat( context.tokens ); 31 | context.executeCallback( context ); 32 | 33 | //newContext = applyExecutionContext.apply( createContext( context ) ); 34 | //newContext.execute( , context ); 35 | } 36 | } 37 | 38 | // If we're node.js, we redefine our 'get-http' call to one that works with 39 | // our environment which does not have XMLHttpRequest by default. 40 | if ( typeof window === 'undefined' ) { 41 | var http = require('http'); 42 | URLFns[ 'get-http' ] = function( context ) { 43 | url = context.stack.pop() 44 | var req = http.request(url, function(res) { 45 | var respBuffer = ""; 46 | res.setEncoding('utf8'); 47 | res.on('end', function() { 48 | context.stack.push( respBuffer ); 49 | context.executeCallback( context ); 50 | }); 51 | res.on('data', function(data) { 52 | console.log( data ); 53 | respBuffer += data; 54 | }); 55 | }); 56 | req.end(); 57 | } 58 | }; 59 | 60 | if (typeof initialDictionary !== 'undefined') { 61 | initialDictionary.registerWords( URLFns ); 62 | } 63 | 64 | if (typeof module != 'undefined' ) { 65 | module.exports.URLFns = URLFns; 66 | } -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | SVFORTH 8 | 9 | 10 | 11 | 12 |
13 | 14 |
15 |
16 |
17 |
18 |
19 | 20 | 21 | 22 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ephsec/svforth/8ba649ba4141a8ea4f833baa7128796516c74e88/lib/__init__.py -------------------------------------------------------------------------------- /lib/forth-helpers.js: -------------------------------------------------------------------------------- 1 | function executeCallback(callback) 2 | { 3 | if( typeof callback != 'undefined' ) { 4 | callback(); 5 | } 6 | } 7 | 8 | function Word( name, fn ) 9 | { 10 | dictionary.register( name, fn ); 11 | } 12 | 13 | byteArrayToHex = function(byteArray) { 14 | value = '\\x' + byteArray.toString('hex'); 15 | return value; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /lib/json.js: -------------------------------------------------------------------------------- 1 | jsonParse=function(){var r="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",k='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';k='(?:"'+k+'*")';var s=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+r+"|"+k+")","g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),u={'"':'"',"/":"/","\\":"\\",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"};function v(h,j,e){return j?u[j]:String.fromCharCode(parseInt(e,16))}var w=new String(""),x=Object.hasOwnProperty;return function(h, 2 | j){h=h.match(s);var e,c=h[0],l=false;if("{"===c)e={};else if("["===c)e=[];else{e=[];l=true}for(var b,d=[e],m=1-l,y=h.length;m=0;)delete f[i[g]]}return j.call(n,o,f)};e=p({"":e},"")}return e}}(); 4 | if(typeof window == 'undefined'){exports.jsonParse=jsonParse}else{window.jsonParse=jsonParse}; 5 | -------------------------------------------------------------------------------- /malware.rss: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Malware Samples 5 | A Bunch of Malware Samples 6 | http://svforth.forth/malware.rss 7 | 8 | IRC Test 9 | Classic IRC Test EXE 10 | irc-test.exe 11 | 12 | 13 | A Nacha Zeus Variant 14 | Nacha Zeus 15 | nacha_zeus.exe 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { "name": "svforth", 2 | "version": "1.0.0", 3 | "repository": { 4 | "type": "git", 5 | "url": "git://github.com/ephsec/svforth.git" 6 | }, 7 | "author": { 8 | "name": "Wes Brown", 9 | "email": "wbrown@ephemeralsecurity.com" 10 | }, 11 | "dependencies": { 12 | "pg" : "2.6.2" 13 | } 14 | } 15 | 16 | 17 | -------------------------------------------------------------------------------- /rsrc/svforth.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0px; 3 | padding: 0px; 4 | background: #000000; 5 | } 6 | 7 | body { 8 | height: 95%; 9 | } 10 | 11 | .ForthCanvas { 12 | position: absolute; 13 | top: 0; 14 | left: 0; 15 | width: 100%; 16 | height: 79%; 17 | } 18 | 19 | .Console { 20 | position: absolute; 21 | bottom: 0; 22 | left: 0; 23 | width: 100%; 24 | height: 20%; 25 | } 26 | 27 | .term { 28 | font-family: monospace; 29 | font-size: 16px; 30 | color: #33d001; 31 | background: none; 32 | } 33 | 34 | .prompt { 35 | font-family: monospace; 36 | white-space: nowrap; 37 | color: #33d001; 38 | -webkit-box-orient: horizontal; 39 | -webkit-box-align: stretch; 40 | display: box; 41 | box-orient: horizontal; 42 | box-align: stretch; 43 | clear: both; 44 | font-size: 16px; 45 | background-color: transparent; 46 | outline: none; 47 | border-style: none; 48 | } 49 | 50 | .prompt:focus { 51 | outline:0; 52 | } 53 | 54 | .screen { 55 | margin:0px; 56 | } 57 | 58 | .divider { 59 | position: absolute; 60 | left: 0; 61 | bottom: 20%; 62 | width: 100%; 63 | height: 0.25%; 64 | padding: 0px; 65 | border-bottom: 1px solid rgba(0,0,0,0.3); 66 | border-top: 1px solid rgba(255,255,255,0.2); 67 | background: #a90329; /* Old browsers */ 68 | } -------------------------------------------------------------------------------- /site.f: -------------------------------------------------------------------------------- 1 | ( our site-specific autostart file for node.js svforth ) 2 | 3 | start-server ( start our RPC and content server on port 8000 ) 4 | --------------------------------------------------------------------------------