├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── NOTES.md ├── README.md ├── build.rs ├── hello-world ├── Cargo.toml ├── Kbuild ├── Makefile └── src │ └── lib.rs ├── src ├── allocator.rs ├── bindings.rs ├── bindings_helper.h ├── c_types.rs ├── chrdev.rs ├── error.rs ├── file_operations.rs ├── filesystem.rs ├── helpers.c ├── lib.rs ├── printk.rs ├── random.rs ├── sysctl.rs ├── types.rs └── user_ptr.rs ├── testlib ├── Cargo.toml └── src │ └── lib.rs └── tests ├── Kbuild ├── Makefile ├── chrdev-region-allocation ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── chrdev ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── filesystem ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── modinfo ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── printk ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── random ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── run_tests.py ├── sysctl-get ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs ├── sysctl ├── Cargo.toml ├── src │ └── lib.rs └── tests │ └── tests.rs └── utils ├── Cargo.toml ├── src └── lib.rs └── tests └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | **/target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .cache.mk 5 | .*o.cmd 6 | .tmp_versions/ 7 | Module.symvers 8 | *.ko 9 | *.mod.c 10 | *.o 11 | modules.order 12 | dummy.c 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | matrix: 2 | include: 3 | - dist: bionic 4 | 5 | language: rust 6 | rust: 7 | - nightly-2020-08-27 8 | 9 | branches: 10 | only: 11 | - master 12 | 13 | install: 14 | - sudo apt-get install -y "linux-headers-$(uname -r)" coreutils 15 | - sudo apt-get install clang-9 16 | - rustup component add rust-src rustfmt clippy 17 | 18 | script: 19 | - CLANG=clang-9 ./tests/run_tests.py 20 | - | 21 | for p in . hello-world tests/*; do 22 | if [ -d "$p" ]; then 23 | (cd "$p" && cargo fmt --all -- --check) || exit 1 24 | fi 25 | done 26 | 27 | after_failure: 28 | - dmesg 29 | 30 | notifications: 31 | email: false 32 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting Alex Gaynor and/or Geoffrey Thomas . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We're always excited to have contributions of any form! 4 | 5 | Examples of contributions include: 6 | 7 | * Code patches 8 | * Documentation improvements 9 | * Bug reports and patch reviews 10 | 11 | ## Filing issues 12 | 13 | If you're filing an issue for a build error, please include enough information 14 | for us to diagnose and reproduce the issue. This generally means, at a minimum 15 | the kernel version (and, if it's not a vanilla upstream kernel, where you got 16 | the kernel from) and your compiler versions (Rust, Clang, and GCC). 17 | 18 | ## Contributing code 19 | 20 | To contribute code, you can send a pull request on Github. Please make sure your 21 | code is formatted with `cargo fmt`, builds, the tests pass, and it's `cargo 22 | clippy`-clean. Don't worry, we've got continuous integration if you miss 23 | anything. 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "linux-kernel-module" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | bitflags = "1" 9 | 10 | [build-dependencies] 11 | bindgen = "0.54" 12 | cc = "1.0" 13 | shlex = "0.1" 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /NOTES.md: -------------------------------------------------------------------------------- 1 | [DomminusCarnufex rs-kernel](https://dominuscarnufex.github.io/cours/rs-kernel/en.html) 2 | === 3 | 4 | This one adds a syscall to the Linux kernel and rebuilds it. The important steps: 5 | 6 | * add a Makefile rule to build an rlib (an ar archive) using `rustc`, 7 | specifying `#![crate_type="rlib"]` in the source 8 | * extract the `.o` file from the rlib, and rename it to match the expected name 9 | * add the `.o` file to `obj-y` 10 | 11 | They also edit the syscall interrupt handler (in asm) to dispatch to 12 | their syscalls. 13 | 14 | No reference to lang items. It uses stable `#[no_std]` without `#[no_core]` - 15 | I'd expect the resulting object file just happens not to reference libcore, but 16 | more complicated objects could. 17 | 18 | No custom compiler flags etc. other than `#[no_std]`. 19 | 20 | [saschagrunert/kmod](https://github.com/saschagrunert/kmod) 21 | === 22 | 23 | A custom Makefile drives the build, by copying a Makefile.in that looks 24 | like a normal Linux module Makefile to a build directory, and then 25 | invoking the usual `make -C /lib/modules/$(uname -r)/build M=$PWD` (see 26 | [Documentation/kbuild/modules.txt](https://www.kernel.org/doc/Documentation/kbuild/modules.txt) 27 | ). 28 | 29 | The custom Makefile sets `RUSTCFLAGS` to 30 | `-O -C code-model=kernel -C relocation-model=static`. 31 | 32 | There's also a `module.c` file containing the usual `MODULE_LICENSE` 33 | etc. macros, plus prototypes for `init_module` and `cleanup_module`. 34 | 35 | Makefile.in does the following: 36 | 37 | * build the module with `cargo rustc`, specifiyng 38 | `crate_type = ['staticlib']` in Cargo.toml 39 | * set `foo-objs := module.o libfoo.a` (note that order is significant: 40 | as with shared libraries, static libraries need to come after things 41 | that depend on them) 42 | * set `obj-m := foo.o` 43 | 44 | (The `foo-objs` syntax is for "composite objects," which is documented in 45 | [Documentation/kbuild/makefiles.txt](https://kernel.org/doc/Documentation/kbuild/makefiles.txt) 46 | section 3.3, except for the bit where `-objs` is synonymous to `-y`; see 47 | [scripts/Makefile.lib](https://github.com/torvalds/linux/blob/master/scripts/Makefile.lib) 48 | for that. It works by combining the listed objects with `ld -r` aka 49 | `--relocatable` to generate `foo.o`.) 50 | 51 | I couldn't get the out-of-tree build to work right with my 3.16 (Debian 52 | oldstable) kernel; it builds fine if you get rid of the extra Makefile 53 | (rename Makefile.in to Makefile) and get rid of the `src` variable there, 54 | making it build in-tree. 55 | 56 | kmod includes two other source files besides `lib.rs` and `module.c`, 57 | which aren't very interesting. `lang_items.rs` has ~empty 58 | implementations of all three lang-items, and `print.rs` has a 59 | straightforward FFI binding to `printk`, plus a macro called `println!` 60 | that doesn't actually implement the format-string logic. These should be 61 | wired up to Linux's unwinding / OOPSing mechanisms and to `core::fmt` 62 | respectively. 63 | 64 | I can replicate the Makefile parts of this by themselves. The following 65 | Makefile successfully links a kernel module out of one.rs and two.c: 66 | 67 | ```make 68 | obj-m := three.o 69 | three-objs := two.o libone.a 70 | lib%.a: %.rs 71 | rustc -o $@ -O $< 72 | ``` 73 | 74 | (Since the point of this Makefile is just to make linking work, I'm 75 | being lazy and _not_ specifying `#![no_std]` in the Rust source; libstd 76 | gets copied into `libone.a` but the linker eliminates it as dead code 77 | when building `three.c`. That lets me avoid thinking about lang-items.) 78 | 79 | [tsgates/rust.ko](https://github.com/tsgates/rust.ko) 80 | === 81 | 82 | This one is much older (2013, last updated 2016) but much more complete. 83 | It brings up a couple of important points: 84 | 85 | * You need a custom target file to set things like `disable_redzone` and 86 | no use of floating point. (Their custom target file also sets 87 | `code-model` to `kernel` and `relocation-model` to `static`, as with 88 | the previous one.) 89 | - Apparently you can just use "+soft-float" in target features these 90 | days, See [this comment on rust-lang/rfcs#1364](https://github.com/rust-lang/rfcs/issues/1364#issuecomment-234404686). 91 | * The kernel internal ABI has no guarantees at all, and you want to write 92 | against the kernel C API, using bindgen. 93 | - One limitation is that bindgen doesn't support C macros. 94 | 95 | [pmj/rustykext](https://github.com/pmj/rustykext) 96 | === 97 | 98 | MacOS. Also uses `-C soft-float` and `-C no-redzone=y` (and `-C 99 | no-stack-check`, which is no longer necessary). 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Linux kernel modules in safe Rust 2 | 3 | **For most purposes, if you're interested in writing Linux kernel modules in Rust, you should look at https://github.com/Rust-for-Linux/linux, which is an effort to contribute that process to the upstream kernel.** 4 | 5 | This is a framework for writing loadable Linux kernel modules in Rust, 6 | using safe abstractions around kernel interfaces and primitives. 7 | 8 | For more information on the motivation and goals for this project, check 9 | out [our presentation at Linux Security Summit North America 10 | 2019](https://ldpreload.com/p/kernel-modules-in-rust-lssna2019.pdf) 11 | and the [video on YouTube](https://www.youtube.com/watch?v=RyY01fRyGhM). 12 | We're immediately focusing on making this project viable for out-of-tree 13 | modules, but we also see this project as a testing ground for whether 14 | in-tree components could be written in Rust. 15 | 16 | There is a simple demo module in the hello-world directory, as well as 17 | various other examples in the tests/ directory. 18 | 19 | ## Design 20 | 21 | We run [bindgen](https://github.com/rust-lang/rust-bindgen) on the 22 | kernel headers to generate automatic Rust FFI bindings. bindgen is 23 | powered by [Clang](https://clang.llvm.org), so we use the kernel's 24 | own build system to determine the appropriate CFLAGS. Then we write safe 25 | bindings to these types (see the various files inside `src/`). 26 | 27 | Each kernel module in Rust lives in a `staticlib` crate, which generates 28 | a `.a` file. We pass this object to the Linux kernel's own module build 29 | system for linking into a `.ko`. 30 | 31 | The kernel is inherently multi-threaded: kernel resources can be 32 | accessed from multiple userspace processes at once, which causes 33 | multiple threads of execution inside the kernel to handle system calls 34 | (or interrupts). Therefore, the `KernelModule` type is 35 | [`Sync`](https://doc.rust-lang.org/book/ch16-04-extensible-concurrency-sync-and-send.html), 36 | so all data shared by a kernel module must be safe to access 37 | concurrently (such as by implementing locking). 38 | 39 | ## System requirements 40 | 41 | We're currently only running CI on Linux 4.15 (Ubuntu Xenial) on amd64, 42 | although we intend to support kernels from 4.4 through the latest 43 | release. Please report a bug (or better yet, send in a patch!) if your 44 | kernel doesn't work. 45 | 46 | Other architectures aren't implemented yet, but should work as long as 47 | there's Rust and LLVM support - see [#112][] 48 | for expected status. They'll need `src/c_types.rs` ported, too. 49 | 50 | You'll need to have [Rust](https://www.rust-lang.org) - in particular 51 | Rust nightly, as we use [some unstable 52 | features](https://github.com/fishinabarrel/linux-kernel-module-rust/issues/41) - 53 | and [Clang](https://clang.llvm.org) installed. You need LLVM/Clang 9 54 | (released September 2019) or higher for multiple reasons, primarily 55 | [support for `asm goto`][]. If you're on Debian, Ubuntu, or a derivative, 56 | https://apt.llvm.org is great. 57 | 58 | If the binary named `clang` is too old, make sure to set the `CC` or 59 | `CLANG` environment variable appropriately, e.g., `CC=clang-9`. 60 | 61 | Very recent kernels may require newer versions of Clang - try Clang 11 62 | if older versions don't work for you. 63 | 64 | [#112]: https://github.com/fishinabarrel/linux-kernel-module-rust/issues/112 65 | [support for `asm goto`]: https://github.com/fishinabarrel/linux-kernel-module-rust/issues/123 66 | 67 | ## Building hello-world 68 | 69 | 1. Install clang, kernel headers, and the `rust-src` and `rustfmt` components 70 | from `rustup`: 71 | 72 | ``` 73 | apt-get install llvm clang linux-headers-"$(uname -r)" # or the equivalent for your OS 74 | rustup component add --toolchain=nightly rust-src rustfmt 75 | ``` 76 | 77 | 2. cd to one of the examples 78 | 79 | ``` 80 | cd hello-world 81 | ``` 82 | 83 | 3. Build the kernel module using the Linux kernel build system (kbuild), this 84 | will invoke `cargo` to build the Rust code 85 | 86 | ``` 87 | make 88 | ``` 89 | 90 | 4. Load and unload the module! 91 | 92 | ``` 93 | sudo insmod helloworld.ko 94 | sudo rmmod helloworld 95 | dmesg | tail 96 | ``` 97 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::io::{BufRead, BufReader}; 2 | use std::path::PathBuf; 3 | use std::{env, fs}; 4 | 5 | const INCLUDED_TYPES: &[&str] = &["file_system_type", "mode_t", "umode_t", "ctl_table"]; 6 | const INCLUDED_FUNCTIONS: &[&str] = &[ 7 | "cdev_add", 8 | "cdev_init", 9 | "cdev_del", 10 | "register_filesystem", 11 | "unregister_filesystem", 12 | "krealloc", 13 | "kfree", 14 | "mount_nodev", 15 | "kill_litter_super", 16 | "register_sysctl", 17 | "unregister_sysctl_table", 18 | "access_ok", 19 | "_copy_to_user", 20 | "_copy_from_user", 21 | "alloc_chrdev_region", 22 | "unregister_chrdev_region", 23 | "wait_for_random_bytes", 24 | "get_random_bytes", 25 | "rng_is_initialized", 26 | "printk", 27 | "add_device_randomness", 28 | ]; 29 | const INCLUDED_VARS: &[&str] = &[ 30 | "EINVAL", 31 | "ENOMEM", 32 | "ESPIPE", 33 | "EFAULT", 34 | "EAGAIN", 35 | "__this_module", 36 | "FS_REQUIRES_DEV", 37 | "FS_BINARY_MOUNTDATA", 38 | "FS_HAS_SUBTYPE", 39 | "FS_USERNS_MOUNT", 40 | "FS_RENAME_DOES_D_MOVE", 41 | "BINDINGS_GFP_KERNEL", 42 | "KERN_INFO", 43 | "VERIFY_WRITE", 44 | "LINUX_VERSION_CODE", 45 | "SEEK_SET", 46 | "SEEK_CUR", 47 | "SEEK_END", 48 | "O_NONBLOCK", 49 | ]; 50 | const OPAQUE_TYPES: &[&str] = &[ 51 | // These need to be opaque because they're both packed and aligned, which rustc 52 | // doesn't support yet. See https://github.com/rust-lang/rust/issues/59154 53 | // and https://github.com/rust-lang/rust-bindgen/issues/1538 54 | "desc_struct", 55 | "xregs_state", 56 | ]; 57 | 58 | fn handle_kernel_version_cfg(bindings_path: &PathBuf) { 59 | let f = BufReader::new(fs::File::open(bindings_path).unwrap()); 60 | let mut version = None; 61 | for line in f.lines() { 62 | let line = line.unwrap(); 63 | if let Some(type_and_value) = line.split("pub const LINUX_VERSION_CODE").nth(1) { 64 | if let Some(value) = type_and_value.split('=').nth(1) { 65 | let raw_version = value.split(';').next().unwrap(); 66 | version = Some(raw_version.trim().parse::().unwrap()); 67 | break; 68 | } 69 | } 70 | } 71 | let version = version.expect("Couldn't find kernel version"); 72 | let (major, minor) = match version.to_be_bytes() { 73 | [0, 0, 0, 0, 0, major, minor, _patch] => (major, minor), 74 | _ => panic!("unable to parse LINUX_VERSION_CODE {:x}", version), 75 | }; 76 | 77 | if major >= 6 { 78 | panic!("Please update build.rs with the last 5.x version"); 79 | // Change this block to major >= 7, copy the below block for 80 | // major >= 6, fill in unimplemented!() for major >= 5 81 | } 82 | if major >= 5 { 83 | for x in 0..=if major > 5 { unimplemented!() } else { minor } { 84 | println!("cargo:rustc-cfg=kernel_5_{}_0_or_greater", x); 85 | } 86 | } 87 | if major >= 4 { 88 | // We don't currently support anything older than 4.4 89 | for x in 4..=if major > 4 { 20 } else { minor } { 90 | println!("cargo:rustc-cfg=kernel_4_{}_0_or_greater", x); 91 | } 92 | } 93 | } 94 | 95 | fn handle_kernel_symbols_cfg(symvers_path: &PathBuf) { 96 | let f = BufReader::new(fs::File::open(symvers_path).unwrap()); 97 | for line in f.lines() { 98 | let line = line.unwrap(); 99 | if let Some(symbol) = line.split_ascii_whitespace().nth(1) { 100 | if symbol == "setfl" { 101 | println!("cargo:rustc-cfg=kernel_aufs_setfl"); 102 | break; 103 | } 104 | } 105 | } 106 | } 107 | 108 | // Takes the CFLAGS from the kernel Makefile and changes all the include paths to be absolute 109 | // instead of relative. 110 | fn prepare_cflags(cflags: &str, kernel_dir: &str) -> Vec { 111 | let cflag_parts = shlex::split(&cflags).unwrap(); 112 | let mut cflag_iter = cflag_parts.iter(); 113 | let mut kernel_args = vec![]; 114 | while let Some(arg) = cflag_iter.next() { 115 | if arg.starts_with("-I") && !arg.starts_with("-I/") { 116 | kernel_args.push(format!("-I{}/{}", kernel_dir, &arg[2..])); 117 | } else if arg == "-include" { 118 | kernel_args.push(arg.to_string()); 119 | let include_path = cflag_iter.next().unwrap(); 120 | if include_path.starts_with('/') { 121 | kernel_args.push(include_path.to_string()); 122 | } else { 123 | kernel_args.push(format!("{}/{}", kernel_dir, include_path)); 124 | } 125 | } else { 126 | kernel_args.push(arg.to_string()); 127 | } 128 | } 129 | kernel_args 130 | } 131 | 132 | fn main() { 133 | println!("cargo:rerun-if-env-changed=CC"); 134 | println!("cargo:rerun-if-env-changed=KDIR"); 135 | println!("cargo:rerun-if-env-changed=c_flags"); 136 | 137 | let kernel_dir = env::var("KDIR").expect("Must be invoked from kernel makefile"); 138 | let kernel_cflags = env::var("c_flags").expect("Add 'export c_flags' to Kbuild"); 139 | let kbuild_cflags_module = 140 | env::var("KBUILD_CFLAGS_MODULE").expect("Must be invoked from kernel makefile"); 141 | 142 | let cflags = format!("{} {}", kernel_cflags, kbuild_cflags_module); 143 | let kernel_args = prepare_cflags(&cflags, &kernel_dir); 144 | 145 | let target = env::var("TARGET").unwrap(); 146 | 147 | let mut builder = bindgen::Builder::default() 148 | .use_core() 149 | .ctypes_prefix("c_types") 150 | .derive_default(true) 151 | .size_t_is_usize(true) 152 | .rustfmt_bindings(true); 153 | 154 | builder = builder.clang_arg(format!("--target={}", target)); 155 | for arg in kernel_args.iter() { 156 | builder = builder.clang_arg(arg.clone()); 157 | } 158 | 159 | println!("cargo:rerun-if-changed=src/bindings_helper.h"); 160 | builder = builder.header("src/bindings_helper.h"); 161 | 162 | for t in INCLUDED_TYPES { 163 | builder = builder.whitelist_type(t); 164 | } 165 | for f in INCLUDED_FUNCTIONS { 166 | builder = builder.whitelist_function(f); 167 | } 168 | for v in INCLUDED_VARS { 169 | builder = builder.whitelist_var(v); 170 | } 171 | for t in OPAQUE_TYPES { 172 | builder = builder.opaque_type(t); 173 | } 174 | let bindings = builder.generate().expect("Unable to generate bindings"); 175 | 176 | let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 177 | bindings 178 | .write_to_file(out_path.join("bindings.rs")) 179 | .expect("Couldn't write bindings!"); 180 | 181 | handle_kernel_version_cfg(&out_path.join("bindings.rs")); 182 | handle_kernel_symbols_cfg(&PathBuf::from(&kernel_dir).join("Module.symvers")); 183 | 184 | let mut builder = cc::Build::new(); 185 | builder.compiler(env::var("CC").unwrap_or_else(|_| "clang".to_string())); 186 | builder.target(&target); 187 | builder.warnings(false); 188 | println!("cargo:rerun-if-changed=src/helpers.c"); 189 | builder.file("src/helpers.c"); 190 | for arg in kernel_args.iter() { 191 | builder.flag(&arg); 192 | } 193 | builder.compile("helpers"); 194 | } 195 | -------------------------------------------------------------------------------- /hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world" 3 | version = "0.1.0" 4 | authors = ["Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | 10 | [dependencies] 11 | linux-kernel-module = { path = ".." } 12 | -------------------------------------------------------------------------------- /hello-world/Kbuild: -------------------------------------------------------------------------------- 1 | obj-m := helloworld.o 2 | helloworld-objs := hello_world.rust.o 3 | 4 | CARGO ?= cargo 5 | 6 | export c_flags 7 | 8 | $(src)/target/x86_64-linux-kernel/debug/libhello_world.a: cargo_will_determine_dependencies 9 | cd $(src); $(CARGO) build -Z build-std=core,alloc --target=x86_64-linux-kernel 10 | 11 | .PHONY: cargo_will_determine_dependencies 12 | 13 | %.rust.o: target/x86_64-linux-kernel/debug/lib%.a 14 | $(LD) -r -o $@ --whole-archive $< 15 | -------------------------------------------------------------------------------- /hello-world/Makefile: -------------------------------------------------------------------------------- 1 | export KDIR ?= /lib/modules/$(shell uname -r)/build 2 | 3 | CLANG ?= clang 4 | ifeq ($(origin CC),default) 5 | CC := ${CLANG} 6 | endif 7 | 8 | all: 9 | $(MAKE) -C $(KDIR) M=$(CURDIR) CC=$(CC) CONFIG_CC_IS_CLANG=y 10 | 11 | clean: 12 | $(MAKE) -C $(KDIR) M=$(CURDIR) CC=$(CC) clean 13 | -------------------------------------------------------------------------------- /hello-world/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | extern crate alloc; 4 | 5 | use alloc::borrow::ToOwned; 6 | use alloc::string::String; 7 | 8 | use linux_kernel_module::println; 9 | 10 | struct HelloWorldModule { 11 | message: String, 12 | } 13 | 14 | impl linux_kernel_module::KernelModule for HelloWorldModule { 15 | fn init() -> linux_kernel_module::KernelResult { 16 | println!("Hello kernel module!"); 17 | Ok(HelloWorldModule { 18 | message: "on the heap!".to_owned(), 19 | }) 20 | } 21 | } 22 | 23 | impl Drop for HelloWorldModule { 24 | fn drop(&mut self) { 25 | println!("My message is {}", self.message); 26 | println!("Goodbye kernel module!"); 27 | } 28 | } 29 | 30 | linux_kernel_module::kernel_module!( 31 | HelloWorldModule, 32 | author: b"Fish in a Barrel Contributors", 33 | description: b"An extremely simple kernel module", 34 | license: b"GPL" 35 | ); 36 | -------------------------------------------------------------------------------- /src/allocator.rs: -------------------------------------------------------------------------------- 1 | use core::alloc::{GlobalAlloc, Layout}; 2 | use core::ptr; 3 | 4 | use crate::bindings; 5 | use crate::c_types; 6 | 7 | pub struct KernelAllocator; 8 | 9 | unsafe impl GlobalAlloc for KernelAllocator { 10 | unsafe fn alloc(&self, layout: Layout) -> *mut u8 { 11 | // krealloc is used instead of kmalloc because kmalloc is an inline function and can't be 12 | // bound to as a result 13 | bindings::krealloc(ptr::null(), layout.size(), bindings::GFP_KERNEL) as *mut u8 14 | } 15 | 16 | unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 17 | bindings::kfree(ptr as *const c_types::c_void); 18 | } 19 | } 20 | 21 | #[alloc_error_handler] 22 | fn oom(_layout: Layout) -> ! { 23 | panic!("Out of memory!"); 24 | } 25 | -------------------------------------------------------------------------------- /src/bindings.rs: -------------------------------------------------------------------------------- 1 | #[allow( 2 | clippy::all, 3 | non_camel_case_types, 4 | non_upper_case_globals, 5 | non_snake_case, 6 | improper_ctypes 7 | )] 8 | mod bindings { 9 | use crate::c_types; 10 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 11 | } 12 | pub use bindings::*; 13 | 14 | pub const GFP_KERNEL: gfp_t = BINDINGS_GFP_KERNEL; 15 | -------------------------------------------------------------------------------- /src/bindings_helper.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | // Bindgen gets confused at certain things 10 | // 11 | const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL; 12 | -------------------------------------------------------------------------------- /src/c_types.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types)] 2 | 3 | #[cfg(target_arch = "x86_64")] 4 | mod c { 5 | use core::ffi; 6 | 7 | pub type c_int = i32; 8 | pub type c_char = i8; 9 | pub type c_long = i64; 10 | pub type c_longlong = i64; 11 | pub type c_short = i16; 12 | pub type c_uchar = u8; 13 | pub type c_uint = u32; 14 | pub type c_ulong = u64; 15 | pub type c_ulonglong = u64; 16 | pub type c_ushort = u16; 17 | pub type c_schar = i8; 18 | pub type c_size_t = usize; 19 | pub type c_ssize_t = isize; 20 | pub type c_void = ffi::c_void; 21 | } 22 | 23 | pub use c::*; 24 | -------------------------------------------------------------------------------- /src/chrdev.rs: -------------------------------------------------------------------------------- 1 | use core::convert::TryInto; 2 | use core::mem; 3 | use core::ops::Range; 4 | 5 | use alloc::boxed::Box; 6 | use alloc::vec; 7 | use alloc::vec::Vec; 8 | 9 | use crate::bindings; 10 | use crate::c_types; 11 | use crate::error::{Error, KernelResult}; 12 | use crate::file_operations; 13 | use crate::types::CStr; 14 | 15 | pub fn builder(name: CStr<'static>, minors: Range) -> KernelResult { 16 | Ok(Builder { 17 | name, 18 | minors, 19 | file_ops: vec![], 20 | }) 21 | } 22 | 23 | pub struct Builder { 24 | name: CStr<'static>, 25 | minors: Range, 26 | file_ops: Vec<&'static bindings::file_operations>, 27 | } 28 | 29 | impl Builder { 30 | pub fn register_device(mut self) -> Builder { 31 | if self.file_ops.len() >= self.minors.len() { 32 | panic!("More devices registered than minor numbers allocated.") 33 | } 34 | self.file_ops 35 | .push(&file_operations::FileOperationsVtable::::VTABLE); 36 | self 37 | } 38 | 39 | pub fn build(self) -> KernelResult { 40 | let mut dev: bindings::dev_t = 0; 41 | let res = unsafe { 42 | bindings::alloc_chrdev_region( 43 | &mut dev, 44 | self.minors.start.into(), 45 | self.minors.len().try_into()?, 46 | self.name.as_ptr() as *const c_types::c_char, 47 | ) 48 | }; 49 | if res != 0 { 50 | return Err(Error::from_kernel_errno(res)); 51 | } 52 | 53 | // Turn this into a boxed slice immediately because the kernel stores pointers into it, and 54 | // so that data should never be moved. 55 | let mut cdevs = vec![unsafe { mem::zeroed() }; self.file_ops.len()].into_boxed_slice(); 56 | for (i, file_op) in self.file_ops.iter().enumerate() { 57 | unsafe { 58 | bindings::cdev_init(&mut cdevs[i], *file_op); 59 | cdevs[i].owner = &mut bindings::__this_module; 60 | let rc = bindings::cdev_add(&mut cdevs[i], dev + i as bindings::dev_t, 1); 61 | if rc != 0 { 62 | // Clean up the ones that were allocated. 63 | for j in 0..=i { 64 | bindings::cdev_del(&mut cdevs[j]); 65 | } 66 | bindings::unregister_chrdev_region(dev, self.minors.len() as _); 67 | return Err(Error::from_kernel_errno(rc)); 68 | } 69 | } 70 | } 71 | 72 | Ok(Registration { 73 | dev, 74 | count: self.minors.len(), 75 | cdevs, 76 | }) 77 | } 78 | } 79 | 80 | pub struct Registration { 81 | dev: bindings::dev_t, 82 | count: usize, 83 | cdevs: Box<[bindings::cdev]>, 84 | } 85 | 86 | // This is safe because Registration doesn't actually expose any methods. 87 | unsafe impl Sync for Registration {} 88 | 89 | impl Drop for Registration { 90 | fn drop(&mut self) { 91 | unsafe { 92 | for dev in self.cdevs.iter_mut() { 93 | bindings::cdev_del(dev); 94 | } 95 | bindings::unregister_chrdev_region(self.dev, self.count as _); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use core::num::TryFromIntError; 2 | 3 | use crate::bindings; 4 | use crate::c_types; 5 | 6 | pub struct Error(c_types::c_int); 7 | 8 | impl Error { 9 | pub const EINVAL: Self = Error(-(bindings::EINVAL as i32)); 10 | pub const ENOMEM: Self = Error(-(bindings::ENOMEM as i32)); 11 | pub const EFAULT: Self = Error(-(bindings::EFAULT as i32)); 12 | pub const ESPIPE: Self = Error(-(bindings::ESPIPE as i32)); 13 | pub const EAGAIN: Self = Error(-(bindings::EAGAIN as i32)); 14 | 15 | pub fn from_kernel_errno(errno: c_types::c_int) -> Error { 16 | Error(errno) 17 | } 18 | 19 | pub fn to_kernel_errno(&self) -> c_types::c_int { 20 | self.0 21 | } 22 | } 23 | 24 | impl From for Error { 25 | fn from(_: TryFromIntError) -> Error { 26 | Error::EINVAL 27 | } 28 | } 29 | 30 | pub type KernelResult = Result; 31 | -------------------------------------------------------------------------------- /src/file_operations.rs: -------------------------------------------------------------------------------- 1 | use core::convert::{TryFrom, TryInto}; 2 | use core::{marker, mem, ptr}; 3 | 4 | use alloc::boxed::Box; 5 | 6 | use crate::bindings; 7 | use crate::c_types; 8 | use crate::error::{Error, KernelResult}; 9 | use crate::user_ptr::{UserSlicePtr, UserSlicePtrReader, UserSlicePtrWriter}; 10 | 11 | bitflags::bitflags! { 12 | pub struct FileFlags: c_types::c_uint { 13 | const NONBLOCK = bindings::O_NONBLOCK; 14 | } 15 | } 16 | 17 | pub struct File { 18 | ptr: *const bindings::file, 19 | } 20 | 21 | impl File { 22 | unsafe fn from_ptr(ptr: *const bindings::file) -> File { 23 | File { ptr } 24 | } 25 | 26 | pub fn pos(&self) -> u64 { 27 | unsafe { (*self.ptr).f_pos as u64 } 28 | } 29 | 30 | pub fn flags(&self) -> FileFlags { 31 | FileFlags::from_bits_truncate(unsafe { (*self.ptr).f_flags }) 32 | } 33 | } 34 | 35 | // Matches std::io::SeekFrom in the Rust stdlib 36 | pub enum SeekFrom { 37 | Start(u64), 38 | End(i64), 39 | Current(i64), 40 | } 41 | 42 | unsafe extern "C" fn open_callback( 43 | _inode: *mut bindings::inode, 44 | file: *mut bindings::file, 45 | ) -> c_types::c_int { 46 | let f = match T::open() { 47 | Ok(f) => Box::new(f), 48 | Err(e) => return e.to_kernel_errno(), 49 | }; 50 | (*file).private_data = Box::into_raw(f) as *mut c_types::c_void; 51 | 0 52 | } 53 | 54 | unsafe extern "C" fn read_callback( 55 | file: *mut bindings::file, 56 | buf: *mut c_types::c_char, 57 | len: c_types::c_size_t, 58 | offset: *mut bindings::loff_t, 59 | ) -> c_types::c_ssize_t { 60 | let mut data = match UserSlicePtr::new(buf as *mut c_types::c_void, len) { 61 | Ok(ptr) => ptr.writer(), 62 | Err(e) => return e.to_kernel_errno().try_into().unwrap(), 63 | }; 64 | let f = &*((*file).private_data as *const T); 65 | // No FMODE_UNSIGNED_OFFSET support, so offset must be in [0, 2^63). 66 | // See discussion in #113 67 | let positive_offset = match (*offset).try_into() { 68 | Ok(v) => v, 69 | Err(_) => return Error::EINVAL.to_kernel_errno().try_into().unwrap(), 70 | }; 71 | let read = T::READ.unwrap(); 72 | match read(f, &File::from_ptr(file), &mut data, positive_offset) { 73 | Ok(()) => { 74 | let written = len - data.len(); 75 | (*offset) += bindings::loff_t::try_from(written).unwrap(); 76 | written.try_into().unwrap() 77 | } 78 | Err(e) => e.to_kernel_errno().try_into().unwrap(), 79 | } 80 | } 81 | 82 | unsafe extern "C" fn write_callback( 83 | file: *mut bindings::file, 84 | buf: *const c_types::c_char, 85 | len: c_types::c_size_t, 86 | offset: *mut bindings::loff_t, 87 | ) -> c_types::c_ssize_t { 88 | let mut data = match UserSlicePtr::new(buf as *mut c_types::c_void, len) { 89 | Ok(ptr) => ptr.reader(), 90 | Err(e) => return e.to_kernel_errno().try_into().unwrap(), 91 | }; 92 | let f = &*((*file).private_data as *const T); 93 | // No FMODE_UNSIGNED_OFFSET support, so offset must be in [0, 2^63). 94 | // See discussion in #113 95 | let positive_offset = match (*offset).try_into() { 96 | Ok(v) => v, 97 | Err(_) => return Error::EINVAL.to_kernel_errno().try_into().unwrap(), 98 | }; 99 | let write = T::WRITE.unwrap(); 100 | match write(f, &mut data, positive_offset) { 101 | Ok(()) => { 102 | let read = len - data.len(); 103 | (*offset) += bindings::loff_t::try_from(read).unwrap(); 104 | read.try_into().unwrap() 105 | } 106 | Err(e) => e.to_kernel_errno().try_into().unwrap(), 107 | } 108 | } 109 | 110 | unsafe extern "C" fn release_callback( 111 | _inode: *mut bindings::inode, 112 | file: *mut bindings::file, 113 | ) -> c_types::c_int { 114 | let ptr = mem::replace(&mut (*file).private_data, ptr::null_mut()); 115 | drop(Box::from_raw(ptr as *mut T)); 116 | 0 117 | } 118 | 119 | unsafe extern "C" fn llseek_callback( 120 | file: *mut bindings::file, 121 | offset: bindings::loff_t, 122 | whence: c_types::c_int, 123 | ) -> bindings::loff_t { 124 | let off = match whence as u32 { 125 | bindings::SEEK_SET => match offset.try_into() { 126 | Ok(v) => SeekFrom::Start(v), 127 | Err(_) => return Error::EINVAL.to_kernel_errno().into(), 128 | }, 129 | bindings::SEEK_CUR => SeekFrom::Current(offset), 130 | bindings::SEEK_END => SeekFrom::End(offset), 131 | _ => return Error::EINVAL.to_kernel_errno().into(), 132 | }; 133 | let f = &*((*file).private_data as *const T); 134 | let seek = T::SEEK.unwrap(); 135 | match seek(f, &File::from_ptr(file), off) { 136 | Ok(off) => off as bindings::loff_t, 137 | Err(e) => e.to_kernel_errno().into(), 138 | } 139 | } 140 | 141 | pub(crate) struct FileOperationsVtable(marker::PhantomData); 142 | 143 | impl FileOperationsVtable { 144 | pub(crate) const VTABLE: bindings::file_operations = bindings::file_operations { 145 | open: Some(open_callback::), 146 | release: Some(release_callback::), 147 | read: if let Some(_) = T::READ { 148 | Some(read_callback::) 149 | } else { 150 | None 151 | }, 152 | write: if let Some(_) = T::WRITE { 153 | Some(write_callback::) 154 | } else { 155 | None 156 | }, 157 | llseek: if let Some(_) = T::SEEK { 158 | Some(llseek_callback::) 159 | } else { 160 | None 161 | }, 162 | 163 | #[cfg(not(kernel_4_9_0_or_greater))] 164 | aio_fsync: None, 165 | check_flags: None, 166 | #[cfg(all(kernel_4_5_0_or_greater, not(kernel_4_20_0_or_greater)))] 167 | clone_file_range: None, 168 | compat_ioctl: None, 169 | #[cfg(kernel_4_5_0_or_greater)] 170 | copy_file_range: None, 171 | #[cfg(all(kernel_4_5_0_or_greater, not(kernel_4_20_0_or_greater)))] 172 | dedupe_file_range: None, 173 | fallocate: None, 174 | #[cfg(kernel_4_19_0_or_greater)] 175 | fadvise: None, 176 | fasync: None, 177 | flock: None, 178 | flush: None, 179 | fsync: None, 180 | get_unmapped_area: None, 181 | iterate: None, 182 | #[cfg(kernel_4_7_0_or_greater)] 183 | iterate_shared: None, 184 | #[cfg(kernel_5_1_0_or_greater)] 185 | iopoll: None, 186 | lock: None, 187 | mmap: None, 188 | #[cfg(kernel_4_15_0_or_greater)] 189 | mmap_supported_flags: 0, 190 | owner: ptr::null_mut(), 191 | poll: None, 192 | read_iter: None, 193 | #[cfg(kernel_4_20_0_or_greater)] 194 | remap_file_range: None, 195 | sendpage: None, 196 | #[cfg(kernel_aufs_setfl)] 197 | setfl: None, 198 | setlease: None, 199 | show_fdinfo: None, 200 | splice_read: None, 201 | splice_write: None, 202 | unlocked_ioctl: None, 203 | write_iter: None, 204 | }; 205 | } 206 | 207 | pub type ReadFn = Option KernelResult<()>>; 208 | pub type WriteFn = Option KernelResult<()>>; 209 | pub type SeekFn = Option KernelResult>; 210 | 211 | /// `FileOperations` corresponds to the kernel's `struct file_operations`. You 212 | /// implement this trait whenever you'd create a `struct file_operations`. 213 | /// File descriptors may be used from multiple threads (or processes) 214 | /// concurrently, so your type must be `Sync`. 215 | pub trait FileOperations: Sync + Sized { 216 | /// Creates a new instance of this file. Corresponds to the `open` function 217 | /// pointer in `struct file_operations`. 218 | fn open() -> KernelResult; 219 | 220 | /// Reads data from this file to userspace. Corresponds to the `read` 221 | /// function pointer in `struct file_operations`. 222 | const READ: ReadFn = None; 223 | 224 | /// Writes data from userspace o this file. Corresponds to the `write` 225 | /// function pointer in `struct file_operations`. 226 | const WRITE: WriteFn = None; 227 | 228 | /// Changes the position of the file. Corresponds to the `llseek` function 229 | /// pointer in `struct file_operations`. 230 | const SEEK: SeekFn = None; 231 | } 232 | -------------------------------------------------------------------------------- /src/filesystem.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use core::default::Default; 3 | use core::marker; 4 | 5 | use crate::bindings; 6 | use crate::c_types; 7 | use crate::error; 8 | use crate::types::CStr; 9 | 10 | pub struct Registration { 11 | _phantom: marker::PhantomData, 12 | ptr: Box, 13 | } 14 | 15 | // This is safe because Registration doesn't actually expose any methods. 16 | unsafe impl Sync for Registration where T: FileSystem {} 17 | 18 | impl Drop for Registration { 19 | fn drop(&mut self) { 20 | unsafe { bindings::unregister_filesystem(&mut *self.ptr) }; 21 | } 22 | } 23 | 24 | pub trait FileSystem: Sync { 25 | const NAME: CStr<'static>; 26 | const FLAGS: FileSystemFlags; 27 | } 28 | 29 | bitflags::bitflags! { 30 | pub struct FileSystemFlags: c_types::c_int { 31 | const REQUIRES_DEV = bindings::FS_REQUIRES_DEV as c_types::c_int; 32 | const BINARY_MOUNTDATA = bindings::FS_BINARY_MOUNTDATA as c_types::c_int; 33 | const HAS_SUBTYPE = bindings::FS_HAS_SUBTYPE as c_types::c_int; 34 | const USERNS_MOUNT = bindings::FS_USERNS_MOUNT as c_types::c_int; 35 | const RENAME_DOES_D_MOVE = bindings::FS_RENAME_DOES_D_MOVE as c_types::c_int; 36 | } 37 | } 38 | 39 | extern "C" fn fill_super_callback( 40 | _sb: *mut bindings::super_block, 41 | _data: *mut c_types::c_void, 42 | _silent: c_types::c_int, 43 | ) -> c_types::c_int { 44 | // T::fill_super(...) 45 | // This should actually create an object that gets dropped by 46 | // file_system_registration::kill_sb. You can point to it with 47 | // sb->s_fs_info. 48 | unimplemented!(); 49 | } 50 | 51 | extern "C" fn mount_callback( 52 | fs_type: *mut bindings::file_system_type, 53 | flags: c_types::c_int, 54 | _dev_name: *const c_types::c_char, 55 | data: *mut c_types::c_void, 56 | ) -> *mut bindings::dentry { 57 | unsafe { bindings::mount_nodev(fs_type, flags, data, Some(fill_super_callback::)) } 58 | } 59 | 60 | pub fn register() -> error::KernelResult> { 61 | let mut fs_registration = Registration { 62 | ptr: Box::new(bindings::file_system_type { 63 | name: T::NAME.as_ptr() as *const i8, 64 | owner: unsafe { &mut bindings::__this_module }, 65 | fs_flags: T::FLAGS.bits(), 66 | mount: Some(mount_callback::), 67 | kill_sb: Some(bindings::kill_litter_super), 68 | 69 | ..Default::default() 70 | }), 71 | _phantom: marker::PhantomData, 72 | }; 73 | let result = unsafe { bindings::register_filesystem(&mut *fs_registration.ptr) }; 74 | if result != 0 { 75 | return Err(error::Error::from_kernel_errno(result)); 76 | } 77 | 78 | Ok(fs_registration) 79 | } 80 | -------------------------------------------------------------------------------- /src/helpers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | void bug_helper(void) 8 | { 9 | BUG(); 10 | } 11 | 12 | int access_ok_helper(const void __user *addr, unsigned long n) 13 | { 14 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 0, 0) /* v5.0-rc1~46 */ 15 | return access_ok(addr, n); 16 | #else 17 | return access_ok(0, addr, n); 18 | #endif 19 | } 20 | 21 | /* see https://github.com/rust-lang/rust-bindgen/issues/1671 */ 22 | _Static_assert(__builtin_types_compatible_p(size_t, uintptr_t), 23 | "size_t must match uintptr_t, what architecture is this??"); 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![feature(allocator_api, alloc_error_handler)] 3 | 4 | extern crate alloc; 5 | 6 | use core::panic::PanicInfo; 7 | 8 | mod allocator; 9 | pub mod bindings; 10 | pub mod c_types; 11 | pub mod chrdev; 12 | mod error; 13 | pub mod file_operations; 14 | pub mod filesystem; 15 | pub mod printk; 16 | #[cfg(kernel_4_13_0_or_greater)] 17 | pub mod random; 18 | pub mod sysctl; 19 | mod types; 20 | pub mod user_ptr; 21 | 22 | pub use crate::error::{Error, KernelResult}; 23 | pub use crate::types::{CStr, Mode}; 24 | 25 | /// Declares the entrypoint for a kernel module. The first argument should be a type which 26 | /// implements the [`KernelModule`] trait. Also accepts various forms of kernel metadata. 27 | /// 28 | /// Example: 29 | /// ```rust,no_run 30 | /// use linux_kernel_module; 31 | /// struct MyKernelModule; 32 | /// impl linux_kernel_module::KernelModule for MyKernelModule { 33 | /// fn init() -> linux_kernel_module::KernelResult { 34 | /// Ok(MyKernelModule) 35 | /// } 36 | /// } 37 | /// 38 | /// linux_kernel_module::kernel_module!( 39 | /// MyKernelModule, 40 | /// author: b"Fish in a Barrel Contributors", 41 | /// description: b"My very own kernel module!", 42 | /// license: b"GPL" 43 | /// ); 44 | #[macro_export] 45 | macro_rules! kernel_module { 46 | ($module:ty, $($name:ident : $value:expr),*) => { 47 | static mut __MOD: Option<$module> = None; 48 | #[no_mangle] 49 | pub extern "C" fn init_module() -> $crate::c_types::c_int { 50 | match <$module as $crate::KernelModule>::init() { 51 | Ok(m) => { 52 | unsafe { 53 | __MOD = Some(m); 54 | } 55 | return 0; 56 | } 57 | Err(e) => { 58 | return e.to_kernel_errno(); 59 | } 60 | } 61 | } 62 | 63 | #[no_mangle] 64 | pub extern "C" fn cleanup_module() { 65 | unsafe { 66 | // Invokes drop() on __MOD, which should be used for cleanup. 67 | __MOD = None; 68 | } 69 | } 70 | 71 | $( 72 | $crate::kernel_module!(@attribute $name, $value); 73 | )* 74 | }; 75 | 76 | // TODO: The modinfo attributes below depend on the compiler placing 77 | // the variables in order in the .modinfo section, so that you end up 78 | // with b"key=value\0" in order in the section. This is a reasonably 79 | // standard trick in C, but I'm not sure that rustc guarantees it. 80 | // 81 | // Ideally we'd be able to use concat_bytes! + stringify_bytes! + 82 | // some way of turning a string literal (or at least a string 83 | // literal token) into a bytes literal, and get a single static 84 | // [u8; * N] with the whole thing, but those don't really exist yet. 85 | // Most of the alternatives (e.g. .as_bytes() as a const fn) give 86 | // you a pointer, not an array, which isn't right. 87 | 88 | (@attribute author, $value:expr) => { 89 | #[link_section = ".modinfo"] 90 | #[used] 91 | pub static AUTHOR_KEY: [u8; 7] = *b"author="; 92 | #[link_section = ".modinfo"] 93 | #[used] 94 | pub static AUTHOR_VALUE: [u8; $value.len()] = *$value; 95 | #[link_section = ".modinfo"] 96 | #[used] 97 | pub static AUTHOR_NUL: [u8; 1] = *b"\0"; 98 | }; 99 | 100 | (@attribute description, $value:expr) => { 101 | #[link_section = ".modinfo"] 102 | #[used] 103 | pub static DESCRIPTION_KEY: [u8; 12] = *b"description="; 104 | #[link_section = ".modinfo"] 105 | #[used] 106 | pub static DESCRIPTION_VALUE: [u8; $value.len()] = *$value; 107 | #[link_section = ".modinfo"] 108 | #[used] 109 | pub static DESCRIPTION_NUL: [u8; 1] = *b"\0"; 110 | }; 111 | 112 | (@attribute license, $value:expr) => { 113 | #[link_section = ".modinfo"] 114 | #[used] 115 | pub static LICENSE_KEY: [u8; 8] = *b"license="; 116 | #[link_section = ".modinfo"] 117 | #[used] 118 | pub static LICENSE_VALUE: [u8; $value.len()] = *$value; 119 | #[link_section = ".modinfo"] 120 | #[used] 121 | pub static LICENSE_NUL: [u8; 1] = *b"\0"; 122 | }; 123 | } 124 | 125 | /// KernelModule is the top level entrypoint to implementing a kernel module. Your kernel module 126 | /// should implement the `init` method on it, which maps to the `module_init` macro in Linux C API. 127 | /// You can use this method to do whatever setup or registration your module should do. For any 128 | /// teardown or cleanup operations, your type may implement [`Drop`]. 129 | /// 130 | /// [`Drop`]: https://doc.rust-lang.org/stable/core/ops/trait.Drop.html 131 | pub trait KernelModule: Sized + Sync { 132 | fn init() -> KernelResult; 133 | } 134 | 135 | extern "C" { 136 | fn bug_helper() -> !; 137 | } 138 | 139 | #[panic_handler] 140 | fn panic(_info: &PanicInfo) -> ! { 141 | unsafe { 142 | bug_helper(); 143 | } 144 | } 145 | 146 | #[global_allocator] 147 | static ALLOCATOR: allocator::KernelAllocator = allocator::KernelAllocator; 148 | -------------------------------------------------------------------------------- /src/printk.rs: -------------------------------------------------------------------------------- 1 | use core::cmp; 2 | use core::fmt; 3 | 4 | use crate::bindings; 5 | use crate::c_types::c_int; 6 | 7 | #[doc(hidden)] 8 | pub fn printk(s: &[u8]) { 9 | // Don't copy the trailing NUL from `KERN_INFO`. 10 | let mut fmt_str = [0; bindings::KERN_INFO.len() - 1 + b"%.*s\0".len()]; 11 | fmt_str[..bindings::KERN_INFO.len() - 1] 12 | .copy_from_slice(&bindings::KERN_INFO[..bindings::KERN_INFO.len() - 1]); 13 | fmt_str[bindings::KERN_INFO.len() - 1..].copy_from_slice(b"%.*s\0"); 14 | 15 | // TODO: I believe printk never fails 16 | unsafe { bindings::printk(fmt_str.as_ptr() as _, s.len() as c_int, s.as_ptr()) }; 17 | } 18 | 19 | // From kernel/print/printk.c 20 | const LOG_LINE_MAX: usize = 1024 - 32; 21 | 22 | #[doc(hidden)] 23 | pub struct LogLineWriter { 24 | data: [u8; LOG_LINE_MAX], 25 | pos: usize, 26 | } 27 | 28 | #[allow(clippy::new_without_default)] 29 | impl LogLineWriter { 30 | pub fn new() -> LogLineWriter { 31 | LogLineWriter { 32 | data: [0u8; LOG_LINE_MAX], 33 | pos: 0, 34 | } 35 | } 36 | 37 | pub fn as_bytes(&self) -> &[u8] { 38 | &self.data[..self.pos] 39 | } 40 | } 41 | 42 | impl fmt::Write for LogLineWriter { 43 | fn write_str(&mut self, s: &str) -> fmt::Result { 44 | let copy_len = cmp::min(LOG_LINE_MAX - self.pos, s.as_bytes().len()); 45 | self.data[self.pos..self.pos + copy_len].copy_from_slice(&s.as_bytes()[..copy_len]); 46 | self.pos += copy_len; 47 | Ok(()) 48 | } 49 | } 50 | 51 | /// [`println!`] functions the same as it does in `std`, except instead of 52 | /// printing to `stdout`, it writes to the kernel console at the `KERN_INFO` 53 | /// level. 54 | /// 55 | /// [`println!`]: https://doc.rust-lang.org/stable/std/macro.println.html 56 | #[macro_export] 57 | macro_rules! println { 58 | () => ({ 59 | $crate::printk::printk("\n".as_bytes()); 60 | }); 61 | ($fmt:expr) => ({ 62 | $crate::printk::printk(concat!($fmt, "\n").as_bytes()); 63 | }); 64 | ($fmt:expr, $($arg:tt)*) => ({ 65 | use ::core::fmt; 66 | let mut writer = $crate::printk::LogLineWriter::new(); 67 | let _ = fmt::write(&mut writer, format_args!(concat!($fmt, "\n"), $($arg)*)).unwrap(); 68 | $crate::printk::printk(writer.as_bytes()); 69 | }); 70 | } 71 | -------------------------------------------------------------------------------- /src/random.rs: -------------------------------------------------------------------------------- 1 | use core::convert::TryInto; 2 | 3 | use crate::{bindings, c_types, error}; 4 | 5 | /// Fills `dest` with random bytes generated from the kernel's CSPRNG. Ensures 6 | /// that the CSPRNG has been seeded before generating any random bytes, and 7 | /// will block until it's ready. 8 | pub fn getrandom(dest: &mut [u8]) -> error::KernelResult<()> { 9 | let res = unsafe { bindings::wait_for_random_bytes() }; 10 | if res != 0 { 11 | return Err(error::Error::from_kernel_errno(res)); 12 | } 13 | 14 | unsafe { 15 | bindings::get_random_bytes( 16 | dest.as_mut_ptr() as *mut c_types::c_void, 17 | dest.len().try_into()?, 18 | ); 19 | } 20 | Ok(()) 21 | } 22 | 23 | /// Fills `dest` with random bytes generated from the kernel's CSPRNG. If the 24 | /// CSPRNG is not yet seeded, returns an `Err(EAGAIN)` immediately. Only 25 | /// available on 4.19 and later kernels. 26 | #[cfg(kernel_4_19_0_or_greater)] 27 | pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult<()> { 28 | if !unsafe { bindings::rng_is_initialized() } { 29 | return Err(error::Error::EAGAIN); 30 | } 31 | getrandom(dest) 32 | } 33 | 34 | /// Contributes the contents of `data` to the kernel's entropy pool. Does _not_ 35 | /// credit the kernel entropy counter though. 36 | pub fn add_randomness(data: &[u8]) { 37 | unsafe { 38 | bindings::add_device_randomness( 39 | data.as_ptr() as *const c_types::c_void, 40 | data.len().try_into().unwrap(), 41 | ); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/sysctl.rs: -------------------------------------------------------------------------------- 1 | use alloc::boxed::Box; 2 | use alloc::vec; 3 | use core::mem; 4 | use core::ptr; 5 | use core::sync::atomic; 6 | 7 | use crate::bindings; 8 | use crate::c_types; 9 | use crate::error; 10 | use crate::types; 11 | use crate::user_ptr::{UserSlicePtr, UserSlicePtrWriter}; 12 | 13 | pub trait SysctlStorage: Sync { 14 | fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult<()>); 15 | fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult<()>); 16 | } 17 | 18 | fn trim_whitespace(mut data: &[u8]) -> &[u8] { 19 | while !data.is_empty() && (data[0] == b' ' || data[0] == b'\t' || data[0] == b'\n') { 20 | data = &data[1..]; 21 | } 22 | while !data.is_empty() 23 | && (data[data.len() - 1] == b' ' 24 | || data[data.len() - 1] == b'\t' 25 | || data[data.len() - 1] == b'\n') 26 | { 27 | data = &data[..data.len() - 1]; 28 | } 29 | data 30 | } 31 | 32 | impl SysctlStorage for &T 33 | where 34 | T: SysctlStorage, 35 | { 36 | fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult<()>) { 37 | (*self).store_value(data) 38 | } 39 | 40 | fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult<()>) { 41 | (*self).read_value(data) 42 | } 43 | } 44 | 45 | impl SysctlStorage for atomic::AtomicBool { 46 | fn store_value(&self, data: &[u8]) -> (usize, error::KernelResult<()>) { 47 | let result = match trim_whitespace(data) { 48 | b"0" => { 49 | self.store(false, atomic::Ordering::Relaxed); 50 | Ok(()) 51 | } 52 | b"1" => { 53 | self.store(true, atomic::Ordering::Relaxed); 54 | Ok(()) 55 | } 56 | _ => Err(error::Error::EINVAL), 57 | }; 58 | (data.len(), result) 59 | } 60 | 61 | fn read_value(&self, data: &mut UserSlicePtrWriter) -> (usize, error::KernelResult<()>) { 62 | let value = if self.load(atomic::Ordering::Relaxed) { 63 | b"1\n" 64 | } else { 65 | b"0\n" 66 | }; 67 | (value.len(), data.write(value)) 68 | } 69 | } 70 | 71 | pub struct Sysctl { 72 | inner: Box, 73 | // Responsible for keeping the ctl_table alive. 74 | _table: Box<[bindings::ctl_table]>, 75 | header: *mut bindings::ctl_table_header, 76 | } 77 | 78 | // This is safe because the only public method we have is get(), which returns 79 | // &T, and T: Sync. Any new methods must adhere to this requirement. 80 | unsafe impl Sync for Sysctl {} 81 | 82 | unsafe extern "C" fn proc_handler( 83 | ctl: *mut bindings::ctl_table, 84 | write: c_types::c_int, 85 | buffer: *mut c_types::c_void, 86 | len: *mut usize, 87 | ppos: *mut bindings::loff_t, 88 | ) -> c_types::c_int { 89 | // If we're reading from some offset other than the beginning of the file, 90 | // return an empty read to signal EOF. 91 | if *ppos != 0 && write == 0 { 92 | *len = 0; 93 | return 0; 94 | } 95 | 96 | let data = match UserSlicePtr::new(buffer, *len) { 97 | Ok(ptr) => ptr, 98 | Err(e) => return e.to_kernel_errno(), 99 | }; 100 | let storage = &*((*ctl).data as *const T); 101 | let (bytes_processed, result) = if write != 0 { 102 | let data = match data.read_all() { 103 | Ok(r) => r, 104 | Err(e) => return e.to_kernel_errno(), 105 | }; 106 | storage.store_value(&data) 107 | } else { 108 | let mut writer = data.writer(); 109 | storage.read_value(&mut writer) 110 | }; 111 | *len = bytes_processed; 112 | *ppos += *len as bindings::loff_t; 113 | match result { 114 | Ok(()) => 0, 115 | Err(e) => e.to_kernel_errno(), 116 | } 117 | } 118 | 119 | impl Sysctl { 120 | pub fn register( 121 | path: types::CStr<'static>, 122 | name: types::CStr<'static>, 123 | storage: T, 124 | mode: types::Mode, 125 | ) -> error::KernelResult> { 126 | if name.contains('/') { 127 | return Err(error::Error::EINVAL); 128 | } 129 | 130 | let storage = Box::new(storage); 131 | let mut table = vec![ 132 | bindings::ctl_table { 133 | procname: name.as_ptr() as *const i8, 134 | mode: mode.as_int(), 135 | data: &*storage as *const T as *mut c_types::c_void, 136 | proc_handler: Some(proc_handler::), 137 | 138 | maxlen: 0, 139 | child: ptr::null_mut(), 140 | poll: ptr::null_mut(), 141 | extra1: ptr::null_mut(), 142 | extra2: ptr::null_mut(), 143 | }, 144 | unsafe { mem::zeroed() }, 145 | ] 146 | .into_boxed_slice(); 147 | 148 | let result = 149 | unsafe { bindings::register_sysctl(path.as_ptr() as *const i8, table.as_mut_ptr()) }; 150 | if result.is_null() { 151 | return Err(error::Error::ENOMEM); 152 | } 153 | 154 | Ok(Sysctl { 155 | inner: storage, 156 | _table: table, 157 | header: result, 158 | }) 159 | } 160 | 161 | pub fn get(&self) -> &T { 162 | &self.inner 163 | } 164 | } 165 | 166 | impl Drop for Sysctl { 167 | fn drop(&mut self) { 168 | unsafe { 169 | bindings::unregister_sysctl_table(self.header); 170 | } 171 | self.header = ptr::null_mut(); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | use core::ops::Deref; 2 | 3 | use crate::bindings; 4 | 5 | pub struct Mode(bindings::umode_t); 6 | 7 | impl Mode { 8 | pub fn from_int(m: u16) -> Mode { 9 | Mode(m) 10 | } 11 | 12 | pub fn as_int(&self) -> u16 { 13 | self.0 14 | } 15 | } 16 | 17 | /// A string that is guaranteed to have exactly one NUL byte, which is at the 18 | /// end. Used for interoperability with kernel APIs that take C strings. 19 | #[repr(transparent)] 20 | pub struct CStr<'a>(&'a str); 21 | 22 | impl CStr<'_> { 23 | /// Creates a new CStr from a str without performing any additional checks. 24 | /// # Safety 25 | /// 26 | /// `data` _must_ end with a NUL byte, and should only have only a single 27 | /// NUL byte, or the string will be truncated. 28 | pub const unsafe fn new_unchecked(data: &str) -> CStr { 29 | CStr(data) 30 | } 31 | } 32 | 33 | impl Deref for CStr<'_> { 34 | type Target = str; 35 | 36 | fn deref(&self) -> &str { 37 | self.0 38 | } 39 | } 40 | 41 | /// Creates a new `CStr` from a string literal. The string literal should not contain any NUL 42 | /// bytes. Example usage: 43 | /// ``` 44 | /// const MY_CSTR: CStr<'static> = cstr!("My awesome CStr!"); 45 | /// ``` 46 | #[macro_export] 47 | macro_rules! cstr { 48 | ($str:expr) => {{ 49 | let s = concat!($str, "\x00"); 50 | unsafe { $crate::CStr::new_unchecked(s) } 51 | }}; 52 | } 53 | -------------------------------------------------------------------------------- /src/user_ptr.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec; 2 | use alloc::vec::Vec; 3 | use core::u32; 4 | 5 | use crate::bindings; 6 | use crate::c_types; 7 | use crate::error; 8 | 9 | extern "C" { 10 | fn access_ok_helper(addr: *const c_types::c_void, len: c_types::c_ulong) -> c_types::c_int; 11 | } 12 | 13 | /// A reference to an area in userspace memory, which can be either 14 | /// read-only or read-write. 15 | /// 16 | /// All methods on this struct are safe: invalid pointers return 17 | /// `EFAULT`. Concurrent access, _including data races to/from userspace 18 | /// memory_, is permitted, because fundamentally another userspace 19 | /// thread / process could always be modifying memory at the same time 20 | /// (in the same way that userspace Rust's std::io permits data races 21 | /// with the contents of files on disk). In the presence of a race, the 22 | /// exact byte values read/written are unspecified but the operation is 23 | /// well-defined. Kernelspace code should validate its copy of data 24 | /// after completing a read, and not expect that multiple reads of the 25 | /// same address will return the same value. 26 | /// 27 | /// All APIs enforce the invariant that a given byte of memory from userspace 28 | /// may only be read once. By pretenting double-fetches we avoid TOCTOU 29 | /// vulnerabilities. This is accomplished by taking `self` by value to prevent 30 | /// obtaining multiple readers on a given UserSlicePtr, and the readers only 31 | /// permitting forward reads. 32 | /// 33 | /// Constructing a `UserSlicePtr` only checks that the range is in valid 34 | /// userspace memory, and does not depend on the current process (and 35 | /// can safely be constructed inside a kernel thread with no current 36 | /// userspace process). Reads and writes wrap the kernel APIs 37 | /// `copy_from_user` and `copy_to_user`, and check the memory map of the 38 | /// current process. 39 | pub struct UserSlicePtr(*mut c_types::c_void, usize); 40 | 41 | impl UserSlicePtr { 42 | /// Construct a user slice from a raw pointer and a length in bytes. 43 | /// 44 | /// Checks that the provided range is within the legal area for 45 | /// userspace memory, using `access_ok` (e.g., on i386, the range 46 | /// must be within the first 3 gigabytes), but does not check that 47 | /// the actual pages are mapped in the current process with 48 | /// appropriate permissions. Those checks are handled in the read 49 | /// and write methods. 50 | /// 51 | /// This is `unsafe` because if it is called within `set_fs(KERNEL_DS)` context then 52 | /// `access_ok` will not do anything. As a result the only place you can safely use this is 53 | /// with an `__user` pointer that was provided by the kernel. 54 | pub(crate) unsafe fn new( 55 | ptr: *mut c_types::c_void, 56 | length: usize, 57 | ) -> error::KernelResult { 58 | if access_ok_helper(ptr, length as c_types::c_ulong) == 0 { 59 | return Err(error::Error::EFAULT); 60 | } 61 | Ok(UserSlicePtr(ptr, length)) 62 | } 63 | 64 | /// Read the entirety of the user slice and return it in a `Vec`. 65 | /// 66 | /// Returns EFAULT if the address does not currently point to 67 | /// mapped, readable memory. 68 | pub fn read_all(self) -> error::KernelResult> { 69 | self.reader().read_all() 70 | } 71 | 72 | /// Construct a `UserSlicePtrReader` that can incrementally read 73 | /// from the user slice. 74 | pub fn reader(self) -> UserSlicePtrReader { 75 | UserSlicePtrReader(self.0, self.1) 76 | } 77 | 78 | /// Write the provided slice into the user slice. 79 | /// 80 | /// Returns EFAULT if the address does not currently point to 81 | /// mapped, writable memory (in which case some data from before the 82 | /// fault may be written), or `data` is larger than the user slice 83 | /// (in which case no data is written). 84 | pub fn write_all(self, data: &[u8]) -> error::KernelResult<()> { 85 | self.writer().write(data) 86 | } 87 | 88 | /// Construct a `UserSlicePtrWrite` that can incrementally write 89 | /// into the user slice. 90 | pub fn writer(self) -> UserSlicePtrWriter { 91 | UserSlicePtrWriter(self.0, self.1) 92 | } 93 | } 94 | 95 | pub struct UserSlicePtrReader(*mut c_types::c_void, usize); 96 | 97 | impl UserSlicePtrReader { 98 | /// Returns the number of bytes left to be read from this. Note that even 99 | /// reading less than this number of bytes may return an Error(). 100 | pub fn len(&self) -> usize { 101 | self.1 102 | } 103 | 104 | /// Returns `true` if `self.len()` is 0. 105 | pub fn is_empty(&self) -> bool { 106 | self.len() == 0 107 | } 108 | 109 | /// Read all data remaining in the user slice and return it in a `Vec`. 110 | /// 111 | /// Returns EFAULT if the address does not currently point to 112 | /// mapped, readable memory. 113 | pub fn read_all(&mut self) -> error::KernelResult> { 114 | let mut data = vec![0; self.1]; 115 | self.read(&mut data)?; 116 | Ok(data) 117 | } 118 | 119 | pub fn read(&mut self, data: &mut [u8]) -> error::KernelResult<()> { 120 | if data.len() > self.1 || data.len() > u32::MAX as usize { 121 | return Err(error::Error::EFAULT); 122 | } 123 | let res = unsafe { 124 | bindings::_copy_from_user( 125 | data.as_mut_ptr() as *mut c_types::c_void, 126 | self.0, 127 | data.len() as _, 128 | ) 129 | }; 130 | if res != 0 { 131 | return Err(error::Error::EFAULT); 132 | } 133 | // Since this is not a pointer to a valid object in our program, 134 | // we cannot use `add`, which has C-style rules for defined 135 | // behavior. 136 | self.0 = self.0.wrapping_add(data.len()); 137 | self.1 -= data.len(); 138 | Ok(()) 139 | } 140 | } 141 | 142 | pub struct UserSlicePtrWriter(*mut c_types::c_void, usize); 143 | 144 | impl UserSlicePtrWriter { 145 | pub fn len(&self) -> usize { 146 | self.1 147 | } 148 | 149 | pub fn is_empty(&self) -> bool { 150 | self.len() == 0 151 | } 152 | 153 | pub fn write(&mut self, data: &[u8]) -> error::KernelResult<()> { 154 | if data.len() > self.1 || data.len() > u32::MAX as usize { 155 | return Err(error::Error::EFAULT); 156 | } 157 | let res = unsafe { 158 | bindings::_copy_to_user( 159 | self.0, 160 | data.as_ptr() as *const c_types::c_void, 161 | data.len() as _, 162 | ) 163 | }; 164 | if res != 0 { 165 | return Err(error::Error::EFAULT); 166 | } 167 | // Since this is not a pointer to a valid object in our program, 168 | // we cannot use `add`, which has C-style rules for defined 169 | // behavior. 170 | self.0 = self.0.wrapping_add(data.len()); 171 | self.1 -= data.len(); 172 | Ok(()) 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /testlib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kernel-module-testlib" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | tempfile = "3" 9 | libc = "0.2.58" 10 | -------------------------------------------------------------------------------- /testlib/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::fs; 3 | use std::path::PathBuf; 4 | use std::process::Command; 5 | 6 | use tempfile::TempDir; 7 | 8 | struct LoadedModule { 9 | name: String, 10 | } 11 | 12 | impl LoadedModule { 13 | fn load(name: String) -> LoadedModule { 14 | let status = Command::new("sudo") 15 | .arg("insmod") 16 | .arg(&name) 17 | .status() 18 | .unwrap(); 19 | assert!(status.success()); 20 | return LoadedModule { name }; 21 | } 22 | } 23 | 24 | impl Drop for LoadedModule { 25 | fn drop(&mut self) { 26 | let status = Command::new("sudo") 27 | .arg("rmmod") 28 | .arg(&self.name) 29 | .status() 30 | .unwrap(); 31 | assert!(status.success()); 32 | } 33 | } 34 | 35 | pub fn with_kernel_module(f: F) { 36 | let status = Command::new("sudo") 37 | .arg("dmesg") 38 | .arg("-C") 39 | .status() 40 | .unwrap(); 41 | assert!(status.success()); 42 | let _m = LoadedModule::load(env::var("KERNEL_MODULE").unwrap()); 43 | f(); 44 | } 45 | 46 | pub fn assert_dmesg_contains(msgs: &[&[u8]]) { 47 | let output = Command::new("dmesg").output().unwrap(); 48 | assert!(output.status.success()); 49 | let lines = output.stdout.split(|x| *x == b'\n').collect::>(); 50 | let mut lines: &[&[u8]] = &lines; 51 | for msg in msgs { 52 | let pos = lines.iter().position(|l| l.ends_with(msg)); 53 | assert!(pos.is_some()); 54 | lines = &lines[pos.unwrap()..]; 55 | } 56 | } 57 | 58 | pub fn get_device_major_number(name: &str) -> libc::dev_t { 59 | let devices = fs::read_to_string("/proc/devices").unwrap(); 60 | let dev_no_line = devices.lines().find(|l| l.ends_with(name)).unwrap(); 61 | let elements = dev_no_line.rsplitn(2, " ").collect::>(); 62 | assert_eq!(elements.len(), 2); 63 | assert_eq!(elements[0], name); 64 | return elements[1].trim().parse().unwrap(); 65 | } 66 | 67 | pub fn temporary_file_path() -> PathBuf { 68 | let mut p = TempDir::new().unwrap().into_path(); 69 | p.push("device"); 70 | return p; 71 | } 72 | 73 | pub struct UnlinkOnDrop<'a> { 74 | path: &'a PathBuf, 75 | } 76 | 77 | impl Drop for UnlinkOnDrop<'_> { 78 | fn drop(&mut self) { 79 | Command::new("sudo") 80 | .arg("rm") 81 | .arg(self.path.to_str().unwrap()) 82 | .status() 83 | .unwrap(); 84 | } 85 | } 86 | 87 | pub fn mknod(path: &PathBuf, major: libc::dev_t, minor: libc::dev_t) -> UnlinkOnDrop { 88 | Command::new("sudo") 89 | .arg("mknod") 90 | .arg("--mode=a=rw") 91 | .arg(path.to_str().unwrap()) 92 | .arg("c") 93 | .arg(major.to_string()) 94 | .arg(minor.to_string()) 95 | .status() 96 | .unwrap(); 97 | return UnlinkOnDrop { path }; 98 | } 99 | -------------------------------------------------------------------------------- /tests/Kbuild: -------------------------------------------------------------------------------- 1 | obj-m := testmodule.o 2 | testmodule-objs := $(TEST_NAME).rust.o 3 | 4 | CARGO ?= cargo 5 | 6 | export c_flags 7 | 8 | $(src)/target/x86_64-linux-kernel/debug/lib%.a: cargo_will_determine_dependencies 9 | cd $(src)/$(TEST_PATH); CARGO_TARGET_DIR=../target $(CARGO) build -Z build-std=core,alloc --target=x86_64-linux-kernel 10 | cd $(src)/$(TEST_PATH); CARGO_TARGET_DIR=../target $(CARGO) clippy -Z build-std=core,alloc --target=x86_64-linux-kernel -- -Dwarnings 11 | 12 | .PHONY: cargo_will_determine_dependencies 13 | 14 | %.rust.o: target/x86_64-linux-kernel/debug/lib%.a 15 | $(LD) -r -o $@ --whole-archive $< 16 | -------------------------------------------------------------------------------- /tests/Makefile: -------------------------------------------------------------------------------- 1 | export KDIR ?= /lib/modules/$(shell uname -r)/build 2 | 3 | CLANG ?= clang 4 | ifeq ($(origin CC),default) 5 | CC := ${CLANG} 6 | endif 7 | 8 | all: 9 | $(MAKE) -C $(KDIR) M=$(CURDIR) CC=$(CC) CONFIG_CC_IS_CLANG=y 10 | 11 | clean: 12 | $(MAKE) -C $(KDIR) M=$(CURDIR) CC=$(CC) clean 13 | -------------------------------------------------------------------------------- /tests/chrdev-region-allocation/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chrdev-region-allocation-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/chrdev-region-allocation/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | use linux_kernel_module::{self, cstr}; 4 | 5 | struct ChrdevRegionAllocationTestModule { 6 | _chrdev_reg: linux_kernel_module::chrdev::Registration, 7 | } 8 | 9 | impl linux_kernel_module::KernelModule for ChrdevRegionAllocationTestModule { 10 | fn init() -> linux_kernel_module::KernelResult { 11 | let chrdev_reg = 12 | linux_kernel_module::chrdev::builder(cstr!("chrdev-region-allocation-tests"), 0..1)? 13 | .build()?; 14 | 15 | Ok(ChrdevRegionAllocationTestModule { 16 | _chrdev_reg: chrdev_reg, 17 | }) 18 | } 19 | } 20 | 21 | linux_kernel_module::kernel_module!( 22 | ChrdevRegionAllocationTestModule, 23 | author: b"Fish in a Barrel Contributors", 24 | description: b"A module for testing character device region allocation", 25 | license: b"GPL" 26 | ); 27 | -------------------------------------------------------------------------------- /tests/chrdev-region-allocation/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | use kernel_module_testlib::with_kernel_module; 4 | 5 | #[test] 6 | fn test_proc_devices() { 7 | with_kernel_module(|| { 8 | let devices = fs::read_to_string("/proc/devices").unwrap(); 9 | let dev_no_line = devices 10 | .lines() 11 | .find(|l| l.ends_with("chrdev-region-allocation-tests")) 12 | .unwrap(); 13 | let elements = dev_no_line.rsplitn(2, " ").collect::>(); 14 | assert_eq!(elements.len(), 2); 15 | assert_eq!(elements[0], "chrdev-region-allocation-tests"); 16 | assert!(elements[1].trim().parse::().is_ok()); 17 | }); 18 | 19 | let devices = fs::read_to_string("/proc/devices").unwrap(); 20 | assert!(devices 21 | .lines() 22 | .find(|l| l.ends_with("chrdev-region-allocation-tests")) 23 | .is_none()); 24 | } 25 | -------------------------------------------------------------------------------- /tests/chrdev/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chrdev-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | libc = "0.2.58" 20 | -------------------------------------------------------------------------------- /tests/chrdev/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | extern crate alloc; 4 | 5 | use alloc::string::ToString; 6 | use core::sync::atomic::{AtomicUsize, Ordering}; 7 | 8 | use linux_kernel_module::{self, cstr}; 9 | 10 | struct CycleFile; 11 | 12 | impl linux_kernel_module::file_operations::FileOperations for CycleFile { 13 | fn open() -> linux_kernel_module::KernelResult { 14 | Ok(CycleFile) 15 | } 16 | 17 | const READ: linux_kernel_module::file_operations::ReadFn = Some( 18 | |_this: &Self, 19 | _file: &linux_kernel_module::file_operations::File, 20 | buf: &mut linux_kernel_module::user_ptr::UserSlicePtrWriter, 21 | offset: u64| 22 | -> linux_kernel_module::KernelResult<()> { 23 | for c in b"123456789" 24 | .iter() 25 | .cycle() 26 | .skip((offset % 9) as _) 27 | .take(buf.len()) 28 | { 29 | buf.write(&[*c])?; 30 | } 31 | Ok(()) 32 | }, 33 | ); 34 | } 35 | 36 | struct SeekFile; 37 | 38 | impl linux_kernel_module::file_operations::FileOperations for SeekFile { 39 | fn open() -> linux_kernel_module::KernelResult { 40 | Ok(SeekFile) 41 | } 42 | 43 | const SEEK: linux_kernel_module::file_operations::SeekFn = Some( 44 | |_this: &Self, 45 | _file: &linux_kernel_module::file_operations::File, 46 | _offset: linux_kernel_module::file_operations::SeekFrom| 47 | -> linux_kernel_module::KernelResult { Ok(1234) }, 48 | ); 49 | } 50 | 51 | struct WriteFile { 52 | written: AtomicUsize, 53 | } 54 | 55 | impl linux_kernel_module::file_operations::FileOperations for WriteFile { 56 | fn open() -> linux_kernel_module::KernelResult { 57 | Ok(WriteFile { 58 | written: AtomicUsize::new(0), 59 | }) 60 | } 61 | 62 | const READ: linux_kernel_module::file_operations::ReadFn = Some( 63 | |this: &Self, 64 | _file: &linux_kernel_module::file_operations::File, 65 | buf: &mut linux_kernel_module::user_ptr::UserSlicePtrWriter, 66 | _offset: u64| 67 | -> linux_kernel_module::KernelResult<()> { 68 | let val = this.written.load(Ordering::SeqCst).to_string(); 69 | buf.write(val.as_bytes())?; 70 | Ok(()) 71 | }, 72 | ); 73 | 74 | const WRITE: linux_kernel_module::file_operations::WriteFn = Some( 75 | |this: &Self, 76 | buf: &mut linux_kernel_module::user_ptr::UserSlicePtrReader, 77 | _offset: u64| 78 | -> linux_kernel_module::KernelResult<()> { 79 | let data = buf.read_all()?; 80 | this.written.fetch_add(data.len(), Ordering::SeqCst); 81 | Ok(()) 82 | }, 83 | ); 84 | } 85 | 86 | struct ChrdevTestModule { 87 | _chrdev_registration: linux_kernel_module::chrdev::Registration, 88 | } 89 | 90 | impl linux_kernel_module::KernelModule for ChrdevTestModule { 91 | fn init() -> linux_kernel_module::KernelResult { 92 | let chrdev_registration = 93 | linux_kernel_module::chrdev::builder(cstr!("chrdev-tests"), 0..3)? 94 | .register_device::() 95 | .register_device::() 96 | .register_device::() 97 | .build()?; 98 | Ok(ChrdevTestModule { 99 | _chrdev_registration: chrdev_registration, 100 | }) 101 | } 102 | } 103 | 104 | linux_kernel_module::kernel_module!( 105 | ChrdevTestModule, 106 | author: b"Fish in a Barrel Contributors", 107 | description: b"A module for testing character devices", 108 | license: b"GPL" 109 | ); 110 | -------------------------------------------------------------------------------- /tests/chrdev/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::io::{Read, Seek, SeekFrom, Write}; 3 | use std::os::unix::prelude::FileExt; 4 | 5 | use kernel_module_testlib::*; 6 | 7 | const DEVICE_NAME: &'static str = "chrdev-tests"; 8 | const READ_FILE_MINOR: libc::dev_t = 0; 9 | const SEEK_FILE_MINOR: libc::dev_t = 1; 10 | const WRITE_FILE_MINOR: libc::dev_t = 2; 11 | 12 | #[test] 13 | fn test_mknod() { 14 | with_kernel_module(|| { 15 | let device_number = get_device_major_number(DEVICE_NAME); 16 | mknod(&temporary_file_path(), device_number, READ_FILE_MINOR); 17 | }); 18 | } 19 | 20 | #[test] 21 | fn test_read() { 22 | with_kernel_module(|| { 23 | let device_number = get_device_major_number(DEVICE_NAME); 24 | let p = temporary_file_path(); 25 | let _u = mknod(&p, device_number, READ_FILE_MINOR); 26 | 27 | let mut f = fs::File::open(&p).unwrap(); 28 | let mut data = [0; 12]; 29 | f.read_exact(&mut data).unwrap(); 30 | assert_eq!(&data, b"123456789123") 31 | }); 32 | } 33 | 34 | #[test] 35 | fn test_read_offset() { 36 | with_kernel_module(|| { 37 | let device_number = get_device_major_number(DEVICE_NAME); 38 | let p = temporary_file_path(); 39 | let _u = mknod(&p, device_number, READ_FILE_MINOR); 40 | 41 | let mut f = fs::File::open(&p).unwrap(); 42 | let mut data = [0; 5]; 43 | f.read_exact(&mut data).unwrap(); 44 | assert_eq!(&data, b"12345"); 45 | f.read_exact(&mut data).unwrap(); 46 | assert_eq!(&data, b"67891"); 47 | }); 48 | } 49 | 50 | #[test] 51 | fn test_read_at() { 52 | with_kernel_module(|| { 53 | let device_number = get_device_major_number(DEVICE_NAME); 54 | let p = temporary_file_path(); 55 | let _u = mknod(&p, device_number, READ_FILE_MINOR); 56 | 57 | let f = fs::File::open(&p).unwrap(); 58 | let mut data = [0; 5]; 59 | f.read_exact_at(&mut data, 7).unwrap(); 60 | assert_eq!(&data, b"89123"); 61 | }); 62 | } 63 | 64 | #[test] 65 | fn test_read_unimplemented() { 66 | with_kernel_module(|| { 67 | let device_number = get_device_major_number(DEVICE_NAME); 68 | let p = temporary_file_path(); 69 | let _u = mknod(&p, device_number, SEEK_FILE_MINOR); 70 | 71 | let mut f = fs::File::open(&p).unwrap(); 72 | let mut data = [0; 12]; 73 | assert_eq!( 74 | f.read_exact(&mut data).unwrap_err().raw_os_error().unwrap(), 75 | libc::EINVAL 76 | ); 77 | }) 78 | } 79 | 80 | #[test] 81 | fn test_lseek_unimplemented() { 82 | with_kernel_module(|| { 83 | let device_number = get_device_major_number(DEVICE_NAME); 84 | let p = temporary_file_path(); 85 | let _u = mknod(&p, device_number, READ_FILE_MINOR); 86 | 87 | let mut f = fs::File::open(&p).unwrap(); 88 | assert_eq!( 89 | f.seek(SeekFrom::Start(12)) 90 | .unwrap_err() 91 | .raw_os_error() 92 | .unwrap(), 93 | libc::ESPIPE 94 | ); 95 | assert_eq!( 96 | f.seek(SeekFrom::End(-12)) 97 | .unwrap_err() 98 | .raw_os_error() 99 | .unwrap(), 100 | libc::ESPIPE 101 | ); 102 | assert_eq!( 103 | f.seek(SeekFrom::Current(12)) 104 | .unwrap_err() 105 | .raw_os_error() 106 | .unwrap(), 107 | libc::ESPIPE 108 | ); 109 | }); 110 | } 111 | 112 | #[test] 113 | fn test_lseek() { 114 | with_kernel_module(|| { 115 | let device_number = get_device_major_number(DEVICE_NAME); 116 | let p = temporary_file_path(); 117 | let _u = mknod(&p, device_number, SEEK_FILE_MINOR); 118 | 119 | let mut f = fs::File::open(&p).unwrap(); 120 | assert_eq!(f.seek(SeekFrom::Start(12)).unwrap(), 1234); 121 | assert_eq!(f.seek(SeekFrom::End(-12)).unwrap(), 1234); 122 | assert_eq!(f.seek(SeekFrom::Current(12)).unwrap(), 1234); 123 | 124 | assert_eq!( 125 | f.seek(SeekFrom::Start(u64::max_value())) 126 | .unwrap_err() 127 | .raw_os_error() 128 | .unwrap(), 129 | libc::EINVAL 130 | ); 131 | }); 132 | } 133 | 134 | #[test] 135 | fn test_write_unimplemented() { 136 | with_kernel_module(|| { 137 | let device_number = get_device_major_number(DEVICE_NAME); 138 | let p = temporary_file_path(); 139 | let _u = mknod(&p, device_number, READ_FILE_MINOR); 140 | 141 | let mut f = fs::OpenOptions::new().write(true).open(&p).unwrap(); 142 | assert_eq!( 143 | f.write(&[1, 2, 3]).unwrap_err().raw_os_error().unwrap(), 144 | libc::EINVAL 145 | ); 146 | }) 147 | } 148 | 149 | #[test] 150 | fn test_write() { 151 | with_kernel_module(|| { 152 | let device_number = get_device_major_number(DEVICE_NAME); 153 | let p = temporary_file_path(); 154 | let _u = mknod(&p, device_number, WRITE_FILE_MINOR); 155 | 156 | let mut f = fs::OpenOptions::new() 157 | .read(true) 158 | .write(true) 159 | .open(&p) 160 | .unwrap(); 161 | assert_eq!(f.write(&[1, 2, 3]).unwrap(), 3); 162 | 163 | let mut buf = [0; 1]; 164 | f.read_exact(&mut buf).unwrap(); 165 | assert_eq!(&buf, b"3"); 166 | 167 | assert_eq!(f.write(&[1, 2, 3, 4, 5]).unwrap(), 5); 168 | 169 | let mut buf = [0; 1]; 170 | f.read_exact(&mut buf).unwrap(); 171 | assert_eq!(&buf, b"8"); 172 | }) 173 | } 174 | -------------------------------------------------------------------------------- /tests/filesystem/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "filesystem-tests" 3 | version = "0.1.0" 4 | authors = ["Luis Gerhorst ", "Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/filesystem/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | extern crate alloc; 4 | 5 | use linux_kernel_module::filesystem::{self, FileSystem, FileSystemFlags}; 6 | use linux_kernel_module::{self, cstr, CStr}; 7 | 8 | struct TestFSModule { 9 | _fs_registration: filesystem::Registration, 10 | } 11 | 12 | struct TestFS {} 13 | 14 | impl FileSystem for TestFS { 15 | const NAME: CStr<'static> = cstr!("testfs"); 16 | const FLAGS: FileSystemFlags = FileSystemFlags::empty(); 17 | } 18 | 19 | impl linux_kernel_module::KernelModule for TestFSModule { 20 | fn init() -> linux_kernel_module::KernelResult { 21 | let fs_registration = filesystem::register::()?; 22 | Ok(TestFSModule { 23 | _fs_registration: fs_registration, 24 | }) 25 | } 26 | } 27 | 28 | linux_kernel_module::kernel_module!( 29 | TestFSModule, 30 | author: b"Fish in a Barrel Contributors", 31 | description: b"A module for testing filesystem::register", 32 | license: b"GPL" 33 | ); 34 | -------------------------------------------------------------------------------- /tests/filesystem/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | use kernel_module_testlib::with_kernel_module; 4 | 5 | #[test] 6 | fn test_proc_filesystems() { 7 | let filesystems = fs::read_to_string("/proc/filesystems").unwrap(); 8 | assert!(!filesystems.contains("testfs")); 9 | 10 | with_kernel_module(|| { 11 | let filesystems = fs::read_to_string("/proc/filesystems").unwrap(); 12 | assert!(filesystems.contains("testfs")); 13 | }); 14 | 15 | let filesystems = fs::read_to_string("/proc/filesystems").unwrap(); 16 | assert!(!filesystems.contains("testfs")); 17 | } 18 | -------------------------------------------------------------------------------- /tests/modinfo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "modinfo-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/modinfo/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | struct ModinfoTestModule; 4 | 5 | impl linux_kernel_module::KernelModule for ModinfoTestModule { 6 | fn init() -> linux_kernel_module::KernelResult { 7 | Ok(ModinfoTestModule) 8 | } 9 | } 10 | 11 | linux_kernel_module::kernel_module!( 12 | ModinfoTestModule, 13 | author: b"Fish in a Barrel Contributors", 14 | description: b"Empty module for testing modinfo", 15 | license: b"GPL" 16 | ); 17 | -------------------------------------------------------------------------------- /tests/modinfo/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::fs; 3 | use std::path::Path; 4 | use std::process::Command; 5 | 6 | use kernel_module_testlib::with_kernel_module; 7 | 8 | #[test] 9 | fn test_modinfo() { 10 | let module = env::var("KERNEL_MODULE").unwrap(); 11 | 12 | for (key, value) in &[ 13 | ("author", "Fish in a Barrel Contributors"), 14 | ("description", "Empty module for testing modinfo"), 15 | ("license", "GPL"), 16 | ] { 17 | let modinfo = Command::new("modinfo") 18 | .arg("-F") 19 | .arg(key) 20 | .arg(&module) 21 | .output() 22 | .unwrap(); 23 | assert!(modinfo.status.success()); 24 | assert_eq!(&std::str::from_utf8(&modinfo.stdout).unwrap().trim(), value); 25 | } 26 | } 27 | 28 | #[test] 29 | fn test_no_proprietary_taint() { 30 | let module = env::var("KERNEL_MODULE").unwrap(); 31 | let module_name = Path::new(&module).file_stem().unwrap(); 32 | let sysfs_path = Path::new("/sys/module").join(module_name).join("taint"); 33 | 34 | with_kernel_module(|| { 35 | let taints = fs::read_to_string(&sysfs_path).unwrap(); 36 | assert!(!taints.contains("P")); 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /tests/printk/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "printk-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/printk/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![allow(clippy::print_literal)] 3 | 4 | use linux_kernel_module::{self, println}; 5 | 6 | struct PrintkTestModule; 7 | 8 | impl linux_kernel_module::KernelModule for PrintkTestModule { 9 | fn init() -> linux_kernel_module::KernelResult { 10 | println!("Single element printk"); 11 | println!(); 12 | println!("printk with {} parameters{}", 2, "!"); 13 | 14 | Ok(PrintkTestModule) 15 | } 16 | } 17 | 18 | linux_kernel_module::kernel_module!( 19 | PrintkTestModule, 20 | author: b"Fish in a Barrel Contributors", 21 | description: b"A module for testing println!()", 22 | license: b"GPL" 23 | ); 24 | -------------------------------------------------------------------------------- /tests/printk/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use kernel_module_testlib::{assert_dmesg_contains, with_kernel_module}; 2 | 3 | #[test] 4 | fn test_printk() { 5 | with_kernel_module(|| { 6 | assert_dmesg_contains(&[b"Single element printk", b"", b"printk with 2 parameters!"]); 7 | }); 8 | } 9 | -------------------------------------------------------------------------------- /tests/random/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "random-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/random/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | extern crate alloc; 4 | 5 | use linux_kernel_module::sysctl::{Sysctl, SysctlStorage}; 6 | use linux_kernel_module::{self, cstr, random, Mode}; 7 | 8 | struct EntropySource; 9 | 10 | impl SysctlStorage for EntropySource { 11 | fn store_value(&self, data: &[u8]) -> (usize, linux_kernel_module::KernelResult<()>) { 12 | random::add_randomness(data); 13 | (data.len(), Ok(())) 14 | } 15 | 16 | fn read_value( 17 | &self, 18 | data: &mut linux_kernel_module::user_ptr::UserSlicePtrWriter, 19 | ) -> (usize, linux_kernel_module::KernelResult<()>) { 20 | let mut storage = alloc::vec![0; data.len()]; 21 | if let Err(e) = random::getrandom(&mut storage) { 22 | return (0, Err(e)); 23 | } 24 | (storage.len(), data.write(&storage)) 25 | } 26 | } 27 | 28 | struct RandomTestModule { 29 | _sysctl_entropy: Sysctl, 30 | } 31 | 32 | impl linux_kernel_module::KernelModule for RandomTestModule { 33 | fn init() -> linux_kernel_module::KernelResult { 34 | Ok(RandomTestModule { 35 | _sysctl_entropy: Sysctl::register( 36 | cstr!("rust/random-tests"), 37 | cstr!("entropy"), 38 | EntropySource, 39 | Mode::from_int(0o666), 40 | )?, 41 | }) 42 | } 43 | } 44 | 45 | linux_kernel_module::kernel_module!( 46 | RandomTestModule, 47 | author: b"Fish in a Barrel Contributors", 48 | description: b"A module for testing the CSPRNG", 49 | license: b"GPL" 50 | ); 51 | -------------------------------------------------------------------------------- /tests/random/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashSet; 2 | use std::fs; 3 | use std::io::Read; 4 | 5 | use kernel_module_testlib::with_kernel_module; 6 | 7 | #[test] 8 | fn test_random_entropy_read() { 9 | with_kernel_module(|| { 10 | let mut keys = HashSet::new(); 11 | for _ in 0..1024 { 12 | let mut key = [0; 16]; 13 | let mut f = fs::File::open("/proc/sys/rust/random-tests/entropy").unwrap(); 14 | f.read_exact(&mut key).unwrap(); 15 | keys.insert(key); 16 | } 17 | assert_eq!(keys.len(), 1024); 18 | }); 19 | } 20 | 21 | #[test] 22 | fn test_random_entropy_write() { 23 | with_kernel_module(|| { 24 | fs::write("/proc/sys/rust/random-tests/entropy", b"1234567890").unwrap(); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /tests/run_tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import subprocess 5 | import sys 6 | 7 | 8 | BASE_DIR = os.path.realpath(os.path.dirname(__file__)) 9 | 10 | 11 | def run(*args, **kwargs): 12 | cwd = kwargs.pop("cwd", None) 13 | environ = kwargs.pop("environ", os.environ) 14 | assert not kwargs 15 | 16 | print("+ [running] {}".format(list(args))) 17 | subprocess.check_call(list(args), cwd=cwd, env=environ) 18 | 19 | 20 | def main(argv): 21 | for path in argv[1:] or os.listdir(BASE_DIR): 22 | if ( 23 | not os.path.isdir(os.path.join(BASE_DIR, path)) or 24 | not os.path.exists(os.path.join(BASE_DIR, path, "tests")) 25 | ): 26 | continue 27 | 28 | print("+ [{}]".format(path)) 29 | 30 | run( 31 | "make", "-C", BASE_DIR, 32 | "TEST_NAME={}_tests".format(path.replace("-", "_")), 33 | "TEST_PATH={}".format(path), 34 | "RUSTFLAGS=-Dwarnings", 35 | ) 36 | # TODO: qemu 37 | run( 38 | "cargo", "test", "--no-default-features", "--", "--test-threads=1", 39 | cwd=os.path.join(BASE_DIR, path), 40 | environ=dict( 41 | os.environ, 42 | KERNEL_MODULE=os.path.join(BASE_DIR, "testmodule.ko"), 43 | RUSTFLAGS="-Dwarnings", 44 | CARGO_TARGET_DIR=os.path.relpath( 45 | os.path.join(BASE_DIR, "target-test"), 46 | os.path.join(BASE_DIR, path) 47 | ), 48 | ) 49 | ) 50 | 51 | 52 | if __name__ == "__main__": 53 | main(sys.argv) 54 | -------------------------------------------------------------------------------- /tests/sysctl-get/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sysctl-get-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/sysctl-get/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | use core::sync::atomic::{AtomicBool, Ordering}; 4 | 5 | use linux_kernel_module::{self, cstr, println}; 6 | 7 | use linux_kernel_module::sysctl::Sysctl; 8 | use linux_kernel_module::Mode; 9 | 10 | static A_VAL: AtomicBool = AtomicBool::new(false); 11 | 12 | struct SysctlGetTestModule { 13 | sysctl_a: Sysctl<&'static AtomicBool>, 14 | } 15 | 16 | impl linux_kernel_module::KernelModule for SysctlGetTestModule { 17 | fn init() -> linux_kernel_module::KernelResult { 18 | Ok(SysctlGetTestModule { 19 | sysctl_a: Sysctl::register( 20 | cstr!("rust/sysctl-get-tests"), 21 | cstr!("a"), 22 | &A_VAL, 23 | Mode::from_int(0o666), 24 | )?, 25 | }) 26 | } 27 | } 28 | 29 | impl Drop for SysctlGetTestModule { 30 | fn drop(&mut self) { 31 | println!("A_VAL: {:?}", A_VAL.load(Ordering::Relaxed)); 32 | println!( 33 | "SYSCTL_A: {:?}", 34 | self.sysctl_a.get().load(Ordering::Relaxed) 35 | ); 36 | } 37 | } 38 | 39 | linux_kernel_module::kernel_module!( 40 | SysctlGetTestModule, 41 | author: b"Fish in a Barrel Contributors", 42 | description: b"A module for testing sysctls", 43 | license: b"GPL" 44 | ); 45 | -------------------------------------------------------------------------------- /tests/sysctl-get/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | use kernel_module_testlib::{assert_dmesg_contains, with_kernel_module}; 4 | 5 | #[test] 6 | fn test_get() { 7 | with_kernel_module(|| { 8 | fs::write("/proc/sys/rust/sysctl-get-tests/a", "1").unwrap(); 9 | }); 10 | assert_dmesg_contains(&[b"A_VAL: true", b"SYSCTL_A: true"]); 11 | } 12 | -------------------------------------------------------------------------------- /tests/sysctl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sysctl-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/sysctl/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | use core::sync::atomic::AtomicBool; 4 | 5 | use linux_kernel_module::{self, cstr}; 6 | 7 | use linux_kernel_module::sysctl::Sysctl; 8 | use linux_kernel_module::Mode; 9 | 10 | struct SysctlTestModule { 11 | _sysctl_a: Sysctl, 12 | _sysctl_b: Sysctl, 13 | } 14 | 15 | impl linux_kernel_module::KernelModule for SysctlTestModule { 16 | fn init() -> linux_kernel_module::KernelResult { 17 | Ok(SysctlTestModule { 18 | _sysctl_a: Sysctl::register( 19 | cstr!("rust/sysctl-tests"), 20 | cstr!("a"), 21 | AtomicBool::new(false), 22 | Mode::from_int(0o666), 23 | )?, 24 | _sysctl_b: Sysctl::register( 25 | cstr!("rust/sysctl-tests"), 26 | cstr!("b"), 27 | AtomicBool::new(false), 28 | Mode::from_int(0o666), 29 | )?, 30 | }) 31 | } 32 | } 33 | 34 | linux_kernel_module::kernel_module!( 35 | SysctlTestModule, 36 | author: b"Fish in a Barrel Contributors", 37 | description: b"A module for testing sysctls", 38 | license: b"GPL" 39 | ); 40 | -------------------------------------------------------------------------------- /tests/sysctl/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::path::Path; 3 | 4 | use kernel_module_testlib::with_kernel_module; 5 | 6 | #[test] 7 | fn test_read_bool_default() { 8 | with_kernel_module(|| { 9 | assert_eq!( 10 | fs::read_to_string("/proc/sys/rust/sysctl-tests/a").unwrap(), 11 | "0\n" 12 | ); 13 | }); 14 | } 15 | 16 | #[test] 17 | fn test_write_bool() { 18 | with_kernel_module(|| { 19 | fs::write("/proc/sys/rust/sysctl-tests/a", "1").unwrap(); 20 | assert_eq!( 21 | fs::read_to_string("/proc/sys/rust/sysctl-tests/a").unwrap(), 22 | "1\n" 23 | ); 24 | }); 25 | } 26 | 27 | #[test] 28 | fn test_write_bool_whitespace() { 29 | with_kernel_module(|| { 30 | fs::write("/proc/sys/rust/sysctl-tests/a", " 1\t").unwrap(); 31 | assert_eq!( 32 | fs::read_to_string("/proc/sys/rust/sysctl-tests/a").unwrap(), 33 | "1\n" 34 | ); 35 | }); 36 | } 37 | 38 | #[test] 39 | fn test_file_doesnt_exit_after_module_unloaded() { 40 | with_kernel_module(|| { 41 | assert!(Path::new("/proc/sys/rust/sysctl-tests/a").exists()); 42 | }); 43 | assert!(!Path::new("/proc/sys/rust/sysctl-tests/a").exists()); 44 | } 45 | -------------------------------------------------------------------------------- /tests/utils/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "utils-tests" 3 | version = "0.1.0" 4 | authors = ["Alex Gaynor ", "Geoffrey Thomas "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["staticlib"] 9 | test = false 10 | 11 | [features] 12 | default = ["linux-kernel-module"] 13 | 14 | [dependencies] 15 | linux-kernel-module = { path = "../..", optional = true } 16 | 17 | [dev-dependencies] 18 | kernel-module-testlib = { path = "../../testlib" } 19 | -------------------------------------------------------------------------------- /tests/utils/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | struct UtilsTestModule; 4 | 5 | #[allow(dead_code)] 6 | const TEST_CSTR: linux_kernel_module::CStr<'static> = linux_kernel_module::cstr!("abc"); 7 | 8 | impl linux_kernel_module::KernelModule for UtilsTestModule { 9 | fn init() -> linux_kernel_module::KernelResult { 10 | Ok(UtilsTestModule) 11 | } 12 | } 13 | 14 | linux_kernel_module::kernel_module!( 15 | UtilsTestModule, 16 | author: b"Fish in a Barrel Contributors", 17 | description: b"A module for testing various utilities", 18 | license: b"GPL" 19 | ); 20 | -------------------------------------------------------------------------------- /tests/utils/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use kernel_module_testlib::with_kernel_module; 2 | 3 | #[test] 4 | fn test_module_loads() { 5 | with_kernel_module(|| {}); 6 | } 7 | --------------------------------------------------------------------------------