projects/guix·blob ruby-team · refs

448 lines · 18.1 KiB

1;;; GNU Guix --- Functional package management for GNU
2;;; Copyright © 2013-2020, 2025 Ludovic Courtès <[email protected]>
3;;; Copyright © 2016 Christine Lemmer-Webber <[email protected]>
4;;; Copyright © 2016, 2017 Leo Famulari <[email protected]>
5;;; Copyright © 2017 Marius Bakke <[email protected]>
6;;; Copyright © 2020, 2022 Tobias Geerinckx-Rice <[email protected]>
7;;; Copyright © 2020 Mathieu Othacehe <[email protected]>
8;;; Copyright © 2022 Pavel Shlyak <[email protected]>
9;;; Copyright © 2022, 2025 Denis 'GNUtoo' Carikli <[email protected]>
10;;; Copyright © 2023 Efraim Flashner <[email protected]>
11;;;
12;;; This file is part of GNU Guix.
13;;;
14;;; GNU Guix is free software; you can redistribute it and/or modify it
15;;; under the terms of the GNU General Public License as published by
16;;; the Free Software Foundation; either version 3 of the License, or (at
17;;; your option) any later version.
18;;;
19;;; GNU Guix is distributed in the hope that it will be useful, but
20;;; WITHOUT ANY WARRANTY; without even the implied warranty of
21;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22;;; GNU General Public License for more details.
23;;;
24;;; You should have received a copy of the GNU General Public License
25;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
26
27(define-module (gnu build image)
28 #:use-module (guix build store-copy)
29 #:use-module (guix build syscalls)
30 #:use-module (guix build utils)
31 #:use-module (guix store database)
32 #:use-module (guix utils)
33 #:use-module (gnu build bootloader)
34 #:use-module (gnu build install)
35 #:use-module (gnu build linux-boot)
36 #:use-module (gnu image)
37 #:use-module (gnu system uuid)
38 #:use-module (ice-9 ftw)
39 #:use-module (ice-9 match)
40 #:use-module (srfi srfi-19)
41 #:use-module (srfi srfi-34)
42 #:use-module (srfi srfi-35)
43 #:export (make-partition-image
44 convert-disk-image
45 genimage
46 initialize-efi-partition
47 initialize-efi32-partition
48 initialize-root-partition
49
50 make-iso9660-image))
51
52(define (sexp->partition sexp)
53 "Take SEXP, a tuple as returned by 'partition->gexp', and turn it into a
54<partition> record."
55 (match sexp
56 ((size file-system file-system-options label uuid flags)
57 (partition (size size)
58 (file-system file-system)
59 (file-system-options file-system-options)
60 (label label)
61 (uuid uuid)
62 (flags flags)))))
63
64(define (size-in-kib size)
65 "Convert SIZE expressed in bytes, to kilobytes and return it as a string."
66 (number->string
67 (inexact->exact (ceiling (/ size 1024)))))
68
69(define* (estimate-partition-size root #:optional (margin .25))
70 "Given the ROOT directory, evaluate and return its size. As this doesn't
71take the partition metadata size into account, take a MARGIN. As this in
72turn doesn't take any constant overhead into account, force a 1-MiB minimum."
73 (max (ash 1 20)
74 ;; without inexact->exact, 'guess can result in an error like that:
75 ;; "Wrong type (expecting exact integer): 7179941140.0".
76 (inexact->exact (round (* (+ 1. margin) (file-size root))))))
77
78(define* (make-btrfs-image partition target root)
79 "Handle the creation of BTRFS partition images. See
80'make-partition-image'."
81 (let ((size (partition-size partition))
82 (fs-options (partition-file-system-options partition))
83 (label (partition-label partition))
84 (uuid (partition-uuid partition)))
85 (apply invoke
86 `("unshare" "--map-root-user" "mkfs.btrfs"
87 "-r" ,root
88 "-L" ,label
89 ,@(if uuid
90 `("-U" ,(uuid->string uuid))
91 '())
92 "--shrink"
93 ,@fs-options
94 ,target))))
95
96(define* (make-ext-image partition target root
97 #:key
98 (owner-uid 0)
99 (owner-gid 0))
100 "Handle the creation of EXT2/3/4 partition images. See
101'make-partition-image'."
102 (let ((size (partition-size partition))
103 (fs (partition-file-system partition))
104 (fs-options (partition-file-system-options partition))
105 (label (partition-label partition))
106 (uuid (partition-uuid partition))
107 (journal-options "lazy_itable_init=1,lazy_journal_init=1"))
108 (apply invoke
109 `("fakeroot" "mke2fs" "-t" ,fs "-d" ,root
110 "-L" ,label
111 ,@(if uuid
112 `("-U" ,(uuid->string uuid))
113 '())
114 "-E" ,(format #f "root_owner=~a:~a,~a"
115 owner-uid owner-gid journal-options)
116 ,@fs-options
117 ,target
118 ,(format #f "~ak"
119 (size-in-kib
120 (if (eq? size 'guess)
121 (estimate-partition-size root)
122 size)))))
123
124 ;; 'mke2fs' does not create directory indexes by default, meaning that
125 ;; directories have a limit of 65,000 sub-directories, which can be
126 ;; problematic for the store. To avoid that, run 'e2fsck -D' to create
127 ;; those directory indexes. See
128 ;; <https://github.com/tytso/e2fsprogs/issues/257>.
129 (invoke "e2fsck" "-fDy" target)))
130
131(define* (make-f2fs-image partition target root
132 #:key
133 (owner-uid 0)
134 (owner-gid 0))
135 "Handle the creation of F2FS partition images. See 'make-partition-image'."
136 (let ((size (partition-size partition))
137 (label (partition-label partition))
138 (uuid (partition-uuid partition))
139 (fs-options (partition-file-system-options partition)))
140 ;; The mkfs.f2fs utility can't create files, so we need to create one
141 ;; before running it.
142 (call-with-output-file target (const #t))
143 (truncate-file
144 target
145 (if (eq? size 'guess)
146 ;; The F2FS filesystem has more overhead than other filesystems like
147 ;; BTRFS and ext4.
148 (estimate-partition-size root .50)
149 size))
150 (apply invoke "fakeroot" "mkfs.f2fs"
151 "-l" label
152 "-R" (format #f "~a:~a" owner-uid owner-gid)
153 `(,@(if uuid
154 `("-U" ,(uuid->string uuid))
155 '())
156 ,@fs-options
157 ,target))
158 (invoke "fakeroot" "sload.f2fs" "-P" "-f" root target)))
159
160(define* (make-vfat-image partition target root fs-bits)
161 "Handle the creation of VFAT partition images. See 'make-partition-image'."
162 (let ((size (partition-size partition))
163 (label (partition-label partition))
164 (flags (partition-flags partition))
165 (fs-options (partition-file-system-options partition)))
166 (apply invoke "fakeroot" "mkdosfs" "-n" label "-C" target
167 "-F" (number->string fs-bits)
168 (size-in-kib
169 (if (eq? size 'guess)
170 (estimate-partition-size root)
171 size))
172 ;; u-boot in particular needs the formatted block
173 ;; size and the physical block size to be equal.
174 ;; TODO: What about 4k blocks?
175 (if (and (member 'esp flags)
176 (not (member "-S" fs-options)))
177 (append (list "-S" "512") fs-options)
178 fs-options))
179 (for-each (lambda (file)
180 (unless (member file '("." ".."))
181 (invoke "mcopy" "-bsp" "-i" target
182 (string-append root "/" file)
183 (string-append "::" file))))
184 (scandir root))))
185
186(define* (make-swap-image partition target)
187 "Make a swap partition of a certain size."
188 (let ((size (partition-size partition))
189 (label (partition-label partition))
190 (uuid (partition-uuid partition))
191 (fs-options (partition-file-system-options partition)))
192 (apply invoke "fakeroot" "mkswap"
193 "--pagesize" "4096"
194 "--endianness" "little"
195 "-L" label
196 "--file" target
197 "--size" (number->string size)
198 `(,@(if uuid
199 `("-U" ,(uuid->string uuid))
200 '())
201 ,@fs-options))))
202
203(define* (make-unformatted-image partition target)
204 "Make an unformatted partition of a certain size."
205 (let ((size (partition-size partition)))
206 ;; Create the file and then truncate it to the desired size.
207 (with-output-to-file target
208 (lambda _ (display "")))
209 (truncate-file target size)))
210
211(define* (make-partition-image partition-sexp target root)
212 "Create and return the image of PARTITION-SEXP as TARGET. Use the given
213ROOT directory to populate the image."
214 (let* ((partition (sexp->partition partition-sexp))
215 (type (partition-file-system partition)))
216 (cond
217 ((string=? "btrfs" type)
218 (make-btrfs-image partition target root))
219 ((string-prefix? "ext" type)
220 (make-ext-image partition target root))
221 ((string=? "f2fs" type)
222 (make-f2fs-image partition target root))
223 ((or (string=? type "vfat") (string=? type "fat16"))
224 (make-vfat-image partition target root 16))
225 ((string=? type "fat32")
226 (make-vfat-image partition target root 32))
227 ((string=? "swap" type)
228 (make-swap-image partition target))
229 ((string=? type "unformatted")
230 (make-unformatted-image partition target))
231 (else
232 (raise (condition
233 (&message
234 (message "unsupported partition type"))))))))
235
236(define (convert-disk-image image format output)
237 "Convert IMAGE to OUTPUT according to the given FORMAT."
238 (case format
239 ((compressed-qcow2)
240 (invoke "qemu-img" "convert" "-c" "-f" "raw"
241 ;; The maximum number of co-routines is 16.
242 "-m" (number->string (min 16 (parallel-job-count)))
243 "-O" "qcow2"
244 "-o" "compression_type=zstd"
245 image output))
246 (else
247 (copy-file image output))))
248
249(define* (genimage config)
250 "Use genimage to generate in TARGET directory, the image described in the
251given CONFIG file."
252 ;; genimage needs a 'root' directory.
253 (mkdir "root")
254 (invoke "genimage" "--config" config))
255
256(define* (register-closure prefix closure
257 #:key
258 (schema (sql-schema))
259 (wal-mode? #t))
260 "Register CLOSURE in PREFIX, where PREFIX is the directory name of the
261target store and CLOSURE is the name of a file containing a reference graph as
262produced by #:references-graphs. Pass WAL-MODE? to call-with-database."
263 (let ((items (call-with-input-file closure read-reference-graph)))
264 (parameterize ((sql-schema schema))
265 (with-database (store-database-file #:prefix prefix) db
266 #:wal-mode? wal-mode?
267 (register-items db items
268 #:prefix prefix
269 #:registration-time %epoch)))))
270
271(define* (initialize-efi-partition root
272 #:key
273 grub-efi
274 #:allow-other-keys)
275 "Install in ROOT directory, an EFI loader using GRUB-EFI."
276 (install-efi-loader grub-efi root))
277
278(define* (initialize-efi32-partition root
279 #:key
280 grub-efi32
281 #:allow-other-keys)
282 "Install in ROOT directory, an EFI 32bit loader using GRUB-EFI32."
283 (install-efi-loader grub-efi32 root
284 #:targets (cond ((target-x86?)
285 '("i386-efi" . "BOOTIA32.EFI"))
286 ((target-arm?)
287 '("arm-efi" . "BOOTARM.EFI")))))
288
289(define* (initialize-root-partition root
290 #:key
291 bootcfg
292 bootcfg-location
293 bootloader-package
294 bootloader-installer
295 (copy-closures? #t)
296 (deduplicate? #t)
297 references-graphs
298 (register-closures? #t)
299 system-directory
300 make-device-nodes
301 (wal-mode? #t)
302 #:allow-other-keys)
303 "Initialize the given ROOT directory. Use BOOTCFG and BOOTCFG-LOCATION to
304install the bootloader configuration.
305
306If COPY-CLOSURES? is true, copy all of REFERENCES-GRAPHS to the partition. If
307REGISTER-CLOSURES? is true, register REFERENCES-GRAPHS in the store. If
308DEDUPLICATE? is true, then also deduplicate files common to CLOSURES and the
309rest of the store when registering the closures. SYSTEM-DIRECTORY is the name
310of the directory of the 'system' derivation. Pass WAL-MODE? to
311register-closure."
312 (define root-store
313 (string-append root (%store-directory)))
314
315 (define tmp-store ".tmp-store")
316
317 (populate-root-file-system system-directory root)
318
319 (when copy-closures?
320 (populate-store references-graphs root
321 #:deduplicate? deduplicate?))
322
323 ;; Populate /dev.
324 (when make-device-nodes
325 (make-device-nodes #:root root))
326
327 (when register-closures?
328 (unless copy-closures?
329 ;; XXX: 'register-closure' wants to palpate the things it registers, so
330 ;; create a symlink to the store.
331 (rename-file root-store tmp-store)
332 (symlink (%store-directory) root-store))
333
334 (for-each (lambda (closure)
335 (register-closure root closure
336 #:wal-mode? wal-mode?))
337 references-graphs)
338
339 (unless copy-closures?
340 (delete-file root-store)
341 (rename-file tmp-store root-store)))
342
343 ;; There's no point installing a bootloader if we do not populate the store.
344 (when copy-closures?
345 (when bootloader-installer
346 (display "installing bootloader...\n")
347 (bootloader-installer bootloader-package #f root))
348 (when bootcfg
349 (install-boot-config bootcfg bootcfg-location root))))
350
351(define* (make-iso9660-image xorriso grub-mkrescue-environment
352 grub bootcfg system-directory root target
353 #:key (volume-id "Guix_image") (volume-uuid #f)
354 register-closures? (references-graphs '())
355 (compression? #t))
356 "Given a GRUB package, creates an iso image as TARGET, using BOOTCFG as
357GRUB configuration and OS-DRV as the stuff in it."
358 (define grub-mkrescue
359 (string-append grub "/bin/grub-mkrescue"))
360
361 (define grub-mkrescue-sed.sh
362 (string-append (getcwd) "/" "grub-mkrescue-sed.sh"))
363
364 ;; Use a modified version of grub-mkrescue-sed.sh, see below.
365 (copy-file (string-append xorriso
366 "/bin/grub-mkrescue-sed.sh")
367 grub-mkrescue-sed.sh)
368
369 ;; Force grub-mkrescue-sed.sh to use the build directory instead of /tmp
370 ;; that is read-only inside the build container.
371 (substitute* grub-mkrescue-sed.sh
372 (("/tmp/") (string-append (getcwd) "/"))
373 (("MKRESCUE_SED_XORRISO_ARGS \\$x")
374 (format #f "MKRESCUE_SED_XORRISO_ARGS $(echo $x | sed \"s|/tmp|~a|\")"
375 (getcwd))))
376
377 ;; 'grub-mkrescue' calls out to mtools programs to create 'efi.img', a FAT
378 ;; file system image, and mtools honors SOURCE_DATE_EPOCH for the mtime of
379 ;; those files. The epoch for FAT is Jan. 1st 1980, not 1970, so choose
380 ;; that.
381 (setenv "SOURCE_DATE_EPOCH"
382 (number->string
383 (time-second
384 (date->time-utc (make-date 0 0 0 0 1 1 1980 0)))))
385
386 ;; Our patched 'grub-mkrescue' honors this environment variable and passes
387 ;; it to 'mformat', which makes it the serial number of 'efi.img'. This
388 ;; allows for deterministic builds.
389 (setenv "GRUB_FAT_SERIAL_NUMBER"
390 (number->string (if volume-uuid
391
392 ;; On 32-bit systems the 2nd argument must be
393 ;; lower than 2^32.
394 (string-hash (iso9660-uuid->string volume-uuid)
395 (- (expt 2 32) 1))
396
397 #x77777777)
398 16))
399
400 (setenv "MKRESCUE_SED_MODE" "original")
401 (setenv "MKRESCUE_SED_XORRISO" (string-append xorriso "/bin/xorriso"))
402 (setenv "MKRESCUE_SED_IN_EFI_NO_PT" "yes")
403
404 (for-each (match-lambda
405 ((name . value) (setenv name value)))
406 grub-mkrescue-environment)
407
408 (apply invoke grub-mkrescue
409 (string-append "--xorriso=" grub-mkrescue-sed.sh)
410 "-o" target
411 (string-append "boot/grub/grub.cfg=" bootcfg)
412 root
413 "--"
414 ;; Set all timestamps to 1.
415 "-volume_date" "all_file_dates" "=1"
416
417 `(,@(if compression?
418 '(;; ‘zisofs’ compression reduces the total image size by ~60%.
419 "-zisofs" "level=9:block_size=128k" ; highest compression
420 ;; It's transparent to our Linux-Libre kernel but not to
421 ;; GRUB. Don't compress the kernel, initrd, and other files
422 ;; read by grub.cfg, as well as common already-compressed
423 ;; file names.
424 "-find" "/" "-type" "f"
425 ;; XXX Even after "--" above, and despite documentation
426 ;; claiming otherwise, "-or" is stolen by grub-mkrescue which
427 ;; then chokes on it (as ‘-o …’) and dies. Don't use "-or".
428 "-not" "-wholename" "/boot/*"
429 "-not" "-wholename" "/System/*"
430 "-not" "-name" "unicode.pf2"
431 "-not" "-name" "bzImage"
432 "-not" "-name" "zImage"
433 "-not" "-name" "Image"
434 "-not" "-name" "vmlinuz"
435 "-not" "-name" "*.gz" ; initrd
436 "-not" "-name" "*.zst" ; all man pages
437 "-not" "-name" "*.png" ; includes grub-image.png
438 "-exec" "set_filter" "--zisofs"
439 "--")
440 '())
441 "-volid" ,(string-upcase volume-id)
442 ,@(if volume-uuid
443 `("-volume_date" "uuid"
444 ,(string-filter (lambda (value)
445 (not (char=? #\- value)))
446 (iso9660-uuid->string
447 volume-uuid)))
448 '()))))