├── .gitignore ├── COPYING ├── Makefile.am ├── README.md ├── autogen.sh ├── configure.ac ├── devices.c ├── fstab.c ├── io.c ├── log.c ├── mount.c ├── nfs.c ├── nfs4.h ├── tiny_initramfs.c ├── tiny_initramfs.h └── util.c /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | initrd.img 3 | initramfs/ 4 | tiny_initramfs 5 | Makefile 6 | Makefile.in 7 | configure 8 | *~ 9 | .deps/ 10 | aclocal.m4 11 | autom4te.cache/ 12 | compile 13 | config.h 14 | config.h.in 15 | config.log 16 | config.status 17 | depcomp 18 | install-sh 19 | missing 20 | stamp-h1 21 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | AM_CPPFLAGS = -Wall -Wextra 2 | 3 | pkglibexec_PROGRAMS = tiny_initramfs 4 | 5 | tiny_initramfs_SOURCES = tiny_initramfs.c io.c fstab.c mount.c log.c devices.c util.c 6 | if ENABLE_NFS4 7 | tiny_initramfs_SOURCES += nfs.c 8 | endif 9 | tiny_initramfs_CFLAGS = -fno-inline-small-functions -fno-caller-saves 10 | tiny_initramfs_LDFLAGS = -static 11 | 12 | EXTRA_DIST = README.md tiny_initramfs.h nfs4.h 13 | 14 | if HAVE_VARIANT 15 | install-exec-hook: 16 | cd $(DESTDIR)$(pkglibexecdir) && \ 17 | mv -f tiny_initramfs init-@VARIANT@ 18 | else 19 | install-exec-hook: 20 | cd $(DESTDIR)$(pkglibexecdir) && \ 21 | mv -f tiny_initramfs init 22 | endif 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | tiny-initramfs - A minimalistic initramfs implementation 2 | ======================================================== 3 | 4 | This is a very minimalistic [initramfs](https://en.wikipedia.org/wiki/Initramfs) 5 | implementation for booting Linux systems. It has nearly no features, 6 | but is very small and very fast. It is written purely in C, but uses 7 | only parts of the standard library. 8 | 9 | There are three primary use cases: 10 | 11 | * It is designed for systems where an initramfs is typically not 12 | necessary (block device drivers + root file system compiled into the 13 | kernel, no separate /usr file system), but where an initramfs is 14 | required for microcode upgrades. Instead of having to use a full 15 | initramfs, which is larger (more time spent in the boot loader 16 | loading it) and slower (because it does more), `tiny-initramfs` will 17 | add next to no overhead. 18 | * In cases where `UUID`-based boot is wanted not a full initramfs. 19 | * In systems with a split `/usr` file system, it is necessary to mount 20 | that in the initramfs already, else subtle problems may occur. If 21 | `/usr` resides on a simple block device already known to the kernel 22 | (without user space helpers such as udev), `tiny-initramfs` provides 23 | a mechanism with very little overhead to mount it before the system 24 | is started. 25 | 26 | Features 27 | -------- 28 | 29 | * Simplicity: the implementation is really simple and very linear. 30 | It's most likely easier to understand than other initramfs 31 | implementations. The entire program is less about 2500 LoC, and that 32 | includes the License headers in the files. 33 | * Size: the implementation is really small (see below). 34 | * Speed: there is no noticeable performance penalty, because very 35 | little is done before execution is handed over to the operating 36 | system proper. 37 | * Supports kernel-named devices, for example `root=/dev/sda1`. 38 | * Supports `root=0xMAJMIN`. 39 | * Supports `root=UUID=...` for ext2, ext3, ext4, xfs and btrfs. 40 | * Supports parsing `/etc/fstab` to determine if a separate `/usr` 41 | partition exists and mounting that - as long as the entry there 42 | follows the same rule as the `root=` parameter (kernel device name, 43 | or `UUID=` entry for a select number of filesystems). 44 | * Supports the `root=`, `rootflags=`, `rootfstype=`, `rootdelay=`, 45 | `rootwait`, `ro`, `rw` and `init=` parameters. 46 | * Default timeout of 180 seconds to wait for the root device to appear 47 | (starts after the `rootdelay=` delay is over), after which a kernel 48 | panic is caused; if `rootwait` is specified it will wait 49 | indefinitely. (Recompilation is necessary for a larger timeout.) 50 | * Supports mounting NFSv4 file systems with `sec=sys` that do **not** 51 | use the idampper, i.e. use raw UIDs/GIDs. For the `/usr` file system 52 | the standard `/etc/fstab` entries are interpreted, for the root file 53 | system one should use `root=/dev/nfs` and the `nfsroot=` parameter 54 | (as documented in the kernel documentation). The network 55 | configuration needs to be specified via the `ip=` kernel command 56 | line parameter. 57 | * Very trivial module loading support (**no** automatic dependency 58 | resolution). 59 | 60 | When compiled on an x86_64 system with the default `-Og` compiler flags, 61 | statically linked against dietlibc 0.33~cvs20120325-6, the binary 62 | stripped and the resulting initramfs (without any modules added) 63 | compressed with `gzip -9`, the images produced are between 9 kiB and 64 | 14 kiB, depending on the feature set selected. 65 | 66 | Using musl instead of dietlibc adds between 1.8 and 2.4 kiB to the 67 | resulting `initrd.img` size (depending on the feature set). 68 | 69 | Using glibc instead of dietlibc adds around 310 kiB to the resulting 70 | initrd image and is not recommended (although it will work). 71 | 72 | Adding modules to the initramfs will increase the size, and many block 73 | device and file system drivers are 100s of kiB in size. On the other 74 | hand, the kernel would be larger if they were compiled in, so the 75 | actual amount of space lost due to using modules is quite a bit 76 | smaller. 77 | 78 | Requirements 79 | ------------ 80 | 81 | * The kernel should have the necessary block device and file system 82 | drivers built-in that are required to access the root and `/usr` 83 | file systems. **Warning:** this is not true for most default kernels 84 | of mainstream distributions, as they require a full initramfs to 85 | load the modules required to mount the root file system. 86 | * If the necessary drivers are not built into the kernel, there is 87 | limited support for loading modules from within the initramfs, see 88 | below for details. 89 | * The kernel must have `CONFIG_DEVTMPFS` built-in, because this 90 | implementation assumes the kernel will just create the devices by 91 | itself. (This is true for most distribution kernels.) 92 | * NFSv4 requires at least kernel 3.5 on both server and client (in 93 | order for raw UIDs/GIDs to work) and requires built-in kernel 94 | support for network autoconfiguration (`CONFIG_IP_PNP` and for DHCP 95 | support also `CONFIG_IP_PNP_DHCP`) as well as built-in kernel 96 | support for NFSv4 (`CONFIG_NFS_FS` as well as `CONFIG_NFS_V4`). 97 | 98 | When not to use 99 | --------------- 100 | 101 | * `tiny-initramfs` does not support `PARTUUID=` for mounting the root 102 | or `/usr` file systems. It also doesn't support symlinks created by 103 | udev (such as `/dev/disk/by-label/...`). Only the kernel names 104 | themselves, such as `/dev/sda1`, as well as `UUID=` and hexadecimal 105 | device numbers (`0xMAJMIN`, e.g. `0x801`) are supported. 106 | * NFSv2/NFSv3 are currently not supported. 107 | * When booting from USB storage you should always use `UUID=`, because 108 | device names are not necessarily stable. 109 | * `/usr` on a FUSE file system, as they require user space helpers 110 | running to be able to mount. Generally speaking, any file system 111 | that can't be mounted with just a trivial `mount` syscall, but 112 | requires a userspace helper, will not work. 113 | * Any complex storage setup, such as LVM, encryption, iSCSI, etc. 114 | Basically, only things that the kernel provides devices for out of 115 | the box (potentially with additional kernel parameters) is 116 | supported. 117 | 118 | If your setup falls into one of these cases, please use a full 119 | initramfs instead of `tiny-initramfs`. It is not meant to replace 120 | those, but provide a light-weight solution in cases where the 121 | complexities of a full initramfs are unnecessary. 122 | 123 | Caveats 124 | ------- 125 | 126 | * Since the initramfs is supposed to be small, `fsck` will not be 127 | executed by `tiny-initramfs`. For the `/` file system this is 128 | perfectly fine, as most distributions support checking the root file 129 | system at boot outside of the initramfs. But this doesn't work for 130 | `/usr`, because e.g. `e2fsck` will not check a mounted file system 131 | other than the root file system; and e.g. systemd passes `-M` to 132 | `fsck` by default for non-root file systems, so mounted file systems 133 | are excluded anyway. It shouldn't be too difficult to special-case 134 | `/usr` here as well, but that work needs to be done if a file system 135 | check at boot is to be performed for `/usr` with `tiny-initramfs`. 136 | (Note that `e2fsck` plus the required libraries are about 2.5 MiB in 137 | size, so having `fsck` present in the initramfs image is not in the 138 | scope of `tiny-initramfs`, because it would remove all the 139 | advantages.) 140 | * You need to make sure that a split-`/usr` file system is remounted 141 | read-write if the `ro` option is passed on the kernel command line 142 | (because `tiny-initramfs` will also mount `/usr` read-only then); 143 | otherwise `/usr` will remain read-only after boot. If you use 144 | systemd as your init system, or e.g. the newest Debian initscripts 145 | (`2.88dsf-59.3` or higher) in conjunction with sysvinit, this should 146 | work. `tiny-initramfs` itself doesn't care about which init system 147 | is used, but the init system must be able to cope with the state 148 | that `tiny-initramfs` leaves the `/usr` file system in. This may 149 | require changes to some scripts. 150 | * If `/usr` is a bind mount in `/etc/fstab`, this will currently fail, 151 | even though it should be supportable. (It's on the TODO list, as 152 | long as that doesn't require yet another file system.) 153 | * Overlay-type file systems for `/usr` are untested, but they should 154 | work if they are compiled into the kernel. What is *not* supported 155 | are overlay-type file systems for `/` and/or if something has to be 156 | done prior to mounting these file systems (such as creating a 157 | directory, or mounting an additional tmpfs or similar). 158 | * Booting from kernel-assembled RAID arrays (via `md=...`) should 159 | work, but is untested. Don't combine this with `UUID=`, though, as 160 | `tiny-initrd` currently does not check if a block device has array 161 | metadata, so it could falsely identify a member device (instead of 162 | the entire array) when using `UUID=` in some cases. But for arrays 163 | that are assembled by the kernel via `md=...` the device name is 164 | known anyway (typically `/dev/md0`), so this shouldn't be an issue. 165 | * NFS support is not thoroughly tested. 166 | * Host names are unsupported for NFS mounts, only IP addresses work. 167 | * While this is supposed to be portable, this has only been tested on 168 | x86_64 (amd64). Since low-level kernel syscalls are performed, there 169 | may be some issues on other architectures. Please report those if 170 | they are present. 171 | 172 | HOWTO 173 | ----- 174 | 175 | Install an alternative libc implementation that's designed for embedded 176 | use cases, such as [musl](http://www.musl-libc.org/) or 177 | [dietlibc](http://www.fefe.de/dietlibc/). This is strictly speaking not 178 | required, as the default glibc will also work, but then the binary size 179 | of the resulting binary will be far larger. If `tiny-initramfs` doesn't 180 | work with your favorite libc implementation, please report this, so 181 | that it may be fixed. 182 | 183 | Find out the compile command required to use your C library. For 184 | example, with dietlibc it's `"diet gcc"`, with musl it's `musl-gcc`. 185 | 186 | Use 187 | 188 | ./configure CC="diet gcc" 189 | make 190 | 191 | to compile the `tiny_initramfs` binary and 192 | 193 | make initrd.img 194 | 195 | to auto-create the initramfs image. Replace `"diet gcc"` with the 196 | appropriate command for your libc implementation. 197 | 198 | Note that if you specify `CFLAGS` (potentially via your build system) 199 | you should take care to specify `-Os` and *not* to specify any debug 200 | (`-g`) options, as those tend to increase the binary size quite a bit. 201 | `./configure` will warn you about it, but it not abort in that case, 202 | because the binary will work. Likewise, if you don't use an alternative 203 | libc implementation but glibc, `./configure` will warn you about it, 204 | because that will increase the binary size by a factor of 10 to 20. 205 | 206 | You may specify multiple options to enable/disable certain features in 207 | the initramfs. Specifically, you can disable UUID mounting support 208 | (enabled by default), and you can enable NFSv4 support (disabled by 209 | default). A list of possible options is displayed when using 210 | 211 | ./configure --help 212 | 213 | The initramfs creation is really simple, you may also do so manually: 214 | 215 | 1. create an empty directory, let's call it `initramfs/` 216 | 2. copy `tiny_initramfs` to the directory, call it `init` (you can 217 | call it something else, but then you also need to pass the 218 | `rdinit=/newname` option to the kernel command line) 219 | 3. strip the binary to reduce it's size (optional) 220 | 4. create the `dev`, `proc` and `target` subdirectories 221 | 5. cpio the directory and compress it 222 | 223 | The following commands do just that: 224 | 225 | mkdir initramfs 226 | cp tiny_initramfs initramfs/init 227 | strip initramfs/init 228 | mkdir initramfs/dev initramfs/proc initramfs/target 229 | cd initramfs ; find . | cpio -o --quiet -R 0:0 -H newc | gzip > ../initrd.img 230 | 231 | With this there's now a (kernel-independent) initramfs image that may 232 | be used to boot the system. Note that as of now there is no integration 233 | with distributions, so configuring the boot loader etc. has to be done 234 | manually. 235 | 236 | Support for loading modules 237 | --------------------------- 238 | 239 | There is limited support for loading modules if `--enable-modules` is 240 | specified during the `configure` invocation. To use this feature, one 241 | needs to create a file `/modules` in the initramfs image that is of the 242 | following format: 243 | 244 | /file.ko options 245 | 246 | The modules should not be in a sub-directory, because the directory 247 | containing them will not be cleaned-up by tiny-initramfs after mounting 248 | the root file system. (Loading the modules will work though.) 249 | 250 | For example, the virtio block device driver `virtio_blk` requires some 251 | additional modules to work. Using `modprobe` one may find out which: 252 | 253 | $ /sbin/modprobe --all --ignore-install --quiet --show-depends virtio_blk 254 | insmod /lib/modules/[...]/kernel/drivers/virtio/virtio.ko 255 | insmod /lib/modules/[...]/kernel/drivers/virtio/virtio_ring.ko 256 | insmod /lib/modules/[...]/kernel/drivers/block/virtio_blk.ko 257 | 258 | It turns out that this is not quite sufficient, because the 259 | `virtio_pci` driver is also required for `virtio_blk` to work (the 260 | driver loads without `virtio_pci`, but doesn't work), so one may use: 261 | 262 | $ /sbin/modprobe --all --ignore-install --quiet --show-depends virtio_blk virtio_pci 263 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/virtio/virtio.ko 264 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/virtio/virtio_ring.ko 265 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/block/virtio_blk.ko 266 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/virtio/virtio.ko 267 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/virtio/virtio_ring.ko 268 | insmod /lib/modules/3.16.0-4-amd64/kernel/drivers/virtio/virtio_pci.ko 269 | 270 | (Note that in case soft dependencies are treated via `install` lines, 271 | these have to be resolved manually. This is typically not the case for 272 | drivers needed within initramfs, because other implementations also 273 | suffer from the same issue. `install` is deprecated anyway according to 274 | the manual page of `modprobe.d`.) 275 | 276 | One may then copy these drivers to the initramfs image, and then add 277 | a module file with the following contents: 278 | 279 | /virtio.ko 280 | /virtio_ring.ko 281 | /virtio_blk.ko 282 | /virtio.ko 283 | /virtio_ring.ko 284 | /virtio_pci.ko 285 | 286 | The order is important, because dependency resolution is **not** 287 | performed by tiny-initramfs, it has to be done while creating the 288 | initramfs image. Duplicate entries are not a problem, because they will 289 | silently be ignored (but you may remove duplicate entries if you don't 290 | change the order otherwise). 291 | 292 | Options may be specified when followed by a space (tab characters not 293 | supported), for example: 294 | 295 | /libata.ko noacpi 296 | 297 | Debugging 298 | --------- 299 | 300 | If an error occurs, tiny-initramfs will print an error message 301 | indicating the problem and then sleep for 10s before exiting. This is 302 | because exiting will cause a kernel panic, but typical kernel traces 303 | are so large that they replace the entire screen contents on a standard 304 | terminal, so that the original message is not visible anymore. The 10s 305 | delay allows the user to see what the problem is. 306 | 307 | Additionally, one may use the `--enable-debug` flag of `./configure` to 308 | make `initrd.img` verbose (while increasing the size a bit). This makes 309 | debugging easier, especially if the system hangs at a certain point. 310 | When compiled with that option, tiny-initramfs will print the contents 311 | of `/proc/self/mountinfo` and sleep for 5s after mounting the root (and 312 | potentially /usr) file systems before executing `init`. 313 | 314 | Design considerations 315 | --------------------- 316 | 317 | The design of `tiny-initramfs` is as minimalistic as possible. The 318 | buffered I/O functions from the `stdio.h` standard library are 319 | completely avoided, because they can increase the code size quite a 320 | bit, depending on the libc implementation. At one point an own 321 | minimalistic buffered I/O routine is implemented (much smaller than the 322 | full standard library linked in). 323 | 324 | Dynamic allocations are avoided and buffers on the stack are used. Code 325 | that properly handles dynamic allocations tends to be longer, so this 326 | reduces code size. The buffers are sized generously (there are not that 327 | many buffers that the amount of RAM used is a concern just yet, even 328 | for small systems), so that no real flexibility is sacrificed. 329 | 330 | None of this is extremely performance-critical (it is going to be quite 331 | fast regardless, because very little is done compared to even just 332 | running a shell), so no algorithm is optimized for speed directly. For 333 | example, the mount option parser table is somewhat compressed to reduce 334 | the code size (negation and recursive variants of mount options are not 335 | repeated), to the point where further reduction would likely sacrifice 336 | the readability of the code. Execution speed is achieved by doing very 337 | little, not by micro-optimizing algorithms. 338 | 339 | Sometimes it is necessary to reimplement certain libc functions because 340 | using the libc variants increase the image size too much. For example, 341 | using `inet_ntoa` and `inet_aton` (to convert between ASCII to binary 342 | representations of IP addresses) from the musl C library will cause 343 | initramfs images (after compression) to be an additional 5 KiB larger 344 | as compared to the own implementation. 345 | 346 | Of course, changes that reduce the current code size even further (as 347 | long as the code remains readable) are very welcome. 348 | 349 | Future features 350 | --------------- 351 | 352 | There is no goal of adding too many additional features here, because 353 | any additional feature is going to increase the binary size, and this 354 | is supposed to be minimalistic and **not** a replacement for a full 355 | initramfs. If you need advanced features, please use an already 356 | existing solution. That said, there are a couple of things that might 357 | be interesting regardless: 358 | 359 | * Minimalistic NFSv2/3 mounting support (akin to the current NFSv4 360 | code). 361 | * Maybe support host name lookups for NFS mounts? (Probably not going 362 | to happen, as an own DNS resolver will likely increase the image 363 | size by too much - and is likely going to be rather complicated.) 364 | * Support `UUID=` for more filesystems, as long as they are really 365 | simple. Currently, the implementation checks the magic bytes of a 366 | given file system on the each device, and then compares the UUID at 367 | the right position in the file system metadata. (See `devices.c` for 368 | details on how this is implemented for the currently supported file 369 | systems.) 370 | * Support for excluding MD/RAID/... devices when probing for UUIDs of 371 | file systems. 372 | 373 | Note that the goal is to keep the `initrd.img` size smaller than 16 KiB 374 | on all platforms, so a cutoff of 15 KiB is used on x86_64, to leave 375 | room for different assembly code sizes etc., at least when used in a 376 | minimal configuration. Therefore, some features (such as `UUID=` and 377 | NFSv4 support) are compile-time optional. 378 | 379 | Note: any features missing from tiny-initramfs that would be required 380 | in a space-constrained environment (i.e. mainly embedded), where it was 381 | designed for, stand an excellent chance of being included later, at 382 | least compile-time optional. Please make your case if you are missing 383 | something. 384 | 385 | TODO 386 | ---- 387 | 388 | * bind mounts for /usr 389 | * clean up the code a bit. 390 | * go through all messages printed and make sure they are uniform in 391 | style 392 | -------------------------------------------------------------------------------- /autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | autoreconf --install 4 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_PREREQ([2.64]) 2 | AC_INIT([tiny-initramfs], 3 | [0.1], 4 | [https://github.com/chris-se/tiny-initramfs/issues], 5 | [tiny-initramfs], 6 | [https://github.com/chris-se/tiny-initramfs]) 7 | AM_INIT_AUTOMAKE([foreign 1.11 -Wall dist-xz no-dist-gzip dist-lzip]) 8 | AM_SILENT_RULES([yes]) 9 | : ${CFLAGS="-Os"} 10 | AC_PROG_CC 11 | AC_CONFIG_HEADERS([config.h]) 12 | AC_CONFIG_FILES([ 13 | Makefile 14 | ]) 15 | AC_ARG_ENABLE([uuid], [AS_HELP_STRING([--disable-uuid], [Enable support for searching for devices via their UUID (default is yes)])]) 16 | AS_IF([test x"$enable_uuid" != x"no"], [AC_DEFINE([ENABLE_UUID], [1], [Define if UUID support is enabled])]) 17 | AC_ARG_ENABLE([nfs4], [AS_HELP_STRING([--enable-nfs4], [Enable support for mounting NFSv4 shares (default is no)])]) 18 | AS_IF([test x"$enable_nfs4" = x"yes"], [AC_DEFINE([ENABLE_NFS4], [1], [Define if NFS4 support is enabled])]) 19 | AM_CONDITIONAL([ENABLE_NFS4], [test x"$enable_nfs4" = x"yes"]) 20 | AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [Enable support for printing debug messages])]) 21 | AS_IF([test x"$enable_debug" = x"yes"], [AC_DEFINE([ENABLE_DEBUG], [1], [Define if debug messages are enabled])]) 22 | AC_ARG_ENABLE([modules], [AS_HELP_STRING([--enable-modules], [Enable support for loading modules (default is no)])]) 23 | AS_IF([test x"$enable_modules" = x"yes"], [ 24 | AC_CHECK_FUNC([finit_module], [AC_DEFINE([HAVE_FINIT_MODULE], [1], [Defined if finit_module is available.])], []) 25 | AC_MSG_CHECKING([for SYS_finit_module]) 26 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include 27 | #include 28 | int a = 29 | #ifdef SYS_finit_module 30 | 42 31 | #endif 32 | ;]])],[ 33 | ac_cv_have_sys_finit_module=yes 34 | AC_DEFINE([HAVE_SYS_FINIT_MODULE], [1], [Defined if SYS_finit_module is available.]) 35 | AC_MSG_RESULT([yes]) 36 | ], [AC_MSG_RESULT([no])]) 37 | AC_CHECK_FUNC([init_module]) 38 | AS_IF([test x"$ac_cv_func_init_module" != x"yes" && test x"$ac_cv_have_sys_finit_module" != x"yes" && test x"$ac_cv_func_finit_module" != x"yes"], 39 | [AC_MSG_ERROR([Neither finit_module nor SYS_finit_module nor init_module syscalls available.]) 40 | ]) 41 | AC_DEFINE([ENABLE_MODULES], [1], [Define if support for loading modules is enabled]) 42 | ]) 43 | AC_ARG_WITH([variant-name], [AS_HELP_STRING([--with-variant-name=NAME], [The variant name of the installed binary (default: none)])]) 44 | AS_IF([test x"$with_variant_name" != x""], [ 45 | AC_DEFINE([VARIANT], ["$with_variant_name"], [The installed binary variant name]) 46 | AC_SUBST([VARIANT], ["$with_variant_name"]) 47 | ]) 48 | AM_CONDITIONAL([HAVE_VARIANT], [test x"$with_variant_name" != x""]) 49 | 50 | # Check for harmful CFLAGS in our build and warn the user. 51 | AS_CASE([$CFLAGS], [*-O[[12345\ ]]*], 52 | [AC_MSG_WARN([optimization level other than -Os specified in CFLAGS, this will increase your binary size.])], []) 53 | AS_CASE([$CFLAGS], [*-Os*], 54 | [], [AC_MSG_WARN([optimization level -Os not specified in CFLAGS, this will increase your binary size.])]) 55 | 56 | # Check if the user links against glibc. 57 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([[#include 58 | int a = 59 | #ifdef __GLIBC__ 60 | 42 61 | #endif 62 | ;]])], [AC_MSG_WARN([you are using glibc, binaries will be huge. Consider using an alternative libc implementation (e.g. dietlibc, musl) instead.])], []) 63 | 64 | AC_OUTPUT 65 | -------------------------------------------------------------------------------- /devices.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * devices.c: Device detection functions 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #define _LARGEFILE_SOURCE 22 | 23 | #include "tiny_initramfs.h" 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #ifdef ENABLE_UUID 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | /* Not all libcs define these things, unfortunately... */ 41 | #ifndef DT_UNKNOWN 42 | #define DT_UNKNOWN 0 43 | #define DT_FIFO 1 44 | #define DT_CHR 2 45 | #define DT_DIR 4 46 | #define DT_BLK 6 47 | #define DT_REG 8 48 | #define DT_LNK 10 49 | #define DT_SOCK 12 50 | #define DT_WHT 14 51 | #endif 52 | 53 | /* We can't include linux/fs.h here. */ 54 | #define BLKGETSIZE64 _IOR(0x12,114,size_t) 55 | 56 | static int hexbyte(char c); 57 | static int is_blockdev_excluded(const char *device_name); 58 | static int is_fs_with_uuid(const char *device_name, const char *uuid_buf); 59 | static int is_ext234_with_uuid(const char *device_name, const char *uuid_buf); 60 | static int is_xfs_with_uuid(const char *device_name, const char *uuid_buf); 61 | static int is_btrfs_with_uuid(const char *device_name, const char *uuid_buf); 62 | static int read_block(const char *device_name, off_t start, void *data_buffer, size_t len); 63 | 64 | int parse_uuid(char *uuid_buf /* 16 bytes */, const char *string_representation) 65 | { 66 | int n; 67 | int c1, c2; 68 | const char *ptr; 69 | if (strlen(string_representation) < 32) 70 | return -EINVAL; 71 | 72 | for (n = 0, ptr = string_representation; *ptr; ) { 73 | if (ptr != string_representation && ptr[0] == '-') 74 | ptr++; 75 | if (!ptr[0] || !ptr[1]) 76 | return -EINVAL; 77 | c1 = hexbyte(ptr[0]); 78 | c2 = hexbyte(ptr[1]); 79 | if (c1 < 0 || c2 < 0) 80 | return -EINVAL; 81 | if (n >= 16) 82 | return -EINVAL; 83 | uuid_buf[n++] = (char)((c1 << 4) + c2); 84 | ptr += 2; 85 | } 86 | 87 | if (n != 16) 88 | return -EINVAL; 89 | 90 | return 0; 91 | } 92 | #endif /* defined(ENABLE_UUID) */ 93 | 94 | void wait_for_device(char *real_device_name, int *timeout, const char *device, int delay) 95 | { 96 | /* We don't have udev running, but there is devtmpfs, so we just 97 | * do a very simple and stupid polling loop to wait until the 98 | * requested device is present. This could be improved a bit, 99 | * but for now it's good enough. */ 100 | time_t start, current; 101 | int have_device; 102 | static int have_shown_message_timeout; 103 | int type; 104 | unsigned int major, minor; 105 | char uuid[16]; 106 | 107 | /* Parse device information */ 108 | if (!is_valid_device_name(device, &type, &major, &minor, uuid)) 109 | panic(0, "Unsupported device specified: ", device, NULL); 110 | 111 | if (delay) 112 | (void)sleep(delay); 113 | 114 | /* Our timeout starts *after* the rootdelay. */ 115 | start = time(NULL); 116 | 117 | #ifdef ENABLE_UUID 118 | if (type != WANT_NAME) { 119 | have_device = scan_devices(real_device_name, type, major, minor, uuid); 120 | } else 121 | #endif 122 | { 123 | set_buf(real_device_name, MAX_PATH_LEN, device, NULL); 124 | have_device = access(device, F_OK) != 0; 125 | } 126 | 127 | while (have_device) { 128 | current = time(NULL); 129 | if (*timeout > 0 && current - start > *timeout) 130 | panic(0, "Timeout while waiting for devices for / (and possibly /usr) filesystems to appear " 131 | "(did you specify the correct ones?)", NULL); 132 | /* In case this takes longer, show a nice message so the user has SOME 133 | * idea of what's going on here. */ 134 | if (current - start > DEVICE_MESSAGE_TIMEOUT && !have_shown_message_timeout) { 135 | have_shown_message_timeout = 1; 136 | warn("Waiting for ", device, " to appear...", NULL); 137 | } 138 | /* Sleep for DEVICE_POLL_MSEC milliseconds, then poll again. */ 139 | struct timespec req = { 0, DEVICE_POLL_MSEC * 1000 * 1000 }; 140 | struct timespec rem; 141 | (void)nanosleep(&req, &rem); 142 | 143 | #ifdef ENABLE_UUID 144 | if (type != WANT_NAME) 145 | have_device = scan_devices(real_device_name, type, major, minor, uuid); 146 | else 147 | #endif 148 | have_device = access(device, F_OK) != 0; 149 | } 150 | 151 | /* Make sure we record how many seconds on the timeout are left, 152 | * because this function may be called again for the /usr filesystem. */ 153 | if (*timeout > 0) { 154 | current = time(NULL); 155 | *timeout = current - start; 156 | if (*timeout <= 0) 157 | *timeout = 1; 158 | } 159 | } 160 | 161 | int is_valid_device_name(const char *device_name, int *type, unsigned int* major, unsigned int *minor, char *uuid) 162 | { 163 | #ifdef ENABLE_UUID 164 | int r; 165 | char *endptr; 166 | char uuid_buf[32 + 4 + 1] = { 0 }; 167 | char uuid_temp[16]; 168 | unsigned long x; 169 | #else 170 | (void)major; 171 | (void)minor; 172 | (void)uuid; 173 | #endif 174 | 175 | if (!device_name) 176 | return 0; 177 | 178 | if (!*device_name) 179 | return 0; 180 | 181 | if (strncmp(device_name, "/dev/", 5) == 0) { 182 | if (type) 183 | *type = WANT_NAME; 184 | return 1; 185 | } 186 | 187 | #ifdef ENABLE_UUID 188 | /* 0x803 or so for 8:3 */ 189 | if (device_name[0] == '0' && device_name[1] == 'x') { 190 | x = strtoul(device_name + 2, &endptr, 16); 191 | if (endptr && !*endptr) { 192 | if (type) { 193 | *type = WANT_MAJMIN; 194 | *major = (int)(x >> 8); 195 | *minor = (int)(x & 0xff); 196 | } 197 | return 1; 198 | } 199 | return 0; 200 | } 201 | 202 | if (strncmp(device_name, "UUID=", 5) == 0) { 203 | char c; 204 | 205 | device_name += 5; 206 | c = *device_name; 207 | if (c == '"' || c == '\'') { 208 | ++device_name; 209 | if (device_name[strlen(device_name)-1] != c) 210 | return 0; 211 | if (strlen(device_name) > 32 + 4 + 1) 212 | return 0; 213 | strncpy(uuid_buf, device_name, 32 + 4); 214 | } else { 215 | if (strlen(device_name) > 32 + 4) 216 | return 0; 217 | strncpy(uuid_buf, device_name, 32 + 4); 218 | } 219 | if (!uuid) 220 | uuid = uuid_temp; 221 | r = (parse_uuid(uuid, uuid_buf) == 0); 222 | if (r && type) 223 | *type = WANT_UUID; 224 | return r; 225 | } 226 | #endif 227 | 228 | return 0; 229 | } 230 | 231 | #ifdef ENABLE_UUID 232 | /* Which data types for this structure is available is wildly 233 | * incompatible between libc implementations, so we just use the 234 | * stdint.h types. */ 235 | struct linux_dirent { 236 | uint64_t d_ino; 237 | int64_t d_off; 238 | uint16_t d_reclen; 239 | unsigned char d_type; 240 | char d_name[]; 241 | }; 242 | 243 | int scan_devices(char *device_name /* MAX_PATH_LEN bytes */, int type, unsigned int maj, unsigned int min, const char *uuid /* 16 bytes */) 244 | { 245 | int dirfd; 246 | int nread, bpos; 247 | struct linux_dirent *d; 248 | char buf[1024]; 249 | int r; 250 | struct stat st; 251 | char fn_buf[MAX_PATH_LEN]; 252 | 253 | dirfd = open("/dev", O_RDONLY | O_DIRECTORY | O_CLOEXEC); 254 | if (dirfd < 0) 255 | return -errno; 256 | 257 | while (1) { 258 | /* We assume that either of these will be available from a libc 259 | implementation. */ 260 | #ifdef SYS_getdents64 261 | nread = syscall(SYS_getdents64, dirfd, (void *)buf, 1024); 262 | #else 263 | nread = getdents64(dirfd, (void *)buf, 1024); 264 | #endif 265 | if (nread < 0) { 266 | r = -errno; 267 | close(dirfd); 268 | return -r; 269 | } 270 | 271 | if (nread == 0) 272 | break; 273 | 274 | for (bpos = 0; bpos < nread; ) { 275 | d = (struct linux_dirent *)(buf + bpos); 276 | set_buf(fn_buf, MAX_PATH_LEN, "/dev/", d->d_name, NULL); 277 | if (strcmp(d->d_name, ".") != 0 && 278 | strcmp(d->d_name, "..") != 0 && 279 | (d->d_type == DT_UNKNOWN || type == WANT_MAJMIN)) { 280 | r = stat(fn_buf, &st); 281 | if (r == 0 && S_ISBLK(st.st_mode)) 282 | d->d_type = DT_BLK; 283 | /* skip if stat fails */ 284 | if (r < 0 && type == WANT_MAJMIN) 285 | d->d_type = DT_UNKNOWN; 286 | } 287 | if (d->d_type == DT_BLK && !is_blockdev_excluded(d->d_name)) { 288 | /* See if we found the device we want... */ 289 | if (type == WANT_MAJMIN) { 290 | if (major(st.st_rdev) == maj && minor(st.st_rdev) == min) { 291 | set_buf(device_name, MAX_PATH_LEN, fn_buf, NULL); 292 | close(dirfd); 293 | return 0; 294 | } 295 | } else if (type == WANT_UUID) { 296 | if (is_fs_with_uuid(fn_buf, uuid)) { 297 | set_buf(device_name, MAX_PATH_LEN, fn_buf, NULL); 298 | close(dirfd); 299 | return 0; 300 | } 301 | } 302 | } 303 | bpos += d->d_reclen; 304 | } 305 | } 306 | 307 | close(dirfd); 308 | 309 | return -ENOENT; 310 | } 311 | 312 | int hexbyte(char c) 313 | { 314 | if (c >= '0' && c <= '9') 315 | return c - '0'; 316 | if (c >= 'A' && c <= 'F') 317 | return c - 'A' + 0xa; 318 | if (c >= 'a' && c <= 'f') 319 | return c - 'a' + 0xa; 320 | return -1; 321 | } 322 | 323 | int is_blockdev_excluded(const char *device_name) 324 | { 325 | typedef struct { 326 | const char *prefix; 327 | const char *suffix; 328 | } dev_match_t; 329 | static dev_match_t exclude_devices[] = { 330 | { "fd", NULL }, 331 | { "mtd", NULL }, 332 | { "nbd", NULL }, 333 | { "gnbd", NULL }, 334 | { "btibm", NULL }, 335 | { "dm-", NULL }, 336 | { "zram", NULL }, 337 | { "mmcblk", "rpmb" }, 338 | { "sr", NULL }, 339 | /* FIXME: We don't exclude md devices here, because we assume that 340 | * they will only exist if the kernel has assembled them 341 | * completely or not at all. (And the kernel only 342 | * automatically assembles devices if they are specified on 343 | * the kernel command line.) This isn't tested, however. */ 344 | /*{ "md", NULL },*/ 345 | { NULL, NULL } 346 | }; 347 | dev_match_t *ptr; 348 | size_t l = strlen(device_name); 349 | size_t k; 350 | int matched; 351 | 352 | for (ptr = exclude_devices; ptr->prefix || ptr->suffix; ptr++) { 353 | matched = 1; 354 | if (ptr->prefix) { 355 | if (strncmp(device_name, ptr->prefix, strlen(ptr->prefix)) != 0) 356 | matched = 0; 357 | } 358 | if (ptr->suffix) { 359 | k = strlen(ptr->suffix); 360 | if (l < k || strncmp(&device_name[l - k], ptr->suffix, k) != 0) 361 | matched = 0; 362 | } 363 | if (matched) 364 | return 1; 365 | } 366 | return 0; 367 | } 368 | 369 | int read_block(const char *device_name, off_t start, void *data_buffer, size_t len) 370 | { 371 | int fd, r; 372 | uint64_t blksize; 373 | off_t pos; 374 | ssize_t n; 375 | 376 | fd = open(device_name, O_RDONLY | O_CLOEXEC); 377 | if (fd < 0) 378 | return -errno; 379 | 380 | r = ioctl(fd, BLKGETSIZE64, &blksize); 381 | if (r < 0) { 382 | r = -errno; 383 | close(fd); 384 | return r; 385 | } 386 | 387 | if ((uint64_t)start + (uint64_t)len > blksize) { 388 | r = 1; 389 | close(fd); 390 | return r; 391 | } 392 | 393 | pos = lseek(fd, start, SEEK_SET); 394 | if (pos == (off_t)-1) { 395 | r = -errno; 396 | close(fd); 397 | return r; 398 | } 399 | 400 | n = read(fd, data_buffer, len); 401 | if (n < 0) { 402 | r = -errno; 403 | close(fd); 404 | return r; 405 | } 406 | 407 | close(fd); 408 | 409 | return 0; 410 | } 411 | 412 | int is_fs_with_uuid(const char *device_name, const char *uuid_buf) 413 | { 414 | return is_btrfs_with_uuid(device_name, uuid_buf) 415 | || is_xfs_with_uuid(device_name, uuid_buf) 416 | || is_ext234_with_uuid(device_name, uuid_buf); 417 | } 418 | 419 | int is_ext234_with_uuid(const char *device_name, const char *uuid_buf) 420 | { 421 | char buf[0x78]; 422 | int r; 423 | 424 | r = read_block(device_name, 1024, buf, 0x78); 425 | if (r < 0 || r > 0) 426 | return 0; 427 | 428 | return memcmp(&buf[0x38], "\x53\xef", 2) == 0 429 | && memcmp(&buf[0x68], uuid_buf, 16) == 0; 430 | } 431 | 432 | int is_xfs_with_uuid(const char *device_name, const char *uuid_buf) 433 | { 434 | char buf[0x30]; 435 | int r; 436 | 437 | r = read_block(device_name, 0, buf, 0x30); 438 | if (r < 0 || r > 0) 439 | return 0; 440 | 441 | return memcmp(&buf[0x00], "XFSB", 4) == 0 442 | && memcmp(&buf[0x20], uuid_buf, 16) == 0; 443 | } 444 | 445 | int is_btrfs_with_uuid(const char *device_name, const char *uuid_buf) 446 | { 447 | char buf[0x48]; 448 | int r; 449 | 450 | r = read_block(device_name, 0x10000, buf, 0x48); 451 | if (r < 0 || r > 0) 452 | return 0; 453 | 454 | return memcmp(&buf[0x40], "_BHRfS_M", 8) == 0 455 | && memcmp(&buf[0x20], uuid_buf, 16) == 0; 456 | } 457 | #endif /* defined(ENABLE_UUID) */ 458 | -------------------------------------------------------------------------------- /fstab.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * io.c: I/O helper functions 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include "tiny_initramfs.h" 26 | 27 | typedef struct fstab_find_fs_data { 28 | const char *dest; 29 | fstab_info *info; 30 | int found; 31 | } fstab_find_fs_data; 32 | 33 | static int process_fstab_entry(fstab_find_fs_data *data, const char *line, int line_is_incomplete); 34 | 35 | int fstab_find_fs(const char *dest, fstab_info *info) 36 | { 37 | int r; 38 | fstab_find_fs_data data = { dest, info, 0 }; 39 | r = traverse_file_by_line(TARGET_DIRECTORY FSTAB_FILENAME, (traverse_line_t)process_fstab_entry, &data); 40 | if (r < 0) 41 | return r; 42 | if (!data.found) 43 | return -ENOENT; 44 | return 0; 45 | } 46 | 47 | int process_fstab_entry(fstab_find_fs_data *data, const char *orig_line, int line_is_incomplete) 48 | { 49 | char *saveptr; 50 | char *token; 51 | int had_nws, i; 52 | char line[MAX_LINE_LEN] = { 0 }; 53 | char *fields[6] = { 0 }; 54 | 55 | /* more than MAX_LINE_LEN in fstab? just ignore it */ 56 | if (line_is_incomplete) 57 | return 0; 58 | 59 | /* ignore comments and empty lines */ 60 | if (!orig_line || !*orig_line || *orig_line == '#') 61 | return 0; 62 | 63 | /* ignore whitespace-only lines */ 64 | had_nws = 0; 65 | for (token = (char *)orig_line; *token; token++) { 66 | if (*token != ' ' && *token != '\t') { 67 | had_nws = 1; 68 | break; 69 | } 70 | } 71 | if (!had_nws) 72 | return 0; 73 | 74 | set_buf(line, MAX_LINE_LEN, orig_line, NULL); 75 | 76 | i = 0; 77 | for (token = strtok_r(line, " \t", &saveptr); token != NULL; token = strtok_r(NULL, " \t", &saveptr)) { 78 | if (i < 6) { 79 | fields[i] = token; 80 | } 81 | i++; 82 | } 83 | 84 | if (i != 6) 85 | return 0; 86 | 87 | /* we are only interested in /usr */ 88 | if (strcmp(fields[1], data->dest) != 0) 89 | return 0; 90 | 91 | if ( 92 | #ifdef ENABLE_NFS4 93 | strcmp(fields[2], "nfs") != 0 && strcmp(fields[2], "nfs4") != 0 94 | #else 95 | 1 96 | #endif 97 | ) { 98 | if (!is_valid_device_name(fields[0], NULL, NULL, NULL, NULL)) 99 | return -ENODEV; 100 | } 101 | 102 | /* NOTE: for the /usr use case this is sufficient, but in general 103 | * one needs to de-escape the source and dest fields, see e.g. 104 | * the fstab-decode utility. 105 | */ 106 | set_buf(data->info->source, MAX_PATH_LEN, fields[0], NULL); 107 | set_buf(data->info->dest, MAX_PATH_LEN, fields[1], NULL); 108 | set_buf(data->info->type, MAX_PATH_LEN, fields[2], NULL); 109 | set_buf(data->info->options, MAX_LINE_LEN, fields[3], NULL); 110 | data->info->dump = strtoul(fields[4], NULL, 10); 111 | data->info->pass = strtoul(fields[5], NULL, 10); 112 | data->found = 1; 113 | return 1; 114 | } 115 | -------------------------------------------------------------------------------- /io.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * io.c: I/O helper functions 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include "tiny_initramfs.h" 28 | 29 | int traverse_file_by_line(const char *filename, traverse_line_t fn, void *data) 30 | { 31 | int fd; 32 | ssize_t r; 33 | char buf[MAX_LINE_LEN] = { 0 }; 34 | char *pos; 35 | char *oldpos; 36 | int more_data = 1, line_is_incomplete = 0; 37 | int e; 38 | 39 | fd = open(filename, O_RDONLY | O_CLOEXEC); 40 | if (fd < 0) 41 | return -errno; 42 | 43 | pos = buf; 44 | 45 | while (more_data) { 46 | read_more_data: 47 | memset(pos, 0, MAX_LINE_LEN - 1 - (pos - buf)); 48 | r = read(fd, pos, MAX_LINE_LEN - 1 - (pos - buf)); 49 | if (r < 0) { 50 | e = -errno; 51 | close(fd); 52 | return e; 53 | } 54 | 55 | more_data = (r == MAX_LINE_LEN - 1 - (pos - buf)); 56 | 57 | oldpos = buf; 58 | do { 59 | pos = strchr(oldpos, '\n'); 60 | if (!pos && more_data) { 61 | if (oldpos == buf) { 62 | line_is_incomplete = 1; 63 | pos = oldpos = buf; 64 | } else { 65 | memmove(buf, oldpos, MAX_LINE_LEN - (oldpos - buf)); 66 | pos = buf + MAX_LINE_LEN - 1 - (oldpos - buf); 67 | oldpos = buf; 68 | } 69 | goto read_more_data; 70 | } 71 | if (pos) { 72 | *pos = '\0'; 73 | pos++; 74 | } 75 | e = fn(data, oldpos, line_is_incomplete); 76 | if (e) { 77 | close(fd); 78 | return e < 0 ? e : 0; 79 | } 80 | line_is_incomplete = 0; 81 | oldpos = pos; 82 | } while (oldpos); 83 | } 84 | close(fd); 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /log.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * log.c: Basic logging helpers 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "tiny_initramfs.h" 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | static void showmsgv(va_list ap, const char *before1, const char *after1, const char *after2); 31 | 32 | void panic(int err, ...) 33 | { 34 | va_list ap; 35 | va_start(ap, err); 36 | if (err) 37 | showmsgv(ap, NULL, ": ", strerror(err)); 38 | else 39 | showmsgv(ap, NULL, NULL, NULL); 40 | va_end(ap); 41 | 42 | /* We want the user to see the message before we cause a kernel panic, 43 | * because a kernel panic obscures the message. But we need to cause 44 | * a kernel panic (by PID 1 exiting), because if the user tells the 45 | * kernel to reboot on panic, we want to make sure this happens. */ 46 | warn("Will cause kernel panic in 10s...", NULL); 47 | sleep(10); 48 | _exit(1); 49 | } 50 | 51 | void warn(const char *str1, ...) 52 | { 53 | va_list ap; 54 | va_start(ap, str1); 55 | showmsgv(ap, str1, NULL, NULL); 56 | va_end(ap); 57 | } 58 | 59 | void showmsgv(va_list ap, const char *before1, const char *after1, const char *after2) 60 | { 61 | /* Don't use stdio functions, because we link statically 62 | * and they bloat the binary. */ 63 | 64 | int argc = 1; 65 | int fd; 66 | struct iovec iov[32]; 67 | unsigned extra_arg_count = !!after1 + !!after2; 68 | const char *arg; 69 | 70 | if (before1) { 71 | iov[1].iov_base = (char *)before1; 72 | iov[1].iov_len = strlen(before1); 73 | argc++; 74 | } 75 | 76 | while ((arg = va_arg(ap, const char *))) { 77 | iov[argc].iov_base = (char *)arg; 78 | iov[argc].iov_len = strlen(arg); 79 | argc++; 80 | /* We only support a fixed number of arguments. */ 81 | if (argc + 1 + extra_arg_count > 32) 82 | break; 83 | } 84 | 85 | if (after1) { 86 | iov[argc].iov_base = (char *)after1; 87 | iov[argc].iov_len = strlen(after1); 88 | argc++; 89 | } 90 | 91 | if (after2) { 92 | iov[argc].iov_base = (char *)after2; 93 | iov[argc].iov_len = strlen(after2); 94 | argc++; 95 | } 96 | 97 | if (argc == 1) 98 | return; 99 | 100 | iov[argc].iov_base = (char *)"\n"; 101 | iov[argc].iov_len = 1; 102 | 103 | iov[0].iov_base = (char *)LOG_PREFIX; 104 | iov[0].iov_len = sizeof(LOG_PREFIX) - 1; 105 | 106 | /* Try to open /dev/kmsg, log to stderr if not possible */ 107 | fd = open(KMSG_FILENAME, O_WRONLY | O_NOCTTY | O_CLOEXEC); 108 | if (fd < 0) 109 | fd = 2; 110 | 111 | writev(fd, iov, argc + 1); 112 | 113 | if (fd >= 3) 114 | close(fd); 115 | } 116 | -------------------------------------------------------------------------------- /mount.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * mount.c: Helper functions for mounting filesystems 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "tiny_initramfs.h" 27 | 28 | /* dietlibc doesn't define MS_DIRSYNC for some reason 29 | * (probably a bug) 30 | */ 31 | #ifndef MS_DIRSYNC 32 | #define MS_DIRSYNC 128 33 | #endif 34 | 35 | /* Newer mount flags (last update: 2016-01) 36 | * (the rest are supported by both musl and dietlibc, should there be 37 | * a C library that doesn't yet contain other flags used, feel free to 38 | * add conditional defines here) 39 | */ 40 | #ifndef MS_LAZYTIME 41 | #define MS_LAZYTIME (1 << 25) 42 | #endif 43 | 44 | static char supported_filesystems[MAX_SUPPORTED_FILESYSTEMS][MAX_FILESYSTEM_TYPE_LEN]; 45 | static int supported_filesystems_count; 46 | static void determine_supported_filesystems(); 47 | static int process_proc_filesystems(void *data, const char *line, int line_is_incomplete); 48 | 49 | int mount_filesystem(const char *source, const char *target, 50 | const char *type, const char *flags, 51 | int override_flags_add, int override_flags_subtract) 52 | { 53 | int options; 54 | char data[MAX_LINE_LEN]; 55 | int nfsver = -1; 56 | int rc = -1; 57 | 58 | #ifdef ENABLE_DEBUG 59 | warn("mount_filesystem(\"", source, "\", \"", target, "\", \"", type ? type : "(null)", "\", \"", flags, "\", ...): begin", NULL); 60 | #endif 61 | 62 | #ifdef ENABLE_NFS4 63 | if (type && (!strcmp(type, "nfs") || !strcmp(type, "nfs4"))) 64 | nfsver = !strcmp(type, "nfs4") ? 4 : 0; 65 | #endif 66 | options = parse_mount_options(data, MAX_LINE_LEN, flags, nfsver != -1 ? &nfsver : NULL); 67 | 68 | #ifdef ENABLE_DEBUG 69 | warn("mount_filesystem: parsing mount options (done), unparsed options: ", data, NULL); 70 | #endif 71 | 72 | options |= override_flags_add; 73 | options &= ~override_flags_subtract; 74 | 75 | #ifdef ENABLE_NFS4 76 | if (type && !strcmp(type, "nfs4") && nfsver != 4) 77 | panic(0, "Cannot combine [nfs]vers=2/3 option with filesystem type nfs4.", NULL); 78 | if (type && (!strcmp(type, "nfs") || !strcmp(type, "nfs4"))) { 79 | if (nfsver != 4 && nfsver != 0) 80 | panic(0, "Sorry, only NFSv4 is currently supported.", NULL); 81 | /* Note that nfsver == 0 means we have type == nfs and no vers= parameter 82 | * at this point - which means that in principle we should try first NFSv4 83 | * and then NFSv3/2. But until we support NFSv3, we'll just do NFSv4. */ 84 | return mount_nfs4(source, target, options, data); 85 | } 86 | #endif 87 | 88 | #ifdef ENABLE_DEBUG 89 | warn("mount_filesystem: not NFS", NULL); 90 | #endif 91 | 92 | /* We need to loop through filesystem types as the kernel doesn't do 93 | * that for us if we call mount(). libmount does something similar, 94 | * but we don't want to link against it. */ 95 | if ((!type || !strcmp(type, "auto") || !strcmp(type, "none")) && !(options & (MS_MOVE | MS_REMOUNT | MS_BIND))) { 96 | int i; 97 | 98 | determine_supported_filesystems(); 99 | 100 | errno = EINVAL; 101 | rc = -1; 102 | for (i = 0; rc < 0 && i < supported_filesystems_count; i++) { 103 | rc = mount(source, target, supported_filesystems[i], options | MS_SILENT, data); 104 | } 105 | if (rc < 0) 106 | return -errno; 107 | return 0; 108 | } 109 | 110 | rc = mount(source, target, type, options, data); 111 | if (rc < 0) 112 | return -errno; 113 | return 0; 114 | } 115 | 116 | /* There are precisely 4 bits currently reserved for 117 | * kernel mount flags, so reuse them for parsing to 118 | * save code space. */ 119 | #define INVERTED (1U << 28) 120 | #define HAS_NO_VARIANT (1U << 29) 121 | #define HAS_R_VARIANT (1U << 30) 122 | #define IGNORE (1U << 31) 123 | 124 | #define FLAG_MASK ~(INVERTED | HAS_NO_VARIANT | HAS_R_VARIANT | IGNORE) 125 | 126 | int parse_mount_options(char *syscall_data, size_t syscall_data_len, const char *option_string, int *nfsver) 127 | { 128 | /* This is not very readable, but it will save quite 129 | * bit of space in the resulting binary... */ 130 | static const char *mount_option_names = 131 | /* 0 */ "ro\0" 132 | "rw\0" 133 | "exec\0" 134 | "suid\0" 135 | "dev\0" 136 | "sync\0" 137 | "dirsync\0" 138 | "remount\0" 139 | "bind\0" 140 | "silent\0" 141 | /* 10 */ "loud\0" 142 | "mand\0" 143 | "atime\0" 144 | "iversion\0" 145 | "diratime\0" 146 | "relatime\0" 147 | "strictatime\0" 148 | "unbindable\0" 149 | "private\0" 150 | "slave\0" 151 | /* 20 */ "shared\0" 152 | "defaults\0" 153 | /* NOTE: We ignore all of these for now, but if a filesystem we 154 | * want to mount really has these options set in /etc/fstab, 155 | * it's not clear that that is the right thing to do... 156 | * (Most of them don't make sense for /usr anyway, and we 157 | * don't support loop devices.) 158 | */ 159 | "_netdev\0" 160 | "auto\0" 161 | "user=\0" 162 | "users\0" 163 | "owner\0" 164 | "group\0" 165 | "comment=\0" 166 | "loop=\0" 167 | /* 30 */ "offset=\0" 168 | "sizelimit=\0" 169 | "encryption=\0" 170 | "nofail\0" 171 | "uhelper=\0" 172 | "helper=\0" 173 | ; 174 | static const unsigned int mount_option_flags[] = { 175 | /* 0 */ 0 | MS_RDONLY, 176 | INVERTED | MS_RDONLY, 177 | INVERTED | HAS_NO_VARIANT | MS_NOEXEC, 178 | INVERTED | HAS_NO_VARIANT | MS_NOSUID, 179 | INVERTED | HAS_NO_VARIANT | MS_NODEV, 180 | HAS_NO_VARIANT | MS_SYNCHRONOUS, 181 | 0 | MS_DIRSYNC, 182 | 0 | MS_REMOUNT, 183 | HAS_R_VARIANT | MS_BIND, 184 | 0 | MS_SILENT, 185 | /* 10 */ INVERTED | MS_SILENT, 186 | HAS_NO_VARIANT | MS_MANDLOCK, 187 | INVERTED | HAS_NO_VARIANT | MS_NOATIME, 188 | HAS_NO_VARIANT | MS_I_VERSION, 189 | INVERTED | HAS_NO_VARIANT | MS_NODIRATIME, 190 | HAS_NO_VARIANT | MS_RELATIME, 191 | HAS_NO_VARIANT | MS_STRICTATIME, 192 | HAS_R_VARIANT | MS_UNBINDABLE, 193 | HAS_R_VARIANT | MS_PRIVATE, 194 | HAS_R_VARIANT | MS_SLAVE, 195 | /* 20 */ HAS_R_VARIANT | MS_SHARED, 196 | 0 | 0, 197 | IGNORE | 0, 198 | HAS_NO_VARIANT | IGNORE | 0, 199 | HAS_NO_VARIANT | IGNORE | 0, 200 | HAS_NO_VARIANT | IGNORE | 0, 201 | HAS_NO_VARIANT | IGNORE | 0, 202 | HAS_NO_VARIANT | IGNORE | 0, 203 | IGNORE | 0, 204 | IGNORE | 0, 205 | /* 30 */ IGNORE | 0, 206 | IGNORE | 0, 207 | IGNORE | 0, 208 | IGNORE | 0, 209 | IGNORE | 0, 210 | IGNORE | 0, 211 | 0 | 0 212 | }; 213 | 214 | char opts[MAX_LINE_LEN] = { 0 }; 215 | char *saveptr; 216 | char *token; 217 | char *check; 218 | int bits = 0; 219 | int had_variant; 220 | int applies; 221 | int bits_to_change; 222 | int invert; 223 | const char *opt_name; 224 | size_t opt_name_len; 225 | int opt_index, this_opt_index; 226 | int opt_flag = 0; 227 | 228 | set_buf(opts, MAX_LINE_LEN, option_string, NULL); 229 | memset(syscall_data, 0, syscall_data_len); 230 | 231 | for (token = strtok_r(opts, ",", &saveptr); token != NULL; token = strtok_r(NULL, ",", &saveptr)) { 232 | /* special case: ignore all that starts with x- */ 233 | if (token[0] == 'x' && token[1] == '-') 234 | continue; 235 | 236 | this_opt_index = -1; 237 | had_variant = 0; 238 | for (opt_index = 0, opt_name = mount_option_names, opt_name_len = strlen(opt_name); 239 | *opt_name; 240 | ++opt_index, opt_name += opt_name_len + 1, opt_name_len = strlen(opt_name)) 241 | { 242 | had_variant = 0; 243 | check = token; 244 | if (mount_option_flags[opt_index] & HAS_NO_VARIANT && strncmp(token, "no", 2) == 0) { 245 | had_variant = HAS_NO_VARIANT; 246 | check = token + 2; 247 | } else if (mount_option_flags[opt_index] & HAS_R_VARIANT && token[0] == 'r') { 248 | had_variant = HAS_R_VARIANT; 249 | check = token + 1; 250 | } 251 | recheck_full: 252 | if (opt_name[opt_name_len - 1] == '=') { 253 | applies = (strncmp(check, opt_name, opt_name_len) == 0) 254 | || (strlen(check) == opt_name_len - 1 && 255 | strncmp(check, opt_name, opt_name_len - 1) == 0); 256 | } else { 257 | applies = strcmp(check, opt_name) == 0; 258 | } 259 | if (!applies && had_variant) { 260 | /* just in case an option starts with 'no' or 'r' */ 261 | had_variant = 0; 262 | check = token; 263 | goto recheck_full; 264 | } 265 | if (applies) { 266 | this_opt_index = opt_index; 267 | break; 268 | } 269 | } 270 | 271 | if (this_opt_index != -1) { 272 | opt_flag = mount_option_flags[this_opt_index]; 273 | if (opt_flag & IGNORE) 274 | continue; 275 | bits_to_change = opt_flag & FLAG_MASK; 276 | if (opt_flag & HAS_R_VARIANT) 277 | bits_to_change |= MS_REC; 278 | /* logical XOR */ 279 | invert = !(opt_flag & INVERTED) != !(had_variant & HAS_NO_VARIANT); 280 | if (invert) 281 | bits &= ~bits_to_change; 282 | else 283 | bits |= bits_to_change; 284 | } else { 285 | /* Hack to handle fstype = nfs with vers = number, so we can 286 | * determine the NFS version and dispatch accordingly. nfsver 287 | * should only be non-NULL if the fstype is "nfs". */ 288 | if (nfsver && *nfsver > -1 && (strncmp(token, "vers=", 5) == 0 || strncmp(token, "nfsvers=", 8) == 0)) { 289 | char *endptr = NULL; 290 | char *eq = strchr(token, '=') + 1; 291 | long val; 292 | if (!*eq) 293 | panic(0, "Empty NFS version specified.", NULL); 294 | val = strtol(eq, &endptr, 10); 295 | if (!endptr || !*endptr) 296 | panic(0, "Invalid NFS version specified: ", eq, NULL); 297 | if (val != 2 && val != 3 && val != 4) 298 | panic(0, "Invalid NFS version specified: ", eq, NULL); 299 | *nfsver = (int)val; 300 | continue; 301 | } 302 | 303 | append_to_buf(syscall_data, syscall_data_len, *syscall_data ? "," : "", token, NULL); 304 | } 305 | } 306 | 307 | return bits; 308 | } 309 | 310 | void determine_supported_filesystems() 311 | { 312 | int r; 313 | 314 | /* we already did this */ 315 | if (supported_filesystems_count > 0) 316 | return; 317 | 318 | r = traverse_file_by_line(PROC_FILESYSTEMS_FILENAME, (traverse_line_t)process_proc_filesystems, NULL); 319 | if (r < 0) 320 | panic(-r, "could not determine list of kernel-supported filesystems", NULL); 321 | } 322 | 323 | int process_proc_filesystems(void *data, const char *line, int line_is_incomplete) 324 | { 325 | (void) data; 326 | /* yikes, shouldn't happen */ 327 | if (line_is_incomplete) 328 | return 0; 329 | if (!strncmp(line, "nodev ", 6) || !strncmp(line, "nodev\t", 6)) 330 | return 0; 331 | while (line[0] == ' ' || line[0] == '\t') 332 | ++line; 333 | if (supported_filesystems_count == MAX_SUPPORTED_FILESYSTEMS) { 334 | warn("kernel supports too many filesystem types, ignoring some " 335 | "(please specify the rootfstype= kernel parameter if your system doesn't boot because of this)", 336 | NULL); 337 | return 0; 338 | } 339 | set_buf(supported_filesystems[supported_filesystems_count++], MAX_FILESYSTEM_TYPE_LEN, line, NULL); 340 | return 0; 341 | } 342 | -------------------------------------------------------------------------------- /nfs.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * nfs.c: Helper functions for mounting NFSv4 filesystems 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | * Note: 21 | * 22 | * The mount_nfs4 function is based on the nfs4mount function in 23 | * util-linux (but heavily modified), originally by Trond Myklebust 24 | * , licensed under the GPLv2+. 25 | */ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include 34 | #include 35 | 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | #include "tiny_initramfs.h" 43 | #include "nfs4.h" 44 | 45 | #define AUTH_UNIX 1 46 | #define NFS_PORT 2049 47 | #define MOUNT_TIMEOUT 30 48 | 49 | /* Not defined by all libc implementations. */ 50 | #ifndef SOCK_CLOEXEC 51 | #define SOCK_CLOEXEC 02000000 52 | #endif 53 | 54 | #define MIN(a,b) \ 55 | ({ __typeof__ (a) _a = (a); \ 56 | __typeof__ (b) _b = (b); \ 57 | _a < _b ? _a : _b; }) 58 | 59 | static int nfs4_ping(int domain, int type, struct sockaddr *dest, socklen_t dest_len, int timeout, char *ip_addr, size_t ip_addr_len); 60 | 61 | /* See comment below why we reimplement this ourselves. */ 62 | static int small_inet_aton(const char *cp, struct in_addr *inp); 63 | static char *small_inet_ntoa(struct in_addr in); 64 | 65 | int mount_nfs4(const char *source, const char *target, 66 | int mount_flags, const char *nfs_options) 67 | { 68 | typedef struct { 69 | const char *name; 70 | int *ptr; 71 | } num_opt_def_t; 72 | 73 | typedef struct { 74 | const char *name; 75 | int flag; 76 | } bool_opt_def_t; 77 | 78 | char p_options[MAX_LINE_LEN], *token, *saveptr, *opt_val, *endptr; 79 | long val; 80 | struct sockaddr_in server_addr = { 0 }; 81 | char ip_addr[16] = "127.0.0.1"; 82 | char hostname[MAX_LINE_LEN] = { 0 }; 83 | char mnt_path[MAX_LINE_LEN] = { 0 }; 84 | struct nfs4_mount_data data = { 0 }; 85 | 86 | int bg = 0, 87 | retry = -1; 88 | 89 | int auth_pseudoflavor = AUTH_UNIX; 90 | time_t timeout; 91 | int r; 92 | int dummy; 93 | int had_warning; 94 | 95 | num_opt_def_t num_opt_defs[] = { 96 | { "rsize", &data.rsize }, 97 | { "wsize", &data.wsize }, 98 | { "timeo", &data.timeo }, 99 | { "retrans", &data.retrans }, 100 | { "acregmin", &data.acregmin }, 101 | { "acregmax", &data.acregmax }, 102 | { "acdirmin", &data.acdirmin }, 103 | { "acdirmax", &data.acdirmax }, 104 | { "retry", &retry }, 105 | { "vers", &dummy }, 106 | { NULL, NULL } 107 | }; 108 | #define INVERTED 0x10000 109 | bool_opt_def_t bool_opt_defs[] = { 110 | { "bg", 0 }, 111 | { "fg", INVERTED }, 112 | { "soft", NFS4_MOUNT_SOFT }, 113 | { "hard", NFS4_MOUNT_SOFT | INVERTED }, 114 | { "intr", NFS4_MOUNT_INTR }, 115 | { "cto", NFS4_MOUNT_NOCTO | INVERTED }, 116 | { "ac", NFS4_MOUNT_NOAC | INVERTED }, 117 | { "sharedcache", NFS4_MOUNT_UNSHARED | INVERTED }, 118 | { NULL, 0 } 119 | }; 120 | num_opt_def_t *num_opt_def; 121 | bool_opt_def_t *bool_opt_def; 122 | 123 | set_buf(p_options, MAX_LINE_LEN, nfs_options, NULL); 124 | 125 | data.retrans = 3; 126 | data.acregmin = 3; 127 | data.acregmax = 60; 128 | data.acdirmin = 30; 129 | data.acdirmax = 60; 130 | data.proto = IPPROTO_TCP; 131 | 132 | opt_val = strchr((char *)source, ':'); 133 | if (!opt_val) 134 | panic(0, "nfs mount: directory to mount not in host:dir format: ", source, NULL); 135 | strncpy(hostname, source, MIN(MAX_LINE_LEN - 1, opt_val - source)); 136 | set_buf(mnt_path, MAX_LINE_LEN, opt_val + 1, NULL); 137 | 138 | server_addr.sin_family = AF_INET; 139 | server_addr.sin_port = htons(NFS_PORT); 140 | if (!small_inet_aton(hostname, &server_addr.sin_addr)) 141 | panic(0, "nfs mount: only IP addresses supported for mounting NFS servers, got ", hostname, " instead.", NULL); 142 | 143 | for (token = strtok_r(p_options, ",", &saveptr); token != NULL; token = strtok_r(NULL, ",", &saveptr)) { 144 | opt_val = strchr(token, '='); 145 | if (opt_val) { 146 | *opt_val = '\0'; 147 | opt_val++; 148 | if (strcmp(token, "proto") == 0) { 149 | if (strcmp(opt_val, "tcp") == 0) 150 | data.proto = IPPROTO_TCP; 151 | else if (strcmp(opt_val, "udp") == 0) 152 | data.proto = IPPROTO_UDP; 153 | else 154 | panic(0, "nfs mount: invalid proto option specified (valid values are: tcp, udp)", NULL); 155 | continue; 156 | } else if (strcmp(token, "clientaddr") == 0) { 157 | /* FIXME */ 158 | panic(0, "nfs mount: clientaddr not supported yet", NULL); 159 | } else if (strcmp(token, "sec") == 0) { 160 | if (strcmp(opt_val + 1, "sys") != 0) 161 | panic(0, "nfs mount: only sec=sys is supported", NULL); 162 | continue; 163 | } 164 | 165 | if (!*opt_val) 166 | panic(0, "nfs mount: invalid empty option ", token, " specified", NULL); 167 | 168 | endptr = NULL; 169 | val = strtol(opt_val, &endptr, 10); 170 | if (!endptr || !*endptr) 171 | panic(0, "nfs mount: option ", token, " requires a number, got ", opt_val, " instead.", NULL); 172 | 173 | if (strcmp(token, "port") == 0) { 174 | server_addr.sin_port = htons((int)val); 175 | continue; 176 | } 177 | 178 | if (strcmp(token, "actimeo") == 0) { 179 | data.acregmin = data.acregmax = data.acdirmin = data.acdirmax = (int)val; 180 | continue; 181 | } 182 | 183 | for (num_opt_def = num_opt_defs; num_opt_def->name; num_opt_def++) { 184 | if (strcmp(token, num_opt_def->name) == 0) { 185 | *num_opt_def->ptr = (int)val; 186 | break; 187 | } 188 | } 189 | if (!num_opt_def->name) 190 | panic(0, "nfs mount: invalid option ", token, "=", opt_val, NULL); 191 | } else { 192 | val = 1; 193 | if (strncmp(token, "no", 2) == 0) { 194 | opt_val = token + 2; 195 | val = 0; 196 | } else { 197 | opt_val = token; 198 | } 199 | if (strcmp(opt_val, "bg") == 0) { 200 | bg = 1; 201 | } else if (strcmp(opt_val, "fg") == 0) { 202 | bg = 0; 203 | } else { 204 | for (bool_opt_def = bool_opt_defs; bool_opt_def->name; bool_opt_def++) { 205 | if (strcmp(opt_val, bool_opt_def->name) == 0) { 206 | /* != is logical XOR in C */ 207 | val = val != !!(bool_opt_def->flag & INVERTED); 208 | if (val) 209 | data.flags |= (bool_opt_def->flag & NFS4_MOUNT_FLAGMASK); 210 | else 211 | data.flags &= ~(bool_opt_def->flag & NFS4_MOUNT_FLAGMASK); 212 | break; 213 | } 214 | } 215 | if (!bool_opt_def->name) 216 | panic(0, "nfs mount: invalid option ", token, NULL); 217 | } 218 | } 219 | } 220 | 221 | if (bg) { 222 | warn("nfs mount: background mounts unsupported for / and /usr, defaulting to foreground", NULL); 223 | bg = 0; 224 | } 225 | 226 | if (retry == -1) 227 | retry = 2; 228 | 229 | data.auth_flavourlen = 1; 230 | data.auth_flavours = &auth_pseudoflavor; 231 | 232 | data.mnt_path.data = mnt_path; 233 | data.mnt_path.len = strlen(mnt_path); 234 | 235 | data.hostname.data = hostname; 236 | data.hostname.len = strlen(hostname); 237 | 238 | data.host_addr = (struct sockaddr *)&server_addr; 239 | data.host_addrlen = sizeof(server_addr); 240 | 241 | timeout = time(NULL) + 60 * retry; 242 | data.version = NFS4_MOUNT_VERSION; 243 | 244 | had_warning = 0; 245 | 246 | for (;;) { 247 | r = nfs4_ping(AF_INET, data.proto == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM, (struct sockaddr *)&server_addr, sizeof(server_addr), MOUNT_TIMEOUT, ip_addr, sizeof(ip_addr)); 248 | if (r == 0) 249 | break; 250 | 251 | if (time(NULL) >= timeout) { 252 | if (r < 0 && r != -ETIMEDOUT) 253 | panic(r, "nfs mount: failed to mount ", source, NULL); 254 | else 255 | panic(0, "nfs mount: timeout while trying to mount ", source, NULL); 256 | } 257 | 258 | if (!had_warning) { 259 | had_warning = 1; 260 | if (r >= 0) 261 | r = -ETIMEDOUT; 262 | warn("nfs mount: waiting for response from NFS server ", hostname, ": ", strerror(-r), NULL); 263 | } 264 | 265 | /* Wait a bit before retrying, otherwise we will flood the network... */ 266 | if (r < 0 && r != -ETIMEDOUT) 267 | sleep(1); 268 | } 269 | 270 | data.client_addr.data = ip_addr; 271 | data.client_addr.len = strlen(ip_addr); 272 | 273 | r = mount(source, target, "nfs4", mount_flags, &data); 274 | if (r < 0) 275 | return -errno; 276 | return r; 277 | } 278 | 279 | int nfs4_ping(int domain, int type, struct sockaddr *dest, socklen_t dest_len, int timeout, char *ip_addr, size_t ip_addr_len) 280 | { 281 | /* So we don't really want to implement the whole RPC protocol 282 | * for NFSv4 (would be too much code), and since we need to do 283 | * a NULLPROC only anyway, where we know how the request and 284 | * response have to look like on a byte level, we just store 285 | * the packets here. If the response match, everything 286 | * succeeded. 287 | * 288 | * Also, we are going to blatantly assume that the NULLPROC 289 | * requests/responses are always going to fit into a single 290 | * RPC fragment. Otherwise, our code would get quite a bit 291 | * more complicated. */ 292 | char nullproc_request[] = { 293 | 0x80, 0x00, 0x00, 0x28, /* last fragment, fragment length: 40 */ 294 | 0x00, 0x00, 0x00, 0x00, /* xid, will be overwritten */ 295 | 0x00, 0x00, 0x00, 0x00, /* message type: call */ 296 | 0x00, 0x00, 0x00, 0x02, /* RPC Version: 2 */ 297 | 0x00, 0x01, 0x86, 0xa3, /* NFS */ 298 | 0x00, 0x00, 0x00, 0x04, /* Version 4 */ 299 | 0x00, 0x00, 0x00, 0x00, /* NULLPROC */ 300 | 0x00, 0x00, 0x00, 0x00, /* NULL credentials */ 301 | 0x00, 0x00, 0x00, 0x00, /* (length 0) */ 302 | 0x00, 0x00, 0x00, 0x00, /* NULL verifier */ 303 | 0x00, 0x00, 0x00, 0x00 /* (length 0) */ 304 | }; 305 | char nullproc_expected_response[] = { 306 | 0x80, 0x00, 0x00, 0x18, /* last fragment, fragment length: 24 */ 307 | 0x00, 0x00, 0x00, 0x00, /* xid, will be overwritten */ 308 | 0x00, 0x00, 0x00, 0x01, /* message type: reply */ 309 | 0x00, 0x00, 0x00, 0x00, /* reply state: accepted */ 310 | 0x00, 0x00, 0x00, 0x00, /* NULL verifier */ 311 | 0x00, 0x00, 0x00, 0x00, /* (length 0) */ 312 | 0x00, 0x00, 0x00, 0x00 /* accept state: RPC executed successfully */ 313 | }; 314 | char nullproc_response[sizeof(nullproc_expected_response)]; 315 | 316 | int sock_fd, r; 317 | ssize_t bytes; 318 | enum { 319 | WAIT_FOR_CONNECT, 320 | WAIT_FOR_SEND, 321 | WAIT_FOR_RECEIVE, 322 | DONE 323 | } state = WAIT_FOR_CONNECT; 324 | struct pollfd poll_fd; 325 | int timeout_msec = timeout * 1000; 326 | int pos = 0; 327 | size_t msg_start; 328 | socklen_t len; 329 | 330 | union { 331 | char buf[256]; 332 | struct sockaddr_in in; 333 | } client_addr; 334 | socklen_t client_addr_len = sizeof(client_addr); 335 | 336 | /* get some random data for xid 337 | * (we don't care about the entropy pool state, 338 | * as we don't pretend that sec=sys NFSv4 is at 339 | * all cryptographically safe) */ 340 | { 341 | int urandom_fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); 342 | if (urandom_fd < 0) 343 | return -errno; 344 | r = read(urandom_fd, nullproc_request + 4, 4); 345 | if (r != 4) { 346 | r = -errno; 347 | close(urandom_fd); 348 | return r; 349 | } 350 | close(urandom_fd); 351 | /* copy xid so we are sure that we get something matching 352 | * back */ 353 | memcpy(nullproc_expected_response + 4, nullproc_request + 4, 4); 354 | } 355 | 356 | sock_fd = socket(domain, type | SOCK_CLOEXEC, 0); 357 | if (sock_fd < 0) 358 | return -errno; 359 | 360 | r = fcntl(sock_fd, F_GETFL); 361 | if (r < 0) 362 | goto error_out; 363 | 364 | r = fcntl(sock_fd, F_SETFL, r | O_NONBLOCK); 365 | if (r < 0) 366 | goto error_out; 367 | 368 | if (type == SOCK_DGRAM) { 369 | state = WAIT_FOR_SEND; 370 | msg_start = 4; 371 | } else { 372 | msg_start = 0; 373 | r = connect(sock_fd, dest, dest_len); 374 | if (r < 0 && errno != EINPROGRESS && errno != EWOULDBLOCK) 375 | goto error_out; 376 | } 377 | 378 | while (state != DONE) { 379 | poll_fd.fd = sock_fd; 380 | poll_fd.events = (state == WAIT_FOR_RECEIVE ? POLLIN : POLLOUT); 381 | poll_fd.revents = 0; 382 | r = poll(&poll_fd, 1, timeout_msec); 383 | if (r == 0) { 384 | errno = ETIMEDOUT; 385 | goto error_out; 386 | } 387 | 388 | switch (state) { 389 | case WAIT_FOR_CONNECT: 390 | len = sizeof(errno); 391 | r = getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, &errno, &len); 392 | if (r < 0 || errno != 0) 393 | goto error_out; 394 | state = WAIT_FOR_SEND; 395 | break; 396 | case WAIT_FOR_SEND: 397 | /* UDP doesn't have fragment length */ 398 | if (type == SOCK_DGRAM) 399 | bytes = sendto(sock_fd, nullproc_request + 4, sizeof(nullproc_request) - 4, 0, dest, dest_len); 400 | else 401 | bytes = send(sock_fd, nullproc_request, sizeof(nullproc_request), 0); 402 | if (bytes != (int)sizeof(nullproc_request) - (type == SOCK_DGRAM) * 4) { 403 | if (bytes >= 0) 404 | errno = EMSGSIZE; 405 | goto error_out; 406 | } 407 | state = WAIT_FOR_RECEIVE; 408 | pos = 0; 409 | break; 410 | case WAIT_FOR_RECEIVE: 411 | if (type == SOCK_DGRAM) { 412 | /* UDP doesn't have fragment length */ 413 | bytes = recvfrom(sock_fd, nullproc_response + 4, sizeof(nullproc_response) - 4, 0, dest, &dest_len); 414 | if (bytes != (int)sizeof(nullproc_response) - 4) { 415 | if (bytes >= 0) 416 | errno = -1; /* unexpected response */ 417 | goto error_out; 418 | } 419 | state = DONE; 420 | } else { 421 | bytes = recv(sock_fd, &nullproc_response[pos], sizeof(nullproc_response) - pos, 0); 422 | if (bytes <= 0) { 423 | if (bytes == 0) 424 | errno = -1; /* unexpected response */ 425 | goto error_out; 426 | } 427 | if (bytes < (int)sizeof(nullproc_response) - pos) { 428 | pos += bytes; 429 | continue; 430 | } 431 | state = DONE; 432 | } 433 | case DONE: 434 | break; 435 | } 436 | } 437 | 438 | /* We had a successful response from the server 439 | * at this point */ 440 | 441 | r = getsockname(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len); 442 | if (r < 0) 443 | r = -errno; 444 | 445 | close(sock_fd); 446 | 447 | if (r < 0) 448 | return r; 449 | 450 | /* Compare the response to the expected response */ 451 | r = memcmp(&nullproc_expected_response[msg_start], &nullproc_response[msg_start], sizeof(nullproc_response) - msg_start); 452 | if (r == 0 && ip_addr) { 453 | /* Write string representation of client address to ip_addr */ 454 | *ip_addr = '\0'; 455 | if (domain == AF_INET) 456 | set_buf(ip_addr, ip_addr_len, small_inet_ntoa(client_addr.in.sin_addr), NULL); 457 | } 458 | return r; 459 | 460 | error_out: 461 | r = -errno; 462 | close(sock_fd); 463 | return r; 464 | } 465 | 466 | /* We reimplement these functions ourselves, because including 467 | * arpa/inet.h + using the functions in the C library can increase the 468 | * size of the (compressed) initrd.img quite a bit with certain C 469 | * libraries. For example. when compiled against musl this adds around 470 | * 5 kiB to the code - just for converting IP addresses to their string 471 | * representation and back... :-( Doing this ourselves reduces the size 472 | * by quite a bit. (Note that we don't need this function often, so 473 | * efficiency is not a concern for the implementation. 474 | */ 475 | 476 | static const char ip_part_terminator_chars[4] = { '.', '.', '.', '\0' }; 477 | 478 | int small_inet_aton(const char *cp, struct in_addr *inp) 479 | { 480 | char *ptr, *endptr; 481 | int i; 482 | unsigned long value; 483 | union { 484 | char bytes[4]; 485 | struct in_addr addr; 486 | } result; 487 | 488 | for (i = 0, ptr = (char *)cp; i < 4; i++, ptr = endptr + 1) { 489 | endptr = NULL; 490 | value = strtoul(ptr, &endptr, 10); 491 | if (value >= 256 || !endptr || endptr == ptr || *endptr != ip_part_terminator_chars[i]) 492 | return 0; 493 | result.bytes[i] = (char)value; 494 | } 495 | 496 | *inp = result.addr; 497 | return 1; 498 | } 499 | 500 | char *small_inet_ntoa(struct in_addr in) 501 | { 502 | static char buf[16]; 503 | int i; 504 | char *ptr; 505 | union { 506 | char bytes[4]; 507 | struct in_addr addr; 508 | } input; 509 | 510 | input.addr = in; 511 | 512 | ptr = buf; 513 | for (i = 0; i < 4; i++) { 514 | unsigned int v = (unsigned char)input.bytes[i]; 515 | *ptr = v / 100 + '0'; 516 | v %= 100; 517 | ptr += (*ptr != '0'); 518 | *ptr = v / 10 + '0'; 519 | v %= 10; 520 | ptr += (*ptr != '0'); 521 | *ptr = v + '0'; 522 | ptr++; 523 | *ptr = ip_part_terminator_chars[i]; 524 | ptr++; 525 | } 526 | 527 | return buf; 528 | } 529 | -------------------------------------------------------------------------------- /nfs4.h: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * 4 | * nfs4.h: NFSv4 kernel interface definition 5 | * Copyright (C) 2002 Trond Myklebust 6 | * Originally licensed under the GPLv2+. 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program. If not, see . 20 | * 21 | * Note: 22 | * 23 | * This file is a slightly modified nfs4_mount.h from the util-linux 24 | * package. 25 | */ 26 | 27 | #ifndef TINY_INITRD_NFS4_H 28 | #define TINY_INITRD_NFS4_H 29 | 30 | /* 31 | * WARNING! Do not delete or change the order of these fields. If 32 | * a new field is required then add it to the end. The version field 33 | * tracks which fields are present. This will ensure some measure of 34 | * mount-to-kernel version compatibility. Some of these aren't used yet 35 | * but here they are anyway. 36 | */ 37 | #define NFS4_MOUNT_VERSION 1 38 | 39 | struct nfs_string { 40 | unsigned int len; 41 | const char* data; 42 | }; 43 | 44 | struct nfs4_mount_data { 45 | int version; /* 1 */ 46 | int flags; /* 1 */ 47 | int rsize; /* 1 */ 48 | int wsize; /* 1 */ 49 | int timeo; /* 1 */ 50 | int retrans; /* 1 */ 51 | int acregmin; /* 1 */ 52 | int acregmax; /* 1 */ 53 | int acdirmin; /* 1 */ 54 | int acdirmax; /* 1 */ 55 | 56 | /* see the definition of 'struct clientaddr4' in RFC3010 */ 57 | struct nfs_string client_addr; /* 1 */ 58 | 59 | /* Mount path */ 60 | struct nfs_string mnt_path; /* 1 */ 61 | 62 | /* Server details */ 63 | struct nfs_string hostname; /* 1 */ 64 | /* Server IP address */ 65 | unsigned int host_addrlen; /* 1 */ 66 | struct sockaddr* host_addr; /* 1 */ 67 | 68 | /* Transport protocol to use */ 69 | int proto; /* 1 */ 70 | 71 | /* Pseudo-flavours to use for authentication. See RFC2623 */ 72 | int auth_flavourlen; /* 1 */ 73 | int *auth_flavours; /* 1 */ 74 | }; 75 | 76 | /* bits in the flags field */ 77 | /* Note: the fields that correspond to existing NFSv2/v3 mount options 78 | * should mirror the values from include/linux/nfs_mount.h 79 | */ 80 | #define NFS4_MOUNT_SOFT 0x0001 /* 1 */ 81 | #define NFS4_MOUNT_INTR 0x0002 /* 1 */ 82 | #define NFS4_MOUNT_NOCTO 0x0010 /* 1 */ 83 | #define NFS4_MOUNT_NOAC 0x0020 /* 1 */ 84 | #define NFS4_MOUNT_STRICTLOCK 0x1000 /* 1 */ 85 | #define NFS4_MOUNT_UNSHARED 0x8000 /* 5 */ 86 | #define NFS4_MOUNT_FLAGMASK 0xFFFF 87 | 88 | #endif /* !defined(TINY_INITRD_NFS4_H) */ 89 | -------------------------------------------------------------------------------- /tiny_initramfs.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * tiny_initramfs.c: main program 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "tiny_initramfs.h" 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #if defined(ENABLE_MODULES) 29 | #if !defined(HAVE_FINIT_MODULE) && !defined(HAVE_SYS_FINIT_MODULE) 30 | #include 31 | #include 32 | #elif defined(HAVE_SYS_FINIT_MODULE) 33 | #include 34 | #endif 35 | #endif 36 | 37 | static void parse_cmdline(); 38 | static int parse_cmdline_helper(void *data, const char *line, int line_is_incomplete); 39 | static void try_exec(int orig_argc, char *const orig_argv[], const char *binary); 40 | #ifdef ENABLE_NFS4 41 | static int find_bootserver_from_pnp(); 42 | static int find_bootserver_helper(void *data, const char *line, int line_is_incomplete); 43 | #endif 44 | 45 | static void cleanup_initramfs(); 46 | 47 | #ifdef ENABLE_DEBUG 48 | static void debug_dump_file(const char *fn); 49 | static int debug_dump_file_helper(void *data, const char *line, int line_is_incomplete); 50 | #endif 51 | 52 | #ifdef ENABLE_MODULES 53 | static void load_modules(); 54 | static int load_module_helper(void *data, const char *line, int line_is_incomplete); 55 | static int cleanup_module_helper(void *data, const char *line, int line_is_incomplete); 56 | extern int init_module(void *module_image, unsigned long len, const char *param_values); 57 | #endif 58 | 59 | static char root_device[MAX_PATH_LEN]; 60 | static char root_options[MAX_LINE_LEN]; 61 | #ifdef ENABLE_NFS4 62 | static char root_nfshost[MAX_LINE_LEN]; 63 | static char root_nfsdir[MAX_LINE_LEN]; 64 | static char root_nfsoptions[MAX_LINE_LEN]; 65 | #endif 66 | static char root_fstype[MAX_FILESYSTEM_TYPE_LEN]; 67 | static int root_delay; 68 | static int root_wait_indefinitely; 69 | static char init_binary[MAX_PATH_LEN]; 70 | static int global_rw; 71 | 72 | int main(int argc, char **argv) 73 | { 74 | int r; 75 | int timeout_togo = DEVICE_TIMEOUT; 76 | fstab_info usrfs_info; 77 | char real_device_name[MAX_PATH_LEN] = { 0 }; 78 | #ifdef ENABLE_NFS4 79 | size_t root_fstype_len, root_options_len, root_nfsdir_len, root_nfsoptions_len; 80 | #endif 81 | 82 | #ifdef ENABLE_DEBUG 83 | warn("Began execution", NULL); 84 | #endif 85 | 86 | #ifdef ENABLE_MODULES 87 | load_modules(); 88 | #ifdef ENABLE_DEBUG 89 | warn("Loaded all kernel modules", NULL); 90 | #endif 91 | #endif /* defined(ENABLE_MODULES) */ 92 | 93 | r = mount("proc", "/proc", "proc", MS_NODEV | MS_NOEXEC | MS_NOSUID, NULL); 94 | if (r < 0) 95 | panic(errno, "Could not mount /proc", NULL); 96 | 97 | #ifdef ENABLE_DEBUG 98 | warn("Mounted /proc", NULL); 99 | #endif 100 | 101 | r = mount("udev", "/dev", "devtmpfs", 0, DEVTMPFS_MOUNTOPTS); 102 | if (r < 0) 103 | panic(errno, "Could not mount /dev (as devtmpfs)", NULL); 104 | 105 | #ifdef ENABLE_DEBUG 106 | warn("Mounted /dev", NULL); 107 | #endif 108 | 109 | parse_cmdline(); 110 | 111 | #ifdef ENABLE_DEBUG 112 | warn("Parsed ", PROC_CMDLINE_FILENAME, NULL); 113 | #endif 114 | 115 | if (!strlen(root_device)) { 116 | #ifdef ENABLE_NFS4 117 | if (strlen(root_nfshost)) 118 | set_buf(root_device, MAX_PATH_LEN, "/dev/nfs", NULL); 119 | else 120 | #endif 121 | panic(0, "No root filesystem (root=) specified", NULL); 122 | } 123 | 124 | #ifdef ENABLE_NFS4 125 | root_fstype_len = strlen(root_fstype); 126 | 127 | if (strcmp(root_device, "/dev/nfs") == 0) { 128 | /* We have nfsroot, so build together new device name */ 129 | if (!strlen(root_nfshost)) { 130 | r = find_bootserver_from_pnp(); 131 | if (r < 0 || !strlen(root_nfshost)) 132 | panic(r ? -r : ENOENT, "Failed to determine boot server from kernel", NULL); 133 | } 134 | 135 | /* Make sure file system type is set properly */ 136 | if (!root_fstype_len || (strcmp(root_fstype, "nfs") != 0 && strcmp(root_fstype, "nfs4") != 0)) { 137 | if (root_fstype_len) 138 | warn("rootfstype set to ", root_fstype, " but root=/dev/nfs specified. Assuming rootfstype=nfs.", NULL); 139 | set_buf(root_fstype, MAX_FILESYSTEM_TYPE_LEN, "nfs", NULL); 140 | } 141 | 142 | root_nfsdir_len = strlen(root_nfsdir); 143 | root_nfsoptions_len = strlen(root_nfsoptions); 144 | root_options_len = strlen(root_options); 145 | 146 | /* This will be special-cased when mounting the filesystem to 147 | * replace it with the IP. */ 148 | if (!root_nfsdir_len) 149 | set_buf(root_nfsdir, MAX_LINE_LEN, DEFAULT_ROOTFS_NFS_DIR, NULL); 150 | 151 | if (strlen(root_nfshost) + 1 + root_nfsdir_len + 1 > MAX_PATH_LEN) 152 | panic(0, "nfsroot=", root_nfshost, ":", root_nfsdir, " too long.", NULL); 153 | 154 | set_buf(real_device_name, MAX_PATH_LEN, root_nfshost, ":", root_nfsdir, NULL); 155 | 156 | if (root_nfsoptions_len) { 157 | if (root_options_len + root_nfsoptions_len + 2 > MAX_LINE_LEN) 158 | panic(0, "nfsroot options (\"", root_nfsoptions, "\") too long.", NULL); 159 | append_to_buf(root_options, MAX_LINE_LEN, root_options_len ? "," : "", root_nfsoptions, NULL); 160 | } 161 | } else 162 | #endif 163 | { 164 | if (root_wait_indefinitely) 165 | timeout_togo = -1; 166 | wait_for_device(real_device_name, &timeout_togo, root_device, root_delay); 167 | } 168 | 169 | #ifdef ENABLE_DEBUG 170 | warn("Waited for root device", NULL); 171 | #endif 172 | 173 | r = mount_filesystem(real_device_name, TARGET_DIRECTORY, strlen(root_fstype) ? root_fstype : NULL, root_options, global_rw ? 0 : MS_RDONLY, global_rw ? MS_RDONLY : 0); 174 | if (r < 0) 175 | panic(-r, "Failed to mount root filesystem from ", root_device, NULL); 176 | 177 | #ifdef ENABLE_DEBUG 178 | warn("Mounted root filesystem", NULL); 179 | #endif 180 | 181 | /* We need these regardless of /usr handling */ 182 | if (access(TARGET_DIRECTORY "/dev", F_OK) != 0) 183 | panic(errno, "/dev doesn't exist on root filesystem", NULL); 184 | if (access(TARGET_DIRECTORY "/proc", F_OK) != 0) 185 | panic(errno, "/proc doesn't exist on root filesystem", NULL); 186 | 187 | /* Make sure we mount /usr if present in /etc/fstab 188 | * (no /etc/fstab is no error, we just assume that there'll 189 | * be no entry then) */ 190 | r = fstab_find_fs("/usr", &usrfs_info); 191 | if (r < 0 && r != -ENOENT && r != -ENODEV) 192 | panic(-r, "Failed to parse /etc/fstab in root device (non-existence would not be an error)", NULL); 193 | if (r == -ENODEV) 194 | panic(0, "Entry in /etc/fstab for /usr must be a (non-symlink) kernel device path" 195 | #ifdef ENABLE_UUID 196 | ", or of the form UUID=" 197 | #endif 198 | #ifdef ENABLE_NFS4 199 | ", or an NFS filesystem." 200 | #endif 201 | , NULL); 202 | 203 | #ifdef ENABLE_DEBUG 204 | warn("Parsed ", FSTAB_FILENAME, NULL); 205 | #endif 206 | 207 | if (r == 0) { 208 | int usr_rw_override = global_rw; 209 | 210 | #ifdef ENABLE_DEBUG 211 | warn("Separate /usr filesystem: trying to mount", NULL); 212 | #endif 213 | 214 | if ( 215 | #ifdef ENABLE_NFS4 216 | strcmp(usrfs_info.type, "nfs") != 0 && strcmp(usrfs_info.type, "nfs4") != 0 217 | #else 218 | 1 219 | #endif 220 | ) { 221 | /* wait for /usr filesystem device */ 222 | wait_for_device(real_device_name, &timeout_togo, usrfs_info.source, 0); 223 | 224 | #ifdef ENABLE_DEBUG 225 | warn("Waited for /usr device", NULL); 226 | #endif 227 | } 228 | #ifdef ENABLE_NFS4 229 | else { 230 | set_buf(real_device_name, MAX_PATH_LEN, usrfs_info.source, NULL); 231 | 232 | /* for network filesystems don't consider ro/rw on the 233 | * kernel command line, but just keep the options set 234 | * in /etc/fstab */ 235 | usr_rw_override = 0; 236 | 237 | #ifdef ENABLE_DEBUG 238 | warn("No need to wait for /usr device (NFS)", NULL); 239 | #endif 240 | } 241 | #endif /* defined(ENABLE_NFS4) */ 242 | 243 | /* mount it */ 244 | r = mount_filesystem(real_device_name, TARGET_DIRECTORY "/usr", usrfs_info.type, usrfs_info.options, usr_rw_override ? 0 : MS_RDONLY, usr_rw_override ? MS_RDONLY : 0); 245 | if (r < 0) 246 | panic(-r, "Failed to mount /usr filesystem from ", usrfs_info.source, NULL); 247 | 248 | #ifdef ENABLE_DEBUG 249 | warn("Mounted /usr filesystem", NULL); 250 | } else { 251 | warn("No separate /usr filesystem", NULL); 252 | #endif 253 | } 254 | 255 | /* move mounts */ 256 | r = mount("/dev", TARGET_DIRECTORY "/dev", NULL, MS_MOVE, NULL); 257 | 258 | #ifdef ENABLE_DEBUG 259 | warn("Moved /dev mount", NULL); 260 | #endif 261 | 262 | if (!r) 263 | r = mount("/proc", TARGET_DIRECTORY "/proc", NULL, MS_MOVE, NULL); 264 | 265 | #ifdef ENABLE_DEBUG 266 | warn("Moved /proc mount", NULL); 267 | #endif 268 | 269 | if (r < 0) 270 | panic(errno, "Couldn't move /dev or /proc from initramfs to root filesystem", NULL); 271 | 272 | /* clean up initramfs contents to free memory */ 273 | cleanup_initramfs(); 274 | 275 | /* switch root */ 276 | r = chdir(TARGET_DIRECTORY); 277 | if (!r) 278 | r = mount(TARGET_DIRECTORY, "/", NULL, MS_MOVE, NULL); 279 | if (!r) 280 | r = chroot("."); 281 | if (r < 0) 282 | panic(errno, "Couldn't switch root filesystem", NULL); 283 | 284 | #ifdef ENABLE_DEBUG 285 | warn("Switched root file system, contents of /proc/self/mountinfo:", NULL); 286 | debug_dump_file("/proc/self/mountinfo"); 287 | warn("Sleeping for 5s", NULL); 288 | sleep(5); 289 | warn("Booting the system", NULL); 290 | #endif 291 | 292 | if (strlen(init_binary)) { 293 | try_exec(argc, argv, init_binary); 294 | } else { 295 | try_exec(argc, argv, "/sbin/init"); 296 | try_exec(argc, argv, "/etc/init"); 297 | try_exec(argc, argv, "/bin/init"); 298 | try_exec(argc, argv, "/bin/sh"); 299 | } 300 | 301 | /* Message stolen from Linux's init/main.c */ 302 | panic(0, "No working init found. Try passing init= option to kernel. " 303 | "See Linux's Documentation/init.txt for guidance.", NULL); 304 | _exit(1); 305 | return 1; 306 | } 307 | 308 | void parse_cmdline() 309 | { 310 | int r; 311 | r = traverse_file_by_line(PROC_CMDLINE_FILENAME, (traverse_line_t)parse_cmdline_helper, NULL); 312 | if (r < 0) 313 | panic(-r, "Could not parse ", PROC_CMDLINE_FILENAME, NULL); 314 | } 315 | 316 | int parse_cmdline_helper(void *data, const char *line, int line_is_incomplete) 317 | { 318 | char *token; 319 | char *saveptr; 320 | char *endptr; 321 | unsigned long lval; 322 | 323 | (void)data; 324 | /* this really shouldn't happen, but don't try to interpret garbage */ 325 | if (line_is_incomplete) 326 | return 0; 327 | 328 | for (token = strtok_r((char *)line, " \t", &saveptr); token != NULL; token = strtok_r(NULL, " \t", &saveptr)) { 329 | if (!strncmp(token, "root=", 5)) { 330 | token += 5; 331 | if (strlen(token) > MAX_PATH_LEN - 1) 332 | panic(0, "Parameter root=", token, " too long", NULL); 333 | if (!is_valid_device_name(token, NULL, NULL, NULL, NULL)) 334 | panic(0, "Parameter root=", token, " unsupported (only /dev/" 335 | #ifdef ENABLE_UUID 336 | ", 0xMAJMIN and UUID= are " 337 | #else 338 | " is " 339 | #endif 340 | " supported)", NULL); 341 | set_buf(root_device, MAX_PATH_LEN, token, NULL); 342 | } else if (!strncmp(token, "rootflags=", 10)) { 343 | token += 10; 344 | /* this will automatically be at least 10 bytes shorter than 345 | * MAX_LINE_LEN */ 346 | set_buf(root_options, MAX_PATH_LEN, token, NULL); 347 | } else if (!strncmp(token, "rootfstype=", 11)) { 348 | token += 11; 349 | if (strlen(token) > MAX_FILESYSTEM_TYPE_LEN - 1) 350 | panic(0, "Parameter rootfstype=", token, " too long", NULL); 351 | set_buf(root_fstype, MAX_FILESYSTEM_TYPE_LEN, token, NULL); 352 | } else if (!strncmp(token, "rootdelay=", 10)) { 353 | token += 10; 354 | lval = strtoul(token, &endptr, 10); 355 | if (!*token || !endptr || *endptr || lval > INT_MAX) 356 | panic(0, "Invalid rootdelay=", token," value, must be integer (and must fit into integer data type)", NULL); 357 | root_delay = (int) lval; 358 | } else if (!strcmp(token, "rootwait")) { 359 | root_wait_indefinitely = 1; 360 | } else if (!strcmp(token, "ro")) { 361 | global_rw = 0; 362 | } else if (!strcmp(token, "rw")) { 363 | global_rw = 1; 364 | } else if (!strncmp(token, "init=", 5)) { 365 | token += 5; 366 | if (strlen(token) > MAX_PATH_LEN - 1) 367 | panic(0, "Parameter init=", token, " too long", NULL); 368 | set_buf(init_binary, MAX_PATH_LEN, token, NULL); 369 | } 370 | #ifdef ENABLE_NFS4 371 | else if (!strncmp(token, "nfsroot=", 8)) { 372 | char *ptr; 373 | 374 | root_nfsdir[0] = '\0'; 375 | root_nfshost[0] = '\0'; 376 | root_nfsoptions[0] = '\0'; 377 | 378 | token += 8; 379 | ptr = strchr(token, ','); 380 | if (ptr) { 381 | *ptr++ = '\0'; 382 | set_buf(root_nfsoptions, MAX_LINE_LEN, ptr, NULL); 383 | } 384 | 385 | ptr = strchr(token, ':'); 386 | if (ptr) { 387 | *ptr = '\0'; 388 | set_buf(root_nfshost, MAX_LINE_LEN, token, NULL); 389 | token = ptr + 1; 390 | } 391 | 392 | set_buf(root_nfsdir, MAX_LINE_LEN, token, NULL); 393 | } 394 | #endif 395 | } 396 | return 0; 397 | } 398 | 399 | #ifdef ENABLE_NFS4 400 | int find_bootserver_from_pnp() 401 | { 402 | return traverse_file_by_line(PROC_NET_PNP_FILENAME, (traverse_line_t)find_bootserver_helper, NULL); 403 | } 404 | 405 | int find_bootserver_helper(void *data, const char *line, int line_is_incomplete) 406 | { 407 | const char *value; 408 | 409 | (void)data; 410 | 411 | /* ignore lines we don't understand */ 412 | if (line_is_incomplete) 413 | return 0; 414 | 415 | if (!strncmp(line, "bootserver", 10) && (line[10] == ' ' || line[10] == '\t')) { 416 | value = &line[11]; 417 | while (*value == ' ' || *value == '\t') 418 | ++value; 419 | if (strlen(value) > 0) 420 | set_buf(root_nfshost, MAX_LINE_LEN, value, NULL); 421 | 422 | return 1; 423 | } 424 | 425 | return 0; 426 | } 427 | #endif 428 | 429 | void try_exec(int orig_argc, char *const orig_argv[], const char *binary) 430 | { 431 | char *argv[256]; 432 | int i; 433 | 434 | if (orig_argc > 255) 435 | panic(0, "Too many arguments to init.", NULL); 436 | 437 | argv[0] = (char *)binary; 438 | for (i = 1; i < orig_argc; i++) 439 | argv[i] = orig_argv[i]; 440 | argv[i] = NULL; 441 | 442 | execv(binary, argv); 443 | } 444 | 445 | #ifdef ENABLE_DEBUG 446 | void debug_dump_file(const char *fn) 447 | { 448 | (void)traverse_file_by_line(fn, (traverse_line_t)debug_dump_file_helper, NULL); 449 | } 450 | 451 | static int debug_dump_file_helper(void *data, const char *line, int line_is_incomplete) 452 | { 453 | (void)data; 454 | (void)line_is_incomplete; 455 | warn(line, NULL); 456 | return 0; 457 | } 458 | #endif 459 | 460 | void cleanup_initramfs() 461 | { 462 | /* Try to remove files and directories that are no longer needed. As 463 | * this is optional, ignore the return values, because at worst this 464 | * is a tiny memory leak. (/init is small anyway.) /dev and /proc 465 | * have been moved to /target at the point when this function is 466 | * called. We can't remove /target, because the rootfs is mounted 467 | * there. */ 468 | (void) rmdir("/dev"); 469 | (void) rmdir("/proc"); 470 | (void) unlink("/init"); 471 | #ifdef ENABLE_MODULES 472 | (void) traverse_file_by_line(MODULES_FILE, (traverse_line_t) cleanup_module_helper, NULL); 473 | (void) unlink(MODULES_FILE); 474 | #endif 475 | } 476 | 477 | #ifdef ENABLE_MODULES 478 | void load_modules() 479 | { 480 | (void) traverse_file_by_line(MODULES_FILE, (traverse_line_t) load_module_helper, NULL); 481 | } 482 | 483 | int load_module_helper(void *data, const char *line, int line_is_incomplete) 484 | { 485 | (void)data; 486 | int r, fd; 487 | char *ptr; 488 | const char *opts; 489 | 490 | if (line_is_incomplete) 491 | return 0; 492 | 493 | if (!*line) 494 | return 0; 495 | 496 | ptr = strchr(line, ' '); 497 | if (ptr) { 498 | *ptr = '\0'; 499 | opts = ptr + 1; 500 | } else { 501 | opts = ""; 502 | } 503 | 504 | #ifdef ENABLE_DEBUG 505 | if (*opts) 506 | warn("Loading kernel module ", line, " (with options: ", opts, ")", NULL); 507 | else 508 | warn("Loading kernel module ", line, NULL); 509 | #endif 510 | 511 | fd = open(line, O_RDONLY | O_CLOEXEC); 512 | if (fd < 0) { 513 | warn("Couldn't load ", line, ": ", strerror(errno), NULL); 514 | return 0; 515 | } 516 | #if defined(HAVE_FINIT_MODULE) 517 | r = finit_module(fd, opts, 0); 518 | if (r < 0) 519 | r = -errno; 520 | #elif defined(HAVE_SYS_FINIT_MODULE) 521 | r = syscall(SYS_finit_module, fd, opts, 0); 522 | if (r < 0) 523 | r = -errno; 524 | #else 525 | { 526 | void *contents; 527 | struct stat st; 528 | 529 | r = fstat(fd, &st); 530 | if (r < 0) { 531 | warn("Couldn't stat ", line, ": ", strerror(errno), NULL); 532 | close(fd); 533 | return 0; 534 | } 535 | 536 | contents = mmap(NULL, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 537 | if (!contents) { 538 | warn("Couldn't mmap ", line, ": ", strerror(errno), NULL); 539 | close(fd); 540 | return 0; 541 | } 542 | r = init_module(contents, (unsigned long) st.st_size, opts); 543 | if (r < 0) 544 | r = -errno; 545 | munmap(contents, (size_t) st.st_size); 546 | } 547 | #endif 548 | 549 | /* Ignore duplicate modules, this simplifies initramfs creation logic 550 | * a bit. */ 551 | if (r < 0 && r != -EEXIST) 552 | warn("Couldn't load ", line, ": ", strerror(-r), NULL); 553 | 554 | close(fd); 555 | 556 | return 0; 557 | } 558 | 559 | int cleanup_module_helper(void *data, const char *line, int line_is_incomplete) 560 | { 561 | (void)data; 562 | char *ptr; 563 | 564 | if (line_is_incomplete) 565 | return 0; 566 | 567 | ptr = strchr(line, ' '); 568 | if (ptr) 569 | *ptr = '\0'; 570 | 571 | (void) unlink(line); 572 | return 0; 573 | } 574 | #endif 575 | -------------------------------------------------------------------------------- /tiny_initramfs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * tiny_initramfs.h: function declarations 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #ifndef TINY_INITRAMFS_H 22 | #define TINY_INITRAMFS_H 23 | 24 | #include 25 | #include 26 | 27 | #include 28 | 29 | #ifndef MAX_LINE_LEN 30 | #define MAX_LINE_LEN 4096 31 | #endif 32 | 33 | #ifndef MAX_PATH_LEN 34 | #define MAX_PATH_LEN 1024 35 | #endif 36 | 37 | #ifndef MODULES_FILE 38 | #define MODULES_FILE "/modules" 39 | #endif 40 | 41 | #ifndef TARGET_DIRECTORY 42 | #define TARGET_DIRECTORY "/target" 43 | #endif 44 | 45 | #ifndef FSTAB_FILENAME 46 | #define FSTAB_FILENAME "/etc/fstab" 47 | #endif 48 | 49 | #ifndef PROC_FILESYSTEMS_FILENAME 50 | #define PROC_FILESYSTEMS_FILENAME "/proc/filesystems" 51 | #endif 52 | 53 | #ifndef PROC_CMDLINE_FILENAME 54 | #define PROC_CMDLINE_FILENAME "/proc/cmdline" 55 | #endif 56 | 57 | #ifndef PROC_NET_PNP_FILENAME 58 | #define PROC_NET_PNP_FILENAME "/proc/net/pnp" 59 | #endif 60 | 61 | #ifndef KMSG_FILENAME 62 | #define KMSG_FILENAME "/dev/ksmg" 63 | #endif 64 | 65 | #ifndef MAX_SUPPORTED_FILESYSTEMS 66 | #define MAX_SUPPORTED_FILESYSTEMS 256 67 | #endif 68 | 69 | #ifndef MAX_FILESYSTEM_TYPE_LEN 70 | #define MAX_FILESYSTEM_TYPE_LEN 32 71 | #endif 72 | 73 | #ifndef LOG_PREFIX 74 | #define LOG_PREFIX "initramfs: " 75 | #endif 76 | 77 | #ifndef DEVTMPFS_MOUNTOPTS 78 | #define DEVTMPFS_MOUNTOPTS "size=10240k,mode=0755" 79 | #endif 80 | 81 | #ifndef DEVICE_TIMEOUT 82 | #define DEVICE_TIMEOUT 180 83 | #endif 84 | 85 | #ifndef DEVICE_MESSAGE_TIMEOUT 86 | #define DEVICE_MESSAGE_TIMEOUT 10 87 | #endif 88 | 89 | #ifndef DEVICE_POLL_MSEC 90 | #define DEVICE_POLL_MSEC 50 91 | #endif 92 | 93 | #ifndef DEFAULT_ROOTFS_NFS_DIR 94 | #define DEFAULT_ROOTFS_NFS_DIR "@@/tftpboot/%s@@" 95 | #endif 96 | 97 | /* Not all alternative libc implementations support these constants yet. */ 98 | #ifndef O_CLOEXEC 99 | #define O_CLOEXEC 02000000 100 | #endif 101 | 102 | /* io.c */ 103 | typedef int (*traverse_line_t)(void *data, const char *line, int line_is_incomplete); 104 | int traverse_file_by_line(const char *filename, traverse_line_t fn, void *data); 105 | 106 | /* fstab.c */ 107 | typedef struct fstab_info { 108 | char source[MAX_PATH_LEN]; 109 | char dest[MAX_PATH_LEN]; 110 | char type[MAX_PATH_LEN]; 111 | char options[MAX_LINE_LEN]; 112 | int dump; 113 | int pass; 114 | } fstab_info; 115 | int fstab_find_fs(const char *dest, fstab_info *info); 116 | 117 | /* mount.c */ 118 | int parse_mount_options(char *syscall_data, size_t syscall_data_len, const char *option_string, int *nfsver); 119 | int mount_filesystem(const char *source, const char *target, const char *type, const char *flags, int override_flags_add, int override_flags_subtract); 120 | 121 | /* log.c */ 122 | void panic(int err, ...) __attribute__((noreturn)); 123 | void warn(const char *str1, ...); 124 | 125 | /* devices.c */ 126 | enum { 127 | WANT_NAME = 0, 128 | WANT_MAJMIN = 1, 129 | WANT_UUID = 2 130 | }; 131 | void wait_for_device(char *real_device_name /* MAX_PATH_LEN bytes */, int *timeout, const char *device, int delay); 132 | #ifdef ENABLE_UUID 133 | int scan_devices(char *device_name /* MAX_PATH_LEN bytes */, int type, unsigned int maj, unsigned int min, const char *uuid /* 16 bytes */); 134 | int parse_uuid(char *uuid_buf /* 16 bytes */, const char *string_representation); 135 | #endif 136 | int is_valid_device_name(const char *device_name, int *type, unsigned int* major, unsigned int *minor, char *uuid /* 16 bytes */); 137 | 138 | /* util.c */ 139 | void append_to_buf(char *buf, size_t size, ...); 140 | void set_buf(char *buf, size_t size, ...); 141 | 142 | #ifdef ENABLE_NFS4 143 | /* nfs.c */ 144 | int mount_nfs4(const char *source, const char *target, int mount_flags, const char *nfs_options); 145 | #endif 146 | 147 | #endif /* !defined(TINY_INITRAMFS_H) */ 148 | -------------------------------------------------------------------------------- /util.c: -------------------------------------------------------------------------------- 1 | /* 2 | * tiny_initramfs - Minimalistic initramfs implementation 3 | * Copyright (C) 2016 Christian Seiler 4 | * 5 | * util.c: Misc helper functions 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | #include "tiny_initramfs.h" 22 | 23 | #include 24 | #include 25 | 26 | static void append_to_buf_v(char *buf, size_t size, va_list ap) 27 | { 28 | const char *ptr; 29 | size_t remaining_size; 30 | if (strlen(buf) > size) 31 | return; 32 | 33 | remaining_size = size - strlen(buf); 34 | 35 | for (ptr = va_arg(ap, const char *); ptr; ptr = va_arg(ap, const char *)) { 36 | strncat(buf, ptr, remaining_size - 1); 37 | 38 | /* Make sure it's NUL-terminated. */ 39 | if (strlen(ptr) >= remaining_size - 1) { 40 | buf[size - 1] = '\0'; 41 | break; 42 | } 43 | 44 | remaining_size -= strlen(ptr); 45 | } 46 | } 47 | 48 | void append_to_buf(char *buf, size_t size, ...) 49 | { 50 | va_list ap; 51 | 52 | va_start(ap, size); 53 | append_to_buf_v(buf, size, ap); 54 | va_end(ap); 55 | } 56 | 57 | void set_buf(char *buf, size_t size, ...) 58 | { 59 | va_list ap; 60 | 61 | va_start(ap, size); 62 | memset(buf, 0, size); 63 | append_to_buf_v(buf, size, ap); 64 | va_end(ap); 65 | } 66 | --------------------------------------------------------------------------------