├── .gitignore ├── .gitmodules ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── kernel ├── arch │ ├── dev │ │ ├── mod.rs │ │ ├── pic.rs │ │ ├── pit.rs │ │ └── port_io.rs │ ├── mod.rs │ └── x86_64 │ │ ├── boot │ │ ├── boot.asm │ │ └── long_mode.asm │ │ ├── gdt.rs │ │ ├── grub.cfg │ │ ├── idt.rs │ │ ├── int │ │ ├── int.rs │ │ ├── isr.asm │ │ ├── isr.rs │ │ └── mod.rs │ │ ├── linker.ld │ │ ├── mem │ │ ├── entry.rs │ │ ├── frame.rs │ │ ├── mod.rs │ │ └── table.rs │ │ └── mod.rs ├── driver │ ├── com.rs │ ├── kbd.rs │ ├── mod.rs │ └── vga.rs ├── lib.rs └── utils │ ├── mod.rs │ └── qemu.rs └── x86_64-rustbucket_os.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | # Vim swap files 13 | **/*.swp 14 | 15 | # Ignore build directory 16 | build 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "multiboot2"] 2 | path = multiboot2 3 | url = https://github.com/Adam-Gleave/multiboot2-rs 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustbucket_os" 3 | version = "0.0.1" 4 | authors = ["Adam Gleave "] 5 | 6 | [lib] 7 | crate-type = ["staticlib"] 8 | path = "kernel/lib.rs" 9 | 10 | [dependencies] 11 | rlibc = "1.0" 12 | multiboot2 = { git = "https://github.com/Adam-Gleave/multiboot2-rs" } 13 | bitflags = "1.0.4" 14 | 15 | [dependencies.lazy_static] 16 | version = "0.2.1" 17 | features = ["spin_no_std"] 18 | 19 | [profile.dev] 20 | debug = true 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | arch ?= x86_64 2 | kernel := build/kernel-$(arch).bin 3 | iso := build/os-$(arch).iso 4 | target ?= $(arch)-rustbucket_os 5 | rust_os := target/$(target)/debug/librustbucket_os.a 6 | 7 | linker_script := kernel/arch/$(arch)/linker.ld 8 | grub_cfg := kernel/arch/$(arch)/grub.cfg 9 | 10 | assembly_boot_files := $(wildcard kernel/arch/$(arch)/boot/*.asm) 11 | assembly_boot_o_files := $(patsubst kernel/arch/$(arch)/boot/%.asm, \ 12 | build/arch/$(arch)/boot/%.o, $(assembly_boot_files)) 13 | 14 | assembly_int_files := $(wildcard kernel/arch/$(arch)/int/*.asm) 15 | assembly_int_o_files := $(patsubst kernel/arch/$(arch)/int/%.asm, \ 16 | build/arch/$(arch)/int/%.o, $(assembly_int_files)) 17 | 18 | .PHONY: all clean run run-log run-test run-test-hidden iso kernel 19 | 20 | all: $(kernel) $(iso) 21 | 22 | clean: 23 | @rm -r build 24 | 25 | run: $(iso) 26 | qemu-system-x86_64 -cdrom $(iso) 27 | 28 | run-log: $(iso) 29 | qemu-system-x86_64 -cdrom $(iso) -serial mon:stdio 30 | 31 | run-test: $(iso) 32 | qemu-system-x86_64 -cdrom $(iso) \ 33 | -serial mon:stdio \ 34 | -device isa-debug-exit,iobase=0xf4,iosize=0x04 \ 35 | 36 | run-test-hidden: $(iso) 37 | qemu-system-x86_64 -cdrom $(iso) \ 38 | -serial mon:stdio \ 39 | -device isa-debug-exit,iobase=0xf4,iosize=0x04 40 | -display none 41 | 42 | iso: $(iso) 43 | 44 | $(iso): $(kernel) $(grub_cfg) 45 | @mkdir -p build/isofiles/boot/grub 46 | @cp $(kernel) build/isofiles/boot/kernel.bin 47 | @cp $(grub_cfg) build/isofiles/boot/grub 48 | grub-mkrescue -o $(iso) build/isofiles 2> /dev/null 49 | @rm -r build/isofiles 50 | 51 | $(kernel): kernel $(rust_os) $(assembly_boot_o_files) $(assembly_int_o_files) $(linker_script) 52 | ld -n --gc-sections -T $(linker_script) -o $(kernel) \ 53 | $(rust_os) --start-group $(assembly_int_o_files) $(assembly_boot_o_files) $(rust_os) --end-group 54 | 55 | kernel: 56 | @RUST_TARGET_PATH="$(pwd)" xargo build --target $(target) 57 | 58 | # compile assembly files 59 | build/arch/$(arch)/boot/%.o: kernel/arch/$(arch)/boot/%.asm 60 | @mkdir -p $(shell dirname $@) 61 | @nasm -f elf64 $< -o $@ 62 | 63 | build/arch/$(arch)/int/%.o: kernel/arch/$(arch)/int/%.asm 64 | @mkdir -p $(shell dirname $@) 65 | @nasm -f elf64 $< -o $@ 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | rustbucket 3 |

4 | 5 | # rustbucket 6 | Tiny experimental kernel written in Rust and x86 assembly language. Purely for educational purposes. Inspiration take from [OSDev](http://wiki.osdev.org/Main_Page), [Philipp Oppermann](https://os.phil-opp.com/set-up-rust/), and [Bare Metal Rust](http://www.randomhacks.net/bare-metal-rust/). 7 | 8 | ### Build 9 | RustBucket is written using Rust, and therefore needs rust (and Cargo) to be installed in order to build properly. To do so, use the script [here](http://rustup.rs/), if on Linux or UNIX. For Windows, there are further instructions on the website. Since the kernel makes use of the [no_std] attribute (since the standard library cannot be implemented, we must recreate one), the __nightly__ toolkit must be used. Xargo (a cross-compiler extension to cargo), must also be installed, so that rlib (a Rust implementation of libc) can be built for the system. QEMU must also be installed if you wish to run the resultant .iso image in an emulator. After retrieving these packages, open a terminal in the root of this directory, and run the following commands: 10 | 11 | ``rustup override add nightly``: switch to the nightly Rust toolkit. 12 | ``rustup component add rust-src``: needed for xargo to work correctly. 13 | Make sure your PATH variable is set. 14 | 15 | Once these have been installed and set up correctly, run ``make run`` to boot into the kernel with QEMU. 16 | -------------------------------------------------------------------------------- /kernel/arch/dev/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod pic; 2 | pub mod pit; 3 | pub mod port_io; 4 | 5 | use driver::vga; 6 | use core::fmt::Write; 7 | use driver::vga::Writer; 8 | 9 | pub fn pic_init() { 10 | unsafe { 11 | //start the initialisation of the PICs 12 | port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4); 13 | port_io::wait(); 14 | port_io::outb(pic::PIC_SLAVE_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4); 15 | port_io::wait(); 16 | 17 | //provide the PIC vector offsets 18 | port_io::outb(pic::PIC_MASTER_DATA, pic::PIC_OFFSET_MASTER); 19 | port_io::wait(); 20 | port_io::outb(pic::PIC_SLAVE_DATA, pic::PIC_OFFSET_SLAVE); 21 | port_io::wait(); 22 | 23 | //provide slave/master relationship information 24 | port_io::outb(pic::PIC_MASTER_DATA, 4); //inform MASTER there is a SLAVE at IRQ2 25 | port_io::wait(); 26 | port_io::outb(pic::PIC_SLAVE_DATA, 2); //inform SLAVE it is a cascade identity 27 | port_io::wait(); 28 | 29 | //provide additional environment information 30 | port_io::outb(pic::PIC_MASTER_DATA, pic::ICW4_8086); //operate in 8086 mode 31 | port_io::wait(); 32 | port_io::outb(pic::PIC_SLAVE_DATA, pic::ICW4_8086); //operate in 8086 mode 33 | port_io::wait(); 34 | 35 | //mask all interrupts, since none are currently initialised 36 | port_io::outb(pic::PIC_MASTER_DATA, 0xFF); 37 | port_io::outb(pic::PIC_SLAVE_DATA, 0xFF); 38 | 39 | pic::irq_set_mask(0, false); 40 | pic::irq_set_mask(1, false); 41 | } 42 | 43 | vga::okay(); 44 | vga::println("Initialised the PIC, at an offset of 0x20"); 45 | } 46 | 47 | pub fn pit_init(hz: u32) { 48 | pit::set_phase(hz); 49 | vga::okay(); 50 | write!(Writer::new(), "Initialised the PIT, at a phase of {:#} Hz\n", hz) 51 | .expect("Unexpected failure in write!()"); 52 | } 53 | -------------------------------------------------------------------------------- /kernel/arch/dev/pic.rs: -------------------------------------------------------------------------------- 1 | //pic.rs 2 | //contains methods to configure the PIC, ready for interrupts 3 | //also contains means to communicate with the PIC one it has been initialised 4 | 5 | use arch::dev::port_io; 6 | 7 | //define constants (port numbers) 8 | pub const PIC_MASTER: u16 = 0x20; 9 | pub const PIC_SLAVE: u16 = 0xA0; 10 | pub const PIC_MASTER_COMMAND: u16 = PIC_MASTER; 11 | pub const PIC_MASTER_DATA: u16 = PIC_MASTER + 1; 12 | pub const PIC_SLAVE_COMMAND: u16 = PIC_SLAVE; 13 | pub const PIC_SLAVE_DATA: u16 = PIC_SLAVE + 1; 14 | 15 | //code for EOI (end of interrupt) signal 16 | pub const EOI: u8 = 0x20; 17 | 18 | //codes needed for PIC initialisation 19 | pub const ICW1_ICW4: u8 = 0x01; //states whether ICW4 is needed 20 | pub const ICW1_SINGLE: u8 = 0x02; //operate in single (cascade) mode 21 | pub const ICW1_INTERVAL4: u8 = 0x04; //call address interval 4 (8) 22 | pub const ICW1_LEVEL: u8 = 0x08; //level triggered (edge) mode 23 | pub const ICW1_INIT: u8 = 0x10; //REQUIRED: start initialisation 24 | 25 | //codes needed for further init steps 26 | pub const ICW4_8086: u8 = 0x01; //8086 mode flag 27 | pub const ICW4_AUTO: u8 = 0x02; //auto EOI 28 | pub const ICW4_BUFFER_SLAVE: u8 = 0x08; //buffered mode (slave) 29 | pub const ICW4_BUFFER_MASTER: u8 = 0x0C; //buffered mode (master) 30 | pub const ICW4_SFNM: u8 = 0x10; //special (not) fully nested 31 | 32 | //codes needed to read ISR/IRR 33 | pub const OCW3_IRR: u8 = 0x0a; 34 | pub const OCW3_ISR: u8 = 0x0b; 35 | 36 | //PIC vector offsets 37 | pub const PIC_OFFSET_MASTER: u8 = 32; //offset the PIC indexes by 32 38 | pub const PIC_OFFSET_SLAVE: u8 = PIC_OFFSET_MASTER + 8; 39 | 40 | //send an EOI to the necessary PIC to acknowledge end of interrupt 41 | pub fn ack(irq: u8) { 42 | unsafe { 43 | //not a valid irq index 44 | if irq >= 16 { 45 | return; 46 | } 47 | 48 | //irq at slave PIC (PIC2) 49 | if irq >= 8 { 50 | port_io::outb(PIC_SLAVE_COMMAND, EOI); 51 | } 52 | //must always call EOI at master PIC (PIC1) 53 | port_io::outb(PIC_MASTER_COMMAND, EOI); 54 | } 55 | } 56 | 57 | //mask or unmask a specific irq in the PIC 58 | pub fn irq_set_mask(mut irq: u8, enable: bool) { 59 | unsafe { 60 | let port; 61 | let value; 62 | 63 | //determine port (PIC) to alter masks at 64 | if irq < 8 { 65 | port = PIC_MASTER_DATA; 66 | } else if irq < 16 { 67 | port = PIC_SLAVE_DATA; 68 | irq -= 8; 69 | } else { 70 | return; //not a valid irq 71 | } 72 | 73 | //alter masks accordingly and send to correct PIC 74 | if !enable { 75 | value = port_io::inb(port) & !(1 << irq); 76 | port_io::outb(port, value); 77 | } else { 78 | value = port_io::inb(port) | (1 << irq); 79 | port_io::outb(port, value); 80 | } 81 | } 82 | } 83 | 84 | fn pic_get_irq_reg(ocw3: u8) -> u16 { 85 | unsafe { 86 | port_io::outb(PIC_MASTER_COMMAND, ocw3); 87 | port_io::outb(PIC_SLAVE_COMMAND, ocw3); 88 | let val: u16 = ((port_io::inb(PIC_SLAVE_COMMAND) as u16) << 8) | 89 | port_io::inb(PIC_MASTER_COMMAND) as u16; 90 | return val; 91 | } 92 | } 93 | 94 | //retrieve the combined IRR registers of the PICs 95 | pub fn pic_get_irr() -> u16 { 96 | return pic_get_irq_reg(OCW3_IRR); 97 | } 98 | 99 | //retrieve the combine ISR registers of the PICs 100 | pub fn pic_get_isr() -> u16 { 101 | return pic_get_irq_reg(OCW3_ISR); 102 | } 103 | -------------------------------------------------------------------------------- /kernel/arch/dev/pit.rs: -------------------------------------------------------------------------------- 1 | //pit.rs 2 | //contains methods to program the Programmable Interval Timer 3 | 4 | use arch::dev::port_io; 5 | 6 | pub static mut RATE: u32 = 0; 7 | pub static mut TICKS: u32 = 0; 8 | 9 | //port addresses 10 | pub const CMD: u16 = 0x43; 11 | pub const DATA_0: u16 = 0x40; 12 | pub const DATA_1: u16 = 0x41; 13 | pub const DATA_2: u16 = 0x42; 14 | 15 | //max phase rate of pit 16 | pub const MAX_RATE: u32 = 1193180; 17 | 18 | pub fn set_phase(hz: u32) { 19 | let divisor = MAX_RATE / hz; 20 | 21 | unsafe { 22 | RATE = hz; 23 | 24 | port_io::outb(CMD, (3 << 1) | (3 << 4)); //channel 0, least + most significant byte 25 | port_io::outb(DATA_0, (divisor & 0xFF) as u8); //low 26 | port_io::outb(DATA_0, (divisor >> 8) as u8); //high 27 | } 28 | } 29 | 30 | pub fn timer_wait(ms: u32) { 31 | unsafe { 32 | while TICKS < ms {} 33 | TICKS = 0; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /kernel/arch/dev/port_io.rs: -------------------------------------------------------------------------------- 1 | //port_io.rs 2 | //describes methods required to send and receive information from system io ports 3 | 4 | #[inline(always)] 5 | pub unsafe fn outb(port: u16, val: u8) { 6 | asm!("outb %al, %dx" :: 7 | "{dx}"(port), "{al}"(val) :: 8 | "volatile"); 9 | } 10 | 11 | #[inline(always)] 12 | pub unsafe fn outw(port: u16, val: u16) { 13 | asm!("outw %ax, %dx" :: 14 | "{dx}"(port), "{ax}"(val) :: 15 | "volatile"); 16 | } 17 | 18 | #[inline(always)] 19 | pub unsafe fn outl(port: u16, val: u32) { 20 | asm!("outl %eax, %dx" :: 21 | "{dx}"(port), "{eax}"(val) :: 22 | "volatile"); 23 | } 24 | 25 | #[inline(always)] 26 | pub unsafe fn inb(port: u16) -> u8 { 27 | let val; 28 | 29 | asm!("inb %dx, %al" : 30 | "={al}"(val) : "{dx}"(port) : 31 | "al" : 32 | "volatile"); 33 | 34 | val 35 | } 36 | 37 | #[inline(always)] 38 | pub unsafe fn inw(port: u16) -> u16 { 39 | let val; 40 | 41 | asm!("inw %dx, %ax" : 42 | "={ax}"(val) : "{dx}"(port) : 43 | "ax" : 44 | "volatile"); 45 | 46 | val 47 | } 48 | 49 | #[inline(always)] 50 | pub unsafe fn inl(port: u16) -> u32 { 51 | let val; 52 | 53 | asm!("inb %dx, %eax" : 54 | "={eax}"(val) : "{dx}"(port) : 55 | "eax" 56 | : "volatile"); 57 | 58 | val 59 | } 60 | 61 | #[inline(always)] 62 | pub unsafe fn wait() { 63 | let mut i = 0; 64 | 65 | while i < 150 { 66 | i = i + 1; 67 | } 68 | } 69 | 70 | #[inline(always)] 71 | pub unsafe fn wait_for(count: u16) { 72 | let mut i = 0; 73 | 74 | while i < count { 75 | i = i + 1; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /kernel/arch/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod x86_64; 2 | pub mod dev; 3 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/boot/boot.asm: -------------------------------------------------------------------------------- 1 | ; boot.asm 2 | 3 | ; x86 assembly file, prints "OK" to screen if kernel is compatible 4 | ; with the systems CPU 5 | 6 | ; define constants 7 | global start ; global access to kernel entry 8 | extern long_mode_start 9 | 10 | section .text 11 | bits 32 ; 32 bit instructions (CPU in protected mode) 12 | start: 13 | mov esp, stack_top 14 | mov edi, ebx ; multiboot information 15 | 16 | ; check for incompatibility with processor 17 | ; error codes if incompatible 18 | call check_multiboot ; throw code 0 19 | call check_cpuid ; throw code 1 20 | call check_long_mode ; throw code 2 21 | 22 | ; enable paging 23 | call set_up_paging 24 | call set_paging 25 | 26 | ; recursive map p4 page table 27 | mov eax, p4_table 28 | or eax, 0b11 29 | mov [p4_table + 511 * 8], eax 30 | 31 | ; load gdt 32 | lgdt [gdt64.pointer] 33 | jmp gdt64.code:long_mode_start 34 | 35 | hlt 36 | 37 | ; check for multiboot loader 38 | check_multiboot: 39 | cmp eax, 0x36d76289 ; magic number placed in eax register by loader 40 | jne .no_multiboot ; if not in register, 41 | ret 42 | .no_multiboot: ; throw error code 0 43 | mov al, "0" 44 | jmp error 45 | 46 | ; detect support for CPUID: 47 | ; attempt to flip bit 21 in FLAGS register 48 | ; (function from OSDev wiki) 49 | check_cpuid: 50 | ; copy FLAGS into eax and ecx 51 | pushfd 52 | pop eax 53 | mov ecx, eax 54 | 55 | ; flip bit 56 | xor eax, 1 << 21 57 | 58 | ; move to FLAGS register 59 | push eax 60 | popfd 61 | 62 | ; restore FLAGS to eax (bit will be flipped if CPUID supported) 63 | ; restore FLAGS before flip op to ecx 64 | pushfd 65 | pop eax 66 | push ecx 67 | popfd 68 | 69 | ; compare eax to ecx to judge if op successful 70 | cmp eax, ecx 71 | je .cpuid_err 72 | ret 73 | 74 | .cpuid_err: 75 | mov al, "1" 76 | jmp error 77 | 78 | ; check 64-bit (long mode) supported 79 | check_long_mode: 80 | ; check processor age 81 | mov eax, 0x80000000 ; call cpuid with magic number 82 | cpuid ; place highest argument in eax 83 | cmp eax, 0x80000001 ; compare to long mode supported cpuid 84 | jb .no_support 85 | 86 | ; check 64-bit (long mode) support on correct systems 87 | mov eax, 0x80000001 ; cpuid arg for extended info 88 | cpuid ; place info in ecx and edx 89 | test edx, 1 << 29 ; check LM bit (bit 29) is set 90 | jz .no_support 91 | ret 92 | .no_support: 93 | mov al, "2" ; throw error code 2 if no LM support 94 | jmp error 95 | 96 | ; print error ("ERR:") and ID character to VGA buffer 97 | ; buffer starts at memory address 0xb8000 98 | error: 99 | mov dword [0xb8000], 0x4f524f45 ; code 4f denotes red background 100 | mov dword [0xb8004], 0x4f3a4f52 101 | mov dword [0xb8008], 0x4f204f20 102 | mov byte [0xb800a], al 103 | hlt 104 | 105 | ; set up paging table references in the cpu 106 | set_up_paging: 107 | mov eax, p3_table 108 | or eax, 0b11 ; present + writable flags set 109 | mov [p4_table], eax 110 | 111 | mov eax, p2_table 112 | or eax, 0b11 113 | mov [p3_table], eax 114 | 115 | mov ecx, 0 116 | 117 | .map_p2_table: 118 | ; map P2 entry to a 2MiB huge page 119 | mov eax, 0x200000 ; 2MiB 120 | mul ecx ; start address of nth entry (n stored in ecx) 121 | or eax, 0b10000011 ; present + writable + huge 122 | mov [p2_table + ecx * 8], eax ; map nth entry 123 | 124 | inc ecx ; increase counter 125 | cmp ecx, 512 ; if counter == 512, the whole P2 table is mapped 126 | jne .map_p2_table ; else map the next entry 127 | 128 | ret 129 | 130 | ; enable paging in the cpu 131 | set_paging: 132 | ; load p4 table to cr3 register 133 | ; cpu uses cr3 register to reference p4 tables 134 | mov eax, p4_table 135 | mov cr3, eax 136 | 137 | ; set Physical Address Extension (PAE) flag in 138 | mov eax, cr4 139 | or eax, 1 << 5 140 | mov cr4, eax 141 | 142 | ; set long mode bit in MSR 143 | mov ecx, 0xC0000080 144 | rdmsr 145 | or eax, 1 << 8 146 | wrmsr 147 | 148 | ; enable paging in cr0 register 149 | mov eax, cr0 150 | or eax, 1 << 31 151 | mov cr0, eax 152 | 153 | ret 154 | 155 | ; stack structure and paging 156 | section .bss 157 | align 4096 158 | p4_table: 159 | resb 4096 160 | p3_table: 161 | resb 4096 162 | p2_table: 163 | resb 4096 164 | stack_bottom: 165 | resb 32768 ; reserve 16 KB of stack space for kernel 166 | stack_top: 167 | 168 | ; set up a gdt table (64-bit) 169 | ; this is a temporary table, before we jump to kernel 170 | section .read_only: 171 | gdt64: 172 | dq 0 ; zero entry 173 | .code: equ $ - gdt64 ; store gdt offset 174 | ; executable, descriptor type, present, 64-bit 175 | dq (1<<43) | (1<<44) | (1<<47) | (1<<53) ; code segment flags 176 | ; create a pointer to the table 177 | .pointer: 178 | dw $ - gdt64 -1 ; size of table 179 | dq gdt64 ; address of table 180 | 181 | ; required data for recognition via bootloader 182 | ; mainly magic numbers and necessary data, to enable multiboot support 183 | section .mboot_h 184 | header_start: 185 | ; definitions 186 | dd 0xe85250d6 ; multiboot 2 number 187 | dd 0 ; architecture specification: 0 (x86) 188 | dd header_end - header_start ; length of header 189 | 190 | ; checksum (avoid compiler warning) 191 | dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start)) 192 | 193 | ; required multiboot end tags 194 | dw 0 ; type 195 | dw 0 ; flags 196 | dw 8 ; size 197 | header_end: 198 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/boot/long_mode.asm: -------------------------------------------------------------------------------- 1 | ; long_mode.asm 2 | 3 | ; start long mode 4 | global long_mode_start 5 | 6 | section .text 7 | bits 64 ; inform nasm of 64-bit instructions 8 | long_mode_start: 9 | 10 | ; print `OKAY` to screen, so we know we got this far 11 | mov rax, 0x2f592f412f4b2f4f 12 | mov qword [0xb8000], rax 13 | 14 | extern kernel_main 15 | call kernel_main 16 | 17 | halt: 18 | hlt 19 | jmp halt ; Infinite loop 20 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/gdt.rs: -------------------------------------------------------------------------------- 1 | //gdt.rs 2 | //defines and provides methods for the Global Descriptor Table, for use in long mode. 3 | //a table has already been defined for protected mode, in boot.asm 4 | 5 | use core::mem::size_of; 6 | use core::fmt::Write; 7 | use driver::vga; 8 | use driver::vga::Writer; 9 | 10 | const GDT_LENGTH: usize = 3; 11 | 12 | //various binary flags that appear in the access field of a gdt entry 13 | //they determine the properties of the entry, and how data is manipulated/accessed 14 | pub enum AccessFlags { 15 | //for code, indicate it is readable 16 | //for data, indicate it is writable 17 | ReadWrite = 0b00000010, 18 | Executable = 0b00001000, //indicate a code segment 19 | Present = 0b10000000, //indicate a valid sector 20 | One = 0b00010000 //self-explanatory -- always set 21 | } 22 | 23 | //various binary flags that appear in the granularity field of a gdt entry 24 | pub enum GranularityFlags { 25 | Page = 0b1000, 26 | LongMode64 = 0b0010 27 | } 28 | 29 | pub struct Gdt([GdtEntry; 3]); 30 | 31 | impl Gdt { 32 | pub fn new() -> Gdt { 33 | Gdt([GdtEntry::missing(); 3]) 34 | } 35 | 36 | pub fn set_entry(&mut self, vector: u8, entry: GdtEntry) { 37 | self.0[vector as usize] = entry; 38 | } 39 | 40 | pub fn install(&'static self) { 41 | let mut ptr = GdtPointer::new(); 42 | ptr.limit = (GDT_LENGTH as u16 * size_of::() as u16) - 1; 43 | ptr.base = self as *const _ as u64; 44 | 45 | unsafe { 46 | asm!("lgdt ($0) 47 | mov $$0x10, %ax 48 | mov %ax, %ds 49 | mov %ax, %fs 50 | mov %ax, %es 51 | mov %ax, %gs 52 | mov %ax, %ss" 53 | :: "r" (&ptr) : "memory"); 54 | } 55 | 56 | vga::okay(); 57 | unsafe { 58 | write!(Writer::new(), "Success! Created 64-bit GDT at address 0x{:X}\n", ptr.base) 59 | .expect("Unexpected failure in write!()");; 60 | } 61 | } 62 | } 63 | 64 | //contains the structure of a gdt entry 65 | #[derive(Copy, Clone, Debug)] 66 | #[repr(C, packed)] 67 | pub struct GdtEntry { 68 | //limit: size of entry 69 | limit_low: u16, 70 | //base: offset in memory of entry 71 | base_low: u16, 72 | base_middle: u8, 73 | //determine the access level of the segment 74 | access: u8, 75 | //determine the granularity of the segment 76 | //rest of limit stored in granularity byte 77 | granularity: u8, 78 | base_high: u8 79 | } 80 | 81 | impl GdtEntry { 82 | pub const fn missing() -> GdtEntry { 83 | GdtEntry { 84 | base_low: 0, 85 | base_middle: 0, 86 | base_high: 0, 87 | limit_low: 0, 88 | granularity: 0, 89 | access: 0 90 | } 91 | } 92 | 93 | pub fn set_up(base_in: u32, limit_in: u32, access_in: u8, gran_in: u8) -> GdtEntry { 94 | let temp_flags: u8 = ((limit_in >> 16) & 0x0F) as u8; 95 | let flags: u8 = temp_flags | ((gran_in << 4) &0xF0) as u8; 96 | 97 | GdtEntry { 98 | //set the base (offset) of the entry 99 | base_low: base_in as u16, 100 | base_middle: (base_in >> 16) as u8, 101 | base_high: (base_in >> 24) as u8, 102 | 103 | //set the size of the entry 104 | limit_low: limit_in as u16, 105 | granularity: flags, 106 | 107 | //set the access level of the entry 108 | access: access_in 109 | } 110 | } 111 | } 112 | 113 | //contains the pointer to the gdt that must be passed to assembly 114 | #[repr(C, packed)] 115 | pub struct GdtPointer { 116 | pub limit: u16, 117 | pub base: u64 118 | } 119 | 120 | impl GdtPointer { 121 | pub fn new() -> GdtPointer { 122 | GdtPointer { 123 | limit: 0, 124 | base: 0 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/grub.cfg: -------------------------------------------------------------------------------- 1 | set timeout=0 2 | set default=0 3 | 4 | menuentry "rustbucket" { 5 | multiboot2 /boot/kernel.bin 6 | boot 7 | } 8 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/idt.rs: -------------------------------------------------------------------------------- 1 | //idt.rs 2 | //defines the Interrupt Descriptor Table, for use in long mode. 3 | 4 | use core::mem::size_of; 5 | use core::fmt::Write; 6 | use driver::vga; 7 | use driver::vga::Writer; 8 | 9 | const IDT_LENGTH: usize = 256; 10 | 11 | //various binary flags that represent entry attributes 12 | enum EntryFlags { 13 | Present = 0b10000000, 14 | //flags to determine gate type 15 | TaskGate = 0b0101, 16 | InterruptGate = 0b1110, 17 | TrapGate = 0b1111, 18 | StorageSeg = 0b10000, 19 | //flags to determine ring (protection) level 20 | Ring0 = 0b0000000, 21 | Ring1 = 0b0100000, 22 | Ring2 = 0b1000000, 23 | Ring3 = 0b1100000 24 | } 25 | 26 | pub struct Idt([IdtEntry; 256]); 27 | 28 | impl Idt { 29 | pub fn new() -> Idt { 30 | Idt([IdtEntry::missing(); 256]) 31 | } 32 | 33 | pub fn set_handler(&mut self, vector: u8, func: u64) { 34 | self.0[vector as usize] = IdtEntry::new(func); 35 | } 36 | 37 | pub fn install(&'static self) { 38 | let mut ptr = IdtPointer::new(); 39 | ptr.limit = (IDT_LENGTH as u16 * size_of::() as u16) - 1; 40 | ptr.base = self as *const _ as u64; 41 | 42 | unsafe { 43 | asm!("lidt ($0)" :: "r" (&ptr) : "memory"); 44 | } 45 | 46 | vga::okay(); 47 | unsafe { 48 | write!(Writer::new(), "Success! Created 64-bit IDT at address 0x{:X}\n", ptr.base) 49 | .expect("Unexpected failure in write!()");; 50 | } 51 | } 52 | } 53 | 54 | //contains the pointer to the gdt that must be passed to assembly 55 | #[repr(C, packed)] 56 | pub struct IdtPointer { 57 | pub limit: u16, 58 | pub base: u64 59 | } 60 | 61 | impl IdtPointer { 62 | pub fn new() -> IdtPointer { 63 | IdtPointer { 64 | limit: 0, 65 | base: 0 66 | } 67 | } 68 | } 69 | 70 | //contains the structure of an idt entry 71 | #[derive(Clone, Copy)] 72 | #[repr(C, packed)] 73 | pub struct IdtEntry { 74 | //base: offset in memory of entry 75 | base_low: u16, 76 | //selector: pointer to interrupt handler function 77 | selector: u16, 78 | zero1: u8, 79 | //entry attributes 80 | flags: u8, 81 | base_middle: u16, 82 | base_high: u32, 83 | zero2: u32 84 | } 85 | 86 | impl IdtEntry { 87 | pub const fn missing() -> IdtEntry { 88 | IdtEntry { 89 | base_low: 0, 90 | selector: 0, 91 | zero1: 0, 92 | flags: 0, 93 | base_middle: 0, 94 | base_high: 0, 95 | zero2: 0 96 | } 97 | } 98 | 99 | pub fn new(pointer: u64) -> IdtEntry { 100 | IdtEntry { 101 | base_low: pointer as u16, 102 | base_middle: (pointer >> 16) as u16, 103 | base_high: (pointer >> 32) as u32, 104 | 105 | selector: 8, 106 | 107 | zero1: 0, 108 | zero2: 0, 109 | 110 | flags: EntryFlags::InterruptGate as u8 | EntryFlags::Present as u8 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/int/int.rs: -------------------------------------------------------------------------------- 1 | //int.rs 2 | //interrupt control 3 | 4 | #[naked] 5 | #[inline(always)] 6 | pub fn enable() { 7 | unsafe { 8 | asm!("sti"); 9 | } 10 | } 11 | 12 | #[naked] 13 | #[inline(always)] 14 | pub fn disable() { 15 | unsafe { 16 | asm!("cli"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/int/isr.asm: -------------------------------------------------------------------------------- 1 | ;isr.asm 2 | 3 | ;defines functions and macros for use handling interrupts 4 | ;makes sure all correct information is preserved and restored, and the 5 | ;interrupt is passed to the right handler 6 | 7 | ;default handlers 8 | global isr_default 9 | global isr_default_err 10 | 11 | ;exceptions 12 | global divide_by_zero_wrapper 13 | global debug_wrapper 14 | global breakpoint_wrapper 15 | global overflow_wrapper 16 | global bounds_wrapper 17 | global opcode_wrapper 18 | global device_na_wrapper 19 | global double_fault_wrapper 20 | global gpf_wrapper 21 | global x87_float_wrapper 22 | global page_fault_wrapper 23 | 24 | ;interrupts 25 | global pit_wrapper 26 | global keyboard_wrapper 27 | global com1_wrapper 28 | global isr_spurious 29 | 30 | section .text 31 | bits 64 32 | ;define a macro for pushing registers onto stack 33 | %macro PUSH_ALL 0 34 | push rax 35 | push rbx 36 | push rcx 37 | push rdx 38 | push rdi 39 | push rsi 40 | push rbp 41 | push r8 42 | push r9 43 | push r10 44 | push r11 45 | push r12 46 | push r13 47 | push r14 48 | push r15 49 | %endmacro 50 | 51 | ;define a macro for restoring values to registers from stack 52 | %macro POP_ALL 0 53 | pop r15 54 | pop r14 55 | pop r13 56 | pop r12 57 | pop r11 58 | pop r10 59 | pop r9 60 | pop r8 61 | pop rbp 62 | pop rsi 63 | pop rdi 64 | pop rdx 65 | pop rcx 66 | pop rbx 67 | pop rax 68 | %endmacro 69 | 70 | align 4 71 | isr_default: 72 | mov rdi, rsp 73 | PUSH_ALL 74 | sub rsp, 8 75 | 76 | extern isr_default_handler 77 | call isr_default_handler 78 | 79 | add rsp, 8 80 | POP_ALL 81 | iretq 82 | 83 | align 4 84 | isr_default_err: 85 | pop rsi 86 | mov rdi, rsp 87 | PUSH_ALL 88 | sub rsp, 8 89 | 90 | extern isr_default_err_handler 91 | call isr_default_err_handler 92 | 93 | add rsp, 8 94 | POP_ALL 95 | iretq 96 | 97 | align 4 98 | isr_spurious: 99 | PUSH_ALL 100 | 101 | POP_ALL 102 | iretq 103 | 104 | align 4 105 | divide_by_zero_wrapper: 106 | mov rdi, rsp 107 | sub rsp, 8 108 | PUSH_ALL 109 | 110 | extern divide_by_zero_handler 111 | call divide_by_zero_handler 112 | 113 | add rsp, 8 114 | POP_ALL 115 | iretq 116 | 117 | align 4 118 | breakpoint_wrapper: 119 | mov rdi, rsp 120 | sub rsp, 8 121 | PUSH_ALL 122 | 123 | extern breakpoint_handler 124 | call breakpoint_handler 125 | 126 | add rsp, 8 127 | POP_ALL 128 | iretq 129 | 130 | align 4 131 | debug_wrapper: 132 | mov rdi, rsp 133 | sub rsp, 8 134 | PUSH_ALL 135 | 136 | extern debug_handler 137 | call debug_handler 138 | 139 | add rsp, 8 140 | POP_ALL 141 | iretq 142 | 143 | align 4 144 | overflow_wrapper: 145 | mov rdi, rsp 146 | sub rsp, 8 147 | PUSH_ALL 148 | 149 | extern overflow_handler 150 | call overflow_handler 151 | 152 | add rsp, 8 153 | POP_ALL 154 | iretq 155 | 156 | align 4 157 | bounds_wrapper: 158 | mov rdi, rsp 159 | sub rsp, 8 160 | PUSH_ALL 161 | 162 | extern bounds_handler 163 | call bounds_handler 164 | 165 | add rsp, 8 166 | POP_ALL 167 | iretq 168 | 169 | align 4 170 | opcode_wrapper: 171 | mov rdi, rsp 172 | sub rsp, 8 173 | PUSH_ALL 174 | 175 | extern opcode_handler 176 | call opcode_handler 177 | 178 | add rsp, 8 179 | POP_ALL 180 | iretq 181 | 182 | align 4 183 | device_na_wrapper: 184 | mov rsi, rsp 185 | sub rsp, 8 186 | PUSH_ALL 187 | 188 | extern device_na_handler 189 | call device_na_handler 190 | 191 | add rsp, 8 192 | POP_ALL 193 | iretq 194 | 195 | align 4 196 | double_fault_wrapper: 197 | pop rsi 198 | mov rdi, rsp 199 | sub rsp, 8 200 | PUSH_ALL 201 | 202 | extern double_fault_handler 203 | call double_fault_handler 204 | 205 | add rsp, 8 206 | POP_ALL 207 | iretq 208 | 209 | align 4 210 | gpf_wrapper: 211 | pop rsi 212 | mov rdi, rsp 213 | sub rsp, 8 214 | PUSH_ALL 215 | 216 | extern gpf_handler 217 | call gpf_handler 218 | 219 | add rsp, 8 220 | POP_ALL 221 | iretq 222 | 223 | align 4 224 | x87_float_wrapper: 225 | mov rdi, rsp 226 | sub rsp, 8 227 | PUSH_ALL 228 | 229 | extern x87_float_handler 230 | call x87_float_handler 231 | 232 | add rsp, 8 233 | POP_ALL 234 | iretq 235 | 236 | align 4 237 | page_fault_wrapper: 238 | pop rsi 239 | mov rdi, rsp 240 | sub rsp, 8 241 | PUSH_ALL 242 | 243 | extern page_fault_handler 244 | call page_fault_handler 245 | 246 | add rsp, 8 247 | POP_ALL 248 | iretq 249 | 250 | align 4 251 | pit_wrapper: 252 | PUSH_ALL 253 | 254 | extern pit_handler 255 | call pit_handler 256 | 257 | POP_ALL 258 | iretq 259 | 260 | align 4 261 | keyboard_wrapper: 262 | PUSH_ALL 263 | 264 | extern keyboard_handler 265 | call keyboard_handler 266 | 267 | POP_ALL 268 | iretq 269 | 270 | align 4 271 | com1_wrapper: 272 | PUSH_ALL 273 | 274 | extern com1_handler 275 | call com1_handler 276 | 277 | POP_ALL 278 | iretq 279 | 280 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/int/isr.rs: -------------------------------------------------------------------------------- 1 | //isr.rs 2 | //defines methods for interrupts 3 | 4 | //***************************************// 5 | // Exception list at: // 6 | // https://wiki.osdev.org/Exceptions // 7 | //***************************************// 8 | 9 | use arch::dev::pic; 10 | use arch::dev::pit; 11 | use driver::vga::Writer; 12 | use driver::vga::print_char; 13 | use driver::kbd::get_char; 14 | use driver::com; 15 | use core::fmt::Write; 16 | 17 | const PIT_OFFSET: u8 = 1; 18 | const KBD_OFFSET: u8 = 2; 19 | const COM1_OFFSET: u8 = 4; 20 | 21 | #[derive(Debug)] 22 | #[repr(C)] 23 | pub struct InterruptFrame { 24 | pub instruction_pointer: u64, 25 | code_segment: u64, 26 | cpu_flags: u64, 27 | stack_pointer: u64, 28 | stack_segment: u64 29 | } 30 | 31 | // TODO: Bitflags? 32 | #[repr(u64)] 33 | enum PageFaultError { 34 | ProtectionViolation = 0b00000001, 35 | AttemptToWrite = 0b00000010, 36 | UserMode = 0b00000100, 37 | TableError = 0b00001000, 38 | InstructionFetch = 0b00010000, 39 | } 40 | 41 | #[no_mangle] 42 | #[linkage = "external"] 43 | pub extern fn isr_default_handler(frame: &InterruptFrame) -> ! { 44 | let frame = &*frame; 45 | write!(Writer::new(), "EXCEPTION: UNHANDLED EXCEPTION at instruction {:#X}\n{:#?}\n\n", 46 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 47 | 48 | loop {} 49 | } 50 | 51 | #[no_mangle] 52 | #[linkage = "external"] 53 | pub extern fn isr_default_err_handler(frame: &InterruptFrame) -> ! { 54 | let frame = &*frame; 55 | write!(Writer::new(), "EXCEPTION: UNHANDLED EXCEPTION at instruction {:X}\n{:#?}\n\n", 56 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 57 | 58 | loop {} 59 | } 60 | 61 | // Vector 0 62 | #[no_mangle] 63 | #[linkage = "external"] 64 | pub extern fn divide_by_zero_handler(frame: &InterruptFrame) -> ! { 65 | let frame = &*frame ; 66 | write!(Writer::new(), "EXCEPTION: DIVIDE BY ZERO at instruction {:#X}\n{:#?}\n\n", 67 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 68 | 69 | loop {} 70 | } 71 | 72 | // Vector 1 73 | #[no_mangle] 74 | #[linkage = "external"] 75 | pub extern fn debug_handler(frame: &InterruptFrame) -> ! { 76 | let frame = &*frame; 77 | write!(Writer::new(), "EXCEPTION: DEBUG at instruction {:#X}\n{:#?}\n\n", 78 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 79 | 80 | loop {} 81 | } 82 | 83 | // Vector 3 84 | #[no_mangle] 85 | #[linkage = "external"] 86 | pub extern fn breakpoint_handler(frame: &InterruptFrame) { 87 | let frame = &*frame; 88 | write!(Writer::new(), "EXCEPTION: BREAK POINT at instruction {:#X}\n{:#?}\n\n", 89 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 90 | } 91 | 92 | // Vector 4 93 | #[no_mangle] 94 | #[linkage = "external"] 95 | pub extern fn overflow_handler(frame: &InterruptFrame) -> ! { 96 | let frame = &*frame; 97 | write!(Writer::new(), "EXCEPTION: OVERFLOW at instruction {:#X}\n{:#?}\n\n", 98 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 99 | 100 | loop {} 101 | } 102 | 103 | // Vector 5 104 | #[no_mangle] 105 | #[linkage = "external"] 106 | pub extern fn bounds_handler(frame: &InterruptFrame) -> ! { 107 | let frame = &*frame; 108 | write!(Writer::new(), "EXCEPTION: OUT-OF-BOUNDS at instruction {:#X}\n{:#?}\n\n", 109 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 110 | 111 | loop {} 112 | } 113 | 114 | // Vector 6 115 | #[no_mangle] 116 | #[linkage = "external"] 117 | pub extern fn opcode_handler(frame: &InterruptFrame) -> ! { 118 | let frame = &*frame; 119 | write!(Writer::new(), "EXCEPTION: INVALID OPCODE at instruction {:#X}\n{:#?}\n\n", 120 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 121 | 122 | loop {} 123 | } 124 | 125 | // Vector 7 126 | #[no_mangle] 127 | #[linkage = "external"] 128 | pub extern fn device_na_handler(frame: &InterruptFrame) -> ! { 129 | let frame = &*frame; 130 | write!(Writer::new(), "EXCEPTION: DEVICE NOT FOUND at instruction {:#X}\n{:#?}\n\n", 131 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 132 | 133 | loop {} 134 | } 135 | 136 | // Vector 8 137 | #[no_mangle] 138 | #[linkage = "external"] 139 | pub extern fn double_fault_handler(frame: &InterruptFrame) -> ! { 140 | let frame = &*frame; 141 | write!(Writer::new(), "EXCEPTION: DOUBLE FAULT at instruction {:#X}\n{:#?}\n\n", 142 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 143 | 144 | loop {} 145 | } 146 | 147 | // Vector 13 148 | #[no_mangle] 149 | #[linkage = "external"] 150 | pub extern fn gpf_handler(frame: &InterruptFrame, code: u64) -> ! { 151 | let frame = &*frame; 152 | write!(Writer::new(), "EXCEPTION: GPF at instruction {:#X}, error {:#X}\n{:#?}\n\n", 153 | frame.instruction_pointer, code, frame).expect("Unexpected failure in write!()"); 154 | 155 | loop {} 156 | } 157 | 158 | // Vector 14 159 | #[no_mangle] 160 | #[linkage = "external"] 161 | pub extern fn page_fault_handler(frame: &InterruptFrame, code: u64) -> ! { 162 | let frame = &*frame; 163 | let code_str; 164 | 165 | // TODO: TIDY UP 166 | match code { 167 | code if code == PageFaultError::ProtectionViolation as u64 => code_str = "PROTECTION VIOLATION", 168 | code if code == PageFaultError::AttemptToWrite as u64 => code_str = "ATTEMPTED TO WRITE", 169 | code if code == PageFaultError::UserMode as u64 => code_str = "USER MODE", 170 | code if code == PageFaultError::TableError as u64 => code_str = "ERROR IN TABLE", 171 | code if code == PageFaultError::InstructionFetch as u64 => code_str = "INSTRUCTION FETCH", 172 | _ => code_str = "UNKNOWN ERROR", 173 | } 174 | 175 | write!(Writer::new(), "EXCEPTION: PAGE FAULT at instruction {:#X}, error: {:#}\n{:#?}\n\n", 176 | frame.instruction_pointer, code_str, frame).expect("Unexpected failure in write!()"); 177 | 178 | loop {} 179 | } 180 | 181 | // Vector 16 182 | #[no_mangle] 183 | #[linkage = "external"] 184 | pub extern fn x87_float_handler(frame: &InterruptFrame) -> ! { 185 | let frame = &*frame; 186 | write!(Writer::new(), "EXCEPTION: x87 FLOATING POINT at instruction {:#X}\n{:#?}\n\n", 187 | frame.instruction_pointer, frame).expect("Unexpected failure in write!()"); 188 | 189 | loop {} 190 | } 191 | 192 | // Vector 32 193 | #[no_mangle] 194 | #[linkage = "external"] 195 | pub extern fn pit_handler() { 196 | unsafe { 197 | pit::TICKS += 1; 198 | 199 | if pit::TICKS >= 0xFFFFFFFF - 1 { 200 | pit::TICKS = 0; 201 | } 202 | } 203 | 204 | pic::ack(PIT_OFFSET); 205 | } 206 | 207 | // Vector 33 208 | #[no_mangle] 209 | #[linkage = "external"] 210 | pub extern fn keyboard_handler() { 211 | let c = get_char(); 212 | 213 | match c { 214 | Some(res) => print_char(res, 0x07), 215 | // Do nothing if NONE returned 216 | None => {} 217 | } 218 | 219 | pic::ack(KBD_OFFSET); 220 | } 221 | 222 | // Vector 36 223 | #[no_mangle] 224 | #[linkage = "external"] 225 | pub extern fn com1_handler() { 226 | write!(Writer::new(), "COM1 INPUT RECEIVED: {}", com::read() as char); 227 | pic::ack(COM1_OFFSET); 228 | } 229 | 230 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/int/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod isr; 2 | pub mod int; 3 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/linker.ld: -------------------------------------------------------------------------------- 1 | ENTRY(start) 2 | 3 | SECTIONS { 4 | /* kernel load address */ 5 | . = 1M; 6 | 7 | .boot : 8 | { 9 | /* load multiboot header first */ 10 | KEEP(*(.mboot_h)) 11 | } 12 | 13 | .text : 14 | { 15 | /* all input sections named 'text' */ 16 | *(.text .text.*) 17 | } 18 | 19 | .rodata : { 20 | *(.rodata .rodata.*) 21 | } 22 | 23 | .data.rel.ro : { 24 | *(.data.rel.ro.local*) *(.data.rel.ro .data.rel.ro.*) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/mem/entry.rs: -------------------------------------------------------------------------------- 1 | // entry.rs 2 | // Contains structs and methods to represent page table entries 3 | 4 | use arch::x86_64::mem::frame::PageFrame; 5 | 6 | bitflags! { 7 | pub struct EntryFlags: u64 { 8 | const PRESENT = 1 << 0; 9 | const WRITABLE = 1 << 1; 10 | const USER_ACCESSIBLE = 1 << 2; 11 | const WRITE_THROUGH = 1 << 3; 12 | const NO_CACHE = 1 << 4; 13 | const ACCESSED = 1 << 5; 14 | const HUGE_PAGE = 1 << 6; 15 | const DIRTY = 1 << 7; 16 | const GLOBAL = 1 << 8; 17 | const NO_EXECUTE = 1 << 63; 18 | } 19 | } 20 | 21 | // Entry contains 64-bit flag 22 | pub struct Entry(u64); 23 | 24 | impl Entry { 25 | pub fn is_unused(&self) -> bool { 26 | self.0 == 0 27 | } 28 | 29 | pub fn set_as_unused(&mut self) { 30 | self.0 = 0; 31 | } 32 | 33 | pub fn flags(&self) -> EntryFlags { 34 | EntryFlags::from_bits_truncate(self.0) 35 | } 36 | 37 | // Get address from page in entry, if present 38 | pub fn pointed_frame(&self) -> Option { 39 | if self.flags().contains(EntryFlags::PRESENT) { 40 | Some(PageFrame::containing_address(self.0 as usize & 0x000fffff_fffff000)) 41 | } 42 | else { 43 | None 44 | } 45 | } 46 | 47 | // Set entry to aligned page 48 | pub fn set(&mut self, frame: PageFrame, flags: EntryFlags) { 49 | assert!(frame.start() & !0x000fffff_fffff000 == 0); 50 | self.0 = frame.start() as u64 | flags.bits(); 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/mem/frame.rs: -------------------------------------------------------------------------------- 1 | // frame.rs 2 | // Contains structs and methods for page frames 3 | 4 | use arch::x86_64::mem::{PhysicalAddress, VirtualAddress}; 5 | 6 | pub const PAGE_SIZE: u16 = 4096; 7 | 8 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] 9 | pub struct PageFrame { 10 | pub number: usize, 11 | } 12 | 13 | impl PageFrame { 14 | // Get the frame containing a virtual address 15 | pub fn containing_address(address: PhysicalAddress) -> PageFrame { 16 | PageFrame { number: address / PAGE_SIZE as usize } 17 | } 18 | 19 | //get the PHYSICAL start address of frame 20 | pub fn start(&self) -> PhysicalAddress { 21 | self.number * PAGE_SIZE as usize 22 | } 23 | } 24 | 25 | pub trait FrameAllocator { 26 | fn allocate_frame(&self) -> Option; 27 | fn deallocate_frame(&self, frame: PageFrame); 28 | } 29 | 30 | pub struct Page(usize); 31 | 32 | impl Page { 33 | // Get page containing virtual address 34 | pub fn containing_address(address: VirtualAddress) -> Page { 35 | assert!(address < 0x0000_8000_0000_0000 || 36 | address >= 0xffff_8000_0000_0000, 37 | "invalid address: 0x{:x}", address); 38 | 39 | Page (address / PAGE_SIZE as usize) 40 | } 41 | 42 | fn start(&self) -> usize { 43 | self.0 * PAGE_SIZE as usize 44 | } 45 | 46 | pub fn p4_index(&self) -> usize { 47 | (self.0 >> 27) & 0o777 48 | } 49 | 50 | pub fn p3_index(&self) -> usize { 51 | (self.0 >> 18) & 0o777 52 | } 53 | 54 | pub fn p2_index(&self) -> usize { 55 | (self.0 >> 9) & 0o777 56 | } 57 | 58 | pub fn p1_index(&self) -> usize { 59 | (self.0 >> 0) & 0o777 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/mem/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod frame; 2 | pub mod entry; 3 | pub mod table; 4 | 5 | use arch::x86_64::mem::frame::{Page, PageFrame, PAGE_SIZE}; 6 | use arch::x86_64::mem::entry::EntryFlags; 7 | use arch::x86_64::mem::table::P4; 8 | 9 | const ENTRY_COUNT: usize = 512; 10 | 11 | pub type PhysicalAddress = usize; 12 | pub type VirtualAddress = usize; 13 | 14 | pub fn translate(virtual_address: VirtualAddress) -> Option { 15 | let offset = virtual_address / PAGE_SIZE as usize; 16 | 17 | translate_page(frame::Page::containing_address(virtual_address)) 18 | .map(|frame| frame.number * PAGE_SIZE as usize * offset) 19 | } 20 | 21 | fn translate_page(page: Page) -> Option { 22 | let p3 = unsafe { &*P4 }.next_table(page.p4_index()); 23 | 24 | let huge_page = || { 25 | p3.and_then(|p3| { 26 | let p3_entry = &p3[page.p3_index()]; 27 | // 1GiB page? 28 | if let Some(start_frame) = p3_entry.pointed_frame() { 29 | if p3_entry.flags().contains(EntryFlags::HUGE_PAGE) { 30 | // address must be 1GiB aligned 31 | assert!(start_frame.number % (ENTRY_COUNT * ENTRY_COUNT) == 0); 32 | return Some(PageFrame { 33 | number: start_frame.number + page.p2_index() * 34 | ENTRY_COUNT + page.p1_index(), 35 | }); 36 | } 37 | } 38 | if let Some(p2) = p3.next_table(page.p3_index()) { 39 | let p2_entry = &p2[page.p2_index()]; 40 | // 2MiB page? 41 | if let Some(start_frame) = p2_entry.pointed_frame() { 42 | if p2_entry.flags().contains(EntryFlags::HUGE_PAGE) { 43 | // address must be 2MiB aligned 44 | assert!(start_frame.number % ENTRY_COUNT == 0); 45 | return Some(PageFrame { 46 | number: start_frame.number + page.p1_index() 47 | }); 48 | } 49 | } 50 | } 51 | None 52 | }) 53 | }; 54 | 55 | p3.and_then(|p3| p3.next_table(page.p3_index())) 56 | .and_then(|p2| p2.next_table(page.p2_index())) 57 | .and_then(|p1| p1[page.p1_index()].pointed_frame()) 58 | .or_else(huge_page) 59 | } 60 | 61 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/mem/table.rs: -------------------------------------------------------------------------------- 1 | //table.rs 2 | //contains methods and implementation for page tables 3 | 4 | use core::marker::PhantomData; 5 | use core::ops::{ Index, IndexMut }; 6 | use arch::x86_64::mem::{ entry::*, frame::PageFrame }; 7 | use arch::x86_64::mem::ENTRY_COUNT; 8 | 9 | pub const P4: *mut Table = 0xffffffff_fffff000 as *mut _; 10 | 11 | // Table levels 12 | pub trait TableLevel {} 13 | 14 | pub enum Level4 {} 15 | pub enum Level3 {} 16 | pub enum Level2 {} 17 | pub enum Level1 {} 18 | 19 | impl TableLevel for Level4 {} 20 | impl TableLevel for Level3 {} 21 | impl TableLevel for Level2 {} 22 | impl TableLevel for Level1 {} 23 | 24 | // Table levels that are mapped to other tables 25 | // (**NOT** P1) 26 | pub trait MappedLevel: TableLevel { 27 | type NextLevel: TableLevel; 28 | } 29 | 30 | impl MappedLevel for Level4 { 31 | type NextLevel = Level3; 32 | } 33 | 34 | impl MappedLevel for Level3 { 35 | type NextLevel = Level2; 36 | } 37 | 38 | impl MappedLevel for Level2 { 39 | type NextLevel = Level1; 40 | } 41 | 42 | // Phantom data for unused type -- just need level for implementation 43 | pub struct Table { 44 | entries: [Entry; ENTRY_COUNT], 45 | level: PhantomData, 46 | } 47 | 48 | impl Index for Table where L: TableLevel { 49 | type Output = Entry; 50 | 51 | fn index(&self, index: usize) -> &Entry { 52 | &self.entries[index] 53 | } 54 | } 55 | 56 | impl IndexMut for Table where L: TableLevel { 57 | fn index_mut(&mut self, index: usize) -> &mut Entry { 58 | &mut self.entries[index] 59 | } 60 | } 61 | 62 | impl Table where L: TableLevel { 63 | pub fn clear(&mut self) { 64 | for entry in self.entries.iter_mut() { 65 | entry.set_as_unused(); 66 | } 67 | } 68 | } 69 | 70 | impl Table where L: MappedLevel { 71 | pub fn next_table(&self, index: usize) -> Option<&Table> { 72 | self.next_table_address(index) 73 | .map(|address| unsafe {&*(address as *const _)}) 74 | } 75 | 76 | pub fn next_table_as_mut(&mut self, index: usize) -> Option<&mut Table> { 77 | self.next_table_address(index) 78 | .map(|address| unsafe {&mut *(address as *mut _)}) 79 | } 80 | 81 | fn next_table_address(&self, index: usize) -> Option { 82 | let entry_flags = self[index].flags(); 83 | 84 | if entry_flags.contains(EntryFlags::PRESENT) 85 | && !entry_flags.contains(EntryFlags::HUGE_PAGE) { 86 | let table_address = self as *const _ as usize; 87 | Some((table_address << 9) | (index << 12)) 88 | } 89 | else { 90 | None 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /kernel/arch/x86_64/mod.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | pub mod idt; 3 | pub mod int; 4 | pub mod gdt; 5 | pub mod mem; 6 | 7 | extern "C" { 8 | // Default handlers 9 | fn isr_default(); 10 | fn isr_default_err(); 11 | 12 | // Exceptions 13 | fn divide_by_zero_wrapper(); 14 | fn debug_wrapper(); 15 | fn breakpoint_wrapper(); 16 | fn overflow_wrapper(); 17 | fn bounds_wrapper(); 18 | fn opcode_wrapper(); 19 | fn device_na_wrapper(); 20 | fn double_fault_wrapper(); 21 | fn gpf_wrapper(); 22 | fn x87_float_wrapper(); 23 | fn page_fault_wrapper(); 24 | 25 | // Interrupts 26 | fn pit_wrapper(); 27 | fn keyboard_wrapper(); 28 | fn com1_wrapper(); 29 | fn isr_spurious(); 30 | } 31 | 32 | lazy_static! { 33 | static ref GDT: gdt::Gdt = { 34 | let mut gdt = gdt::Gdt::new(); 35 | 36 | //set access flags for code segments 37 | let code_flags: u8 = 38 | gdt::AccessFlags::ReadWrite as u8 | 39 | gdt::AccessFlags::Executable as u8 | 40 | gdt::AccessFlags::One as u8 | 41 | gdt::AccessFlags::Present as u8; 42 | //set access flags for data segments 43 | let data_flags: u8 = 44 | gdt::AccessFlags::ReadWrite as u8 | 45 | gdt::AccessFlags::One as u8 | 46 | gdt::AccessFlags::Present as u8; 47 | //set granularity flags, indicate a 64-bit table 48 | let granularity_flags: u8 = 49 | gdt::GranularityFlags::Page as u8 | 50 | gdt::GranularityFlags::LongMode64 as u8; 51 | 52 | gdt.set_entry(0, gdt::GdtEntry::set_up(0, 0, 0, 0)); 53 | gdt.set_entry(1, gdt::GdtEntry::set_up(0, 0xFFFFF, code_flags, granularity_flags)); 54 | gdt.set_entry(2, gdt::GdtEntry::set_up(0, 0xFFFFF, data_flags, granularity_flags)); 55 | 56 | gdt 57 | }; 58 | } 59 | 60 | lazy_static! { 61 | static ref IDT: idt::Idt = { 62 | let mut idt = idt::Idt::new(); 63 | 64 | // Exceptions 65 | idt.set_handler(0, divide_by_zero_wrapper as u64); 66 | idt.set_handler(1, debug_wrapper as u64); 67 | idt.set_handler(3, breakpoint_wrapper as u64); 68 | idt.set_handler(4, overflow_wrapper as u64); 69 | idt.set_handler(5, bounds_wrapper as u64); 70 | idt.set_handler(6, opcode_wrapper as u64); 71 | idt.set_handler(7, device_na_wrapper as u64); 72 | idt.set_handler(8, double_fault_wrapper as u64); 73 | idt.set_handler(10, isr_default_err as u64); // Invalid TSS 74 | idt.set_handler(11, isr_default_err as u64); // Segment not present 75 | idt.set_handler(12, isr_default_err as u64); // Stack segment fault 76 | idt.set_handler(13, gpf_wrapper as u64); 77 | idt.set_handler(14, page_fault_wrapper as u64); 78 | idt.set_handler(16, x87_float_wrapper as u64); 79 | idt.set_handler(17, isr_default_err as u64); // Alignment check 80 | idt.set_handler(18, isr_default as u64); // Machine check 81 | idt.set_handler(19, isr_default as u64); // SIMD flo{ating point 82 | idt.set_handler(20, isr_default as u64); // Virtualisation fault 83 | idt.set_handler(30, isr_default_err as u64); // Security exception 84 | 85 | // Interrupts 86 | idt.set_handler(32, pit_wrapper as u64); 87 | idt.set_handler(33, keyboard_wrapper as u64); 88 | idt.set_handler(36, com1_wrapper as u64); 89 | idt.set_handler(39, isr_spurious as u64); 90 | 91 | idt 92 | }; 93 | } 94 | 95 | pub fn gdt_init() { 96 | GDT.install(); 97 | } 98 | 99 | pub fn idt_init() { 100 | IDT.install(); 101 | } 102 | -------------------------------------------------------------------------------- /kernel/driver/com.rs: -------------------------------------------------------------------------------- 1 | // com.rs 2 | // serial port communication 3 | 4 | use arch::dev::port_io; 5 | use driver::vga; 6 | 7 | const COM1: u16 = 0x3F8; 8 | 9 | pub fn init() { 10 | unsafe { 11 | // Disable all COM1 interrupts 12 | port_io::outb(COM1 + 1, 0x0); 13 | 14 | // Enable DLAB (set baud rate divisor) 15 | port_io::outb(COM1 + 3, 0x80); 16 | 17 | // Set divsor to 3 (38400 baud rate) 18 | port_io::outb(COM1 + 0, 0x03); 19 | port_io::outb(COM1 + 1, 0x00); 20 | 21 | // Set data as 8 bits, 1 stop bit, no parity 22 | port_io::outb(COM1 + 3, 0x03); 23 | 24 | // Enable FIFO, clear with 14-byte threshold 25 | port_io::outb(COM1 + 2, 0xC7); 26 | 27 | // Enable IRQs, RTS/DSR set 28 | port_io::outb(COM1 + 4, 0x0B); 29 | } 30 | 31 | vga::okay(); 32 | vga::println("COM1 serial port initialised"); 33 | } 34 | 35 | pub fn read() -> u8 { 36 | unsafe { 37 | while port_io::inb(COM1 + 5) & 0x01 == 0 {} 38 | port_io::inb(COM1) 39 | } 40 | } 41 | 42 | pub fn write(byte: u8) { 43 | unsafe { 44 | while port_io::inb(COM1 + 5) &0x20 == 0 {} 45 | port_io::outb(COM1, byte); 46 | } 47 | } 48 | 49 | pub fn write_char(c: char) { 50 | write(c as u8); 51 | } 52 | 53 | pub fn write_str(str: &str) { 54 | for c in str.chars() { 55 | write_char(c); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /kernel/driver/kbd.rs: -------------------------------------------------------------------------------- 1 | // kbd.rs 2 | // contains methods that enable the user to perform keyboard input 3 | 4 | use arch::dev::port_io; 5 | 6 | const PS2: u16 = 0x60; 7 | 8 | enum MOD { 9 | SHIFT = 0, 10 | CTRL = 1, 11 | ALT = 2 12 | } 13 | 14 | static mut MODIFIERS: [bool; 3] = [false, false, false]; 15 | 16 | // Scancode set 1 (my keyboard uses this) 17 | pub fn get_char() -> Option { 18 | let code = unsafe { port_io::inb(PS2) }; 19 | set_mods(code); 20 | 21 | code_to_char(code) 22 | } 23 | 24 | fn set_mods(code: u8) { 25 | unsafe { 26 | match code { 27 | 0x2A | 0x36 => MODIFIERS[0] = true, 28 | 0xAA | 0xB6 => MODIFIERS[0] = false, 29 | 0x3A => MODIFIERS[0] = !MODIFIERS[0], 30 | 31 | _ => {}, 32 | } 33 | } 34 | } 35 | 36 | fn code_to_char(code: u8) -> Option { 37 | let result; 38 | 39 | unsafe { 40 | if MODIFIERS[0] { 41 | result = get_shift(code); 42 | } else { 43 | result = get_reg(code); 44 | } 45 | } 46 | 47 | result 48 | } 49 | 50 | fn get_shift(code: u8) -> Option { 51 | let result = match code { 52 | // Alphanumeric 53 | 0x1E => 'A', 0x30 => 'B', 0x2E => 'C', 0x20 => 'D', 0x12 => 'E', 54 | 0x21 => 'F', 0x22 => 'G', 0x23 => 'H', 0x17 => 'I', 0x24 => 'J', 55 | 0x25 => 'K', 0x26 => 'L', 0x32 => 'M', 0x31 => 'N', 0x18 => 'O', 56 | 0x19 => 'P', 0x10 => 'Q', 0x13 => 'R', 0x1F => 'S', 0x14 => 'T', 57 | 0x16 => 'U', 0x2F => 'V', 0x11 => 'W', 0x2D => 'X', 0x15 => 'Y', 58 | 0x2C => 'Z', 0x0B => ')', 0x02 => '!', 0x03 => '@', 0x04 => '#', 59 | 0x05 => '$', 0x06 => '%', 0x07 => '^', 0x08 => '&', 0x09 => '*', 60 | 0x0A => '(', 61 | 62 | // Symbols 63 | 0x29 => '~', 0x0C => '_', 0x0D => '+', 0x2B => '|', 0x1A => '{', 64 | 0x1B => '}', 0x27 => ':', 0x28 => '"', 0x33 => '<', 0x34 => '>', 65 | 0x35 => '?', 66 | 67 | // Keypad 68 | 0x37 => '*', 0x4A => '-', 0x4E => '+', 0x53 => '.', 69 | 70 | // Others 71 | 0x39 => ' ', 0x0F => '\t', 0x1C => '\n', 0x0E => '\u{8}', 72 | 73 | // Undefined 74 | _ => return None, 75 | }; 76 | 77 | Some(result) 78 | } 79 | 80 | fn get_reg(code: u8) -> Option { 81 | let result = match code { 82 | // Alphanumeric 83 | 0x1E => 'a', 0x30 => 'b', 0x2E => 'c', 0x20 => 'd', 0x12 => 'e', 84 | 0x21 => 'f', 0x22 => 'g', 0x23 => 'h', 0x17 => 'i', 0x24 => 'j', 85 | 0x25 => 'k', 0x26 => 'l', 0x32 => 'm', 0x31 => 'n', 0x18 => 'o', 86 | 0x19 => 'p', 0x10 => 'q', 0x13 => 'r', 0x1F => 's', 0x14 => 't', 87 | 0x16 => 'u', 0x2F => 'v', 0x11 => 'w', 0x2D => 'x', 0x15 => 'y', 88 | 0x2C => 'z', 0x0B => '0', 0x02 => '1', 0x03 => '2', 0x04 => '3', 89 | 0x05 => '4', 0x06 => '5', 0x07 => '6', 0x08 => '7', 0x09 => '8', 90 | 0x0A => '9', 91 | 92 | // Symbols 93 | 0x29 => '`', 0x0C => '-', 0x0D => '=', 0x2B => '\\', 0x1A => '[', 94 | 0x1B => ']', 0x27 => ';', 0x28 => '\'', 0x33 => ',', 0x34 => '.', 95 | 0x35 => '/', 96 | 97 | // Keypad 98 | 0x37 => '*', 0x4A => '-', 0x4E => '+', 0x53 => '.', 99 | 100 | // Others 101 | 0x39 => ' ', 0x0F => '\t', 0x1C => '\n', 0x0E => '\u{8}', 102 | 103 | // Undefined 104 | _ => return None, 105 | }; 106 | 107 | Some(result) 108 | } 109 | -------------------------------------------------------------------------------- /kernel/driver/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod vga; 2 | pub mod kbd; 3 | pub mod com; 4 | 5 | -------------------------------------------------------------------------------- /kernel/driver/vga.rs: -------------------------------------------------------------------------------- 1 | //vga.rs 2 | //contains methods that address the vga buffer of the system 3 | //eg. print_char, print_line, terminal_clear etc 4 | 5 | use core::fmt; 6 | 7 | static mut VGA_COL: u32 = 0; 8 | static mut VGA_ROW: i32 = 0; 9 | const VGA_W: u32 = 80; 10 | const VGA_H: u32 = 25; 11 | const VGA_BUFF: usize = 0xB8000; 12 | 13 | extern crate rlibc; 14 | 15 | pub fn print_char_at(c: u8, x: u32, y: u32, color: u8) { 16 | let offset : usize = ((y * VGA_W + x) * 2) as usize; 17 | let data : u16 = (color as u16) << 8 | (c as u16); 18 | unsafe { *((VGA_BUFF + offset) as *mut u16) = data; } 19 | } 20 | 21 | pub fn print_char(c: char, color: u8) { 22 | print_byte(c as u8, color); 23 | } 24 | 25 | pub fn print_byte(c: u8, color: u8) { 26 | unsafe { 27 | if VGA_ROW <= -1 { 28 | clear_term(); 29 | VGA_ROW += 1; 30 | } 31 | 32 | match c { 33 | b'\n' => { 34 | VGA_COL = 0; 35 | VGA_ROW += 1; 36 | }, 37 | 38 | b'\t' => VGA_COL += 4, 39 | 40 | 0x08 => { 41 | if VGA_COL == 0 { 42 | VGA_COL = 79; 43 | VGA_ROW -= 1; 44 | } 45 | else { 46 | VGA_COL -= 1 47 | } 48 | 49 | ;print_char_at(b' ', VGA_COL, VGA_ROW as u32, color); 50 | }, 51 | _ => { 52 | print_char_at(c, VGA_COL, VGA_ROW as u32, color); 53 | VGA_COL += 1; 54 | }, 55 | }; 56 | 57 | if VGA_COL as u32 >= VGA_W { 58 | VGA_ROW += 1; 59 | VGA_COL = 0; 60 | } 61 | 62 | if VGA_ROW as u32 >= VGA_H { 63 | VGA_ROW = -1; 64 | } 65 | } 66 | } 67 | 68 | pub fn print(str: &str, color: u8) { 69 | for c in str.chars() { 70 | print_char(c, color); 71 | } 72 | } 73 | 74 | pub fn println(str: &str) { 75 | print(str, 0x07); 76 | print_char('\n', 0x07); 77 | } 78 | 79 | pub fn clear_term() { 80 | //loop through columns and rows, print whitespace char 81 | for x in 0..VGA_W as u32 { 82 | for y in 0..VGA_H as u32 { 83 | let offset : usize = ((y * VGA_W + x) * 2) as usize; 84 | let data : i16 = 0x0720; 85 | unsafe { *((VGA_BUFF + offset) as *mut i16) = data; } 86 | } 87 | } 88 | } 89 | 90 | // Writer structure, used for write! macro 91 | // enables the use of string formatting for debugging mem addresses, etc 92 | pub struct Writer {} 93 | 94 | impl Writer { 95 | pub fn new() -> Writer { 96 | Writer { 97 | 98 | } 99 | } 100 | } 101 | 102 | impl fmt::Write for Writer { 103 | fn write_str(&mut self, s: &str) -> fmt::Result { 104 | for byte in s.bytes() { 105 | print_byte(byte, 0x07); 106 | } 107 | 108 | Ok(()) 109 | } 110 | } 111 | 112 | // Startup information 113 | pub fn info() { 114 | print_char('[', 0x07); 115 | print(" INFO ", 0x06); 116 | print("] ", 0x07); 117 | } 118 | 119 | // Startup successful action 120 | pub fn okay() { 121 | print_char('[', 0x07); 122 | print(" OKAY ", 0x02); 123 | print("] ", 0x07); 124 | } 125 | 126 | // Startup error 127 | pub fn error() { 128 | print_char('[', 0x07); 129 | print(" ERROR ", 0x04); 130 | print("] ", 0x07); 131 | } 132 | 133 | -------------------------------------------------------------------------------- /kernel/lib.rs: -------------------------------------------------------------------------------- 1 | // lib.rs 2 | // the root of the cargo project source file 3 | // main kernel operation is here 4 | 5 | #![no_std] 6 | #![allow(dead_code)] 7 | #![feature(panic_implementation)] 8 | #![feature(core_intrinsics)] 9 | #![feature(lang_items)] 10 | #![feature(asm)] 11 | #![feature(const_fn)] 12 | #![feature(naked_functions)] 13 | #![feature(abi_x86_interrupt)] 14 | #![feature(linkage)] 15 | 16 | #[macro_use] 17 | extern crate lazy_static; 18 | #[macro_use] 19 | extern crate bitflags; 20 | extern crate multiboot2; 21 | 22 | mod driver; 23 | mod arch; 24 | mod utils; 25 | 26 | use core::intrinsics; 27 | use core::panic::PanicInfo; 28 | use driver::vga; 29 | use driver::vga::Writer; 30 | use driver::com; 31 | use core::fmt::Write; 32 | use arch::dev::pic_init; 33 | use arch::dev::pit_init; 34 | use arch::dev::pit; 35 | use arch::x86_64::gdt_init; 36 | use arch::x86_64::idt_init; 37 | use arch::x86_64::int::int; 38 | use utils::qemu; 39 | 40 | // called on system panic -- not implemented yet 41 | #[lang = "eh_personality"] 42 | extern fn eh_personality() {} 43 | 44 | #[panic_handler] 45 | #[no_mangle] 46 | pub extern fn panic_fmt(_info: &PanicInfo) -> ! { 47 | vga::error(); 48 | write!(Writer::new(), " System PANIC!\n") 49 | .expect("Unexpected error in writing panic information!()"); 50 | vga::error(); 51 | write!(Writer::new(), "{}", _info); 52 | 53 | loop{} 54 | } 55 | 56 | #[no_mangle] 57 | pub extern fn kernel_main(mb_info_ptr: usize) -> ! { 58 | let mb_info = unsafe { multiboot2::load(mb_info_ptr) }; 59 | 60 | let elf_sections_tag = mb_info.get_elf_sections() 61 | .expect("ELF sections tag required!"); 62 | 63 | let kernel_start = elf_sections_tag.get_sections().map(|s| s.get_start_addr()) 64 | .min().unwrap(); 65 | let kernel_end = elf_sections_tag.get_sections().map(|s| s.get_start_addr() + s.get_size()) 66 | .max().unwrap(); 67 | let multiboot_start = mb_info_ptr; 68 | let multiboot_end = multiboot_start + (mb_info.total_size() as usize); 69 | 70 | vga::clear_term(); 71 | 72 | vga::print(" _ _ _ _ 73 | _ __ _ _ ___| |_| |__ _ _ ___| | _____| |_ 74 | | '__| | | / __| __| '_ \\| | | |/ __| |/ / _ \\ __| 75 | | | | |_| \\__ \\ |_| |_) | |_| | (__| < __/ |_ 76 | |_| \\__,_|___/\\__|_.__/ \\__,_|\\___|_|\\_\\___|\\__|\n\n", 0x06); 77 | 78 | 79 | vga::print("Welcome to the ", 0x07); 80 | vga::print("rustbucket", 0x06); 81 | vga::println(" kernel!\nStarting boot procedure...\n"); 82 | 83 | vga::info(); 84 | write!(Writer::new(), "Kernel start: {:#X}, kernel end: {:#X}\n", 85 | kernel_start, kernel_end); 86 | vga::info(); 87 | write!(Writer::new(), "Multiboot start: {:#X}, Multiboot end: {:#X}\n\n", multiboot_start, multiboot_end); 88 | 89 | gdt_init(); 90 | idt_init(); 91 | pic_init(); 92 | pit_init(1000); 93 | 94 | int::enable(); 95 | vga::okay(); 96 | vga::println("Enabled interrupts\n"); 97 | 98 | com::init(); 99 | vga::info(); 100 | vga::println("Sending test serial string...\n"); 101 | com::write_str("\nHello from serial!\n"); 102 | 103 | vga::info(); 104 | vga::print("Exiting QEMU in ", 0x07); 105 | 106 | for i in (1..4).rev() { 107 | write!(Writer::new(), "{}...", i); 108 | pit::timer_wait(1000); 109 | } 110 | 111 | qemu::shutdown(); 112 | 113 | //interrupt(); 114 | 115 | loop {} 116 | 117 | // TODO 118 | // ---- 119 | // - Add exception & hardware interrupt handlers to IDT 120 | // - Allocate space for thread stacks 121 | // - Halt the CPU until the next timer interrupt occurs, thereby enabling multi-threading 122 | 123 | // EXTRA 124 | // ----- 125 | // Create dynamic memory allocator 126 | // Create a mini kernel-space command-line 127 | // Begin writing filesystem implementation (filesystems, inodes, file descriptors, etc.) 128 | } 129 | 130 | #[naked] 131 | #[inline(always)] 132 | pub fn interrupt() { 133 | unsafe { 134 | asm!("int3"); 135 | } 136 | } 137 | 138 | #[naked] 139 | #[inline(always)] 140 | pub fn bochs_break() { 141 | unsafe { 142 | asm!("xchg bx, bx" :::: "intel"); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /kernel/utils/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod qemu; 2 | 3 | -------------------------------------------------------------------------------- /kernel/utils/qemu.rs: -------------------------------------------------------------------------------- 1 | // qemu.rs 2 | // utility functions for interacting with the qemu host 3 | 4 | use arch::dev::port_io; 5 | 6 | // Commonly unused port 7 | const PORT: u16 = 0xF4; 8 | 9 | pub fn shutdown() { 10 | unsafe { 11 | port_io::outl(PORT, 0); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /x86_64-rustbucket_os.json: -------------------------------------------------------------------------------- 1 | { 2 | "llvm-target": "x86_64-unknown-none-gnu", 3 | "data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128", 4 | "linker-flavor": "gcc", 5 | "target-endian": "little", 6 | "target-pointer-width": "64", 7 | "target-c-int-width": "32", 8 | "arch": "x86_64", 9 | "os": "none", 10 | "disable-redzone": true, 11 | "features": "-mmx,-sse,+soft-float", 12 | "panic-strategy": "abort" 13 | } 14 | --------------------------------------------------------------------------------