2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "make_ext4fs.h"
18 #include "ext4_utils.h"
23 #include <sparse/sparse.h>
35 #include <sys/types.h>
41 /* These match the Linux definitions of these flags.
42 L_xx is defined to avoid conflicting with the win32 versions.
44 #define L_S_IRUSR 00400
45 #define L_S_IWUSR 00200
46 #define L_S_IXUSR 00100
47 #define S_IRWXU (L_S_IRUSR | L_S_IWUSR | L_S_IXUSR)
51 #define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
55 #define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH)
56 #define S_ISUID 0004000
57 #define S_ISGID 0002000
58 #define S_ISVTX 0001000
62 #include <selinux/selinux.h>
63 #include <selinux/label.h>
69 /* TODO: Not implemented:
70 Allocating blocks in the same block group as the file inode
71 Hash or binary tree directories
72 Special files: sockets, devices, fifos
75 static int filter_dot(const struct dirent *d)
77 return (strcmp(d->d_name, "..") && strcmp(d->d_name, "."));
80 static u32 build_default_directory_structure(const char *dir_path,
81 struct selabel_handle *sehnd)
85 struct dentry dentries = {
86 .filename = "lost+found",
87 .file_type = EXT4_FT_DIR,
93 root_inode = make_directory(0, 1, &dentries, 1);
94 inode = make_directory(root_inode, 0, NULL, 0);
95 *dentries.inode = inode;
96 inode_set_permissions(inode, dentries.mode,
97 dentries.uid, dentries.gid, dentries.mtime);
102 char *secontext = NULL;
104 asprintf(&path, "%slost+found", dir_path);
105 if (selabel_lookup(sehnd, &secontext, path, S_IFDIR) < 0) {
106 error("cannot lookup security context for %s", path);
108 inode_set_selinux(inode, secontext);
119 /* Read a local directory and create the same tree in the generated filesystem.
120 Calls itself recursively with each directory in the given directory.
121 full_path is an absolute or relative path, with a trailing slash, to the
122 directory on disk that should be copied, or NULL if this is a directory
123 that does not exist on disk (e.g. lost+found).
124 dir_path is an absolute path, with trailing slash, to the same directory
125 if the image were mounted at the specified mount point */
126 static u32 build_directory_structure(const char *full_path, const char *dir_path, const char *target_out_path,
127 u32 dir_inode, fs_config_func_t fs_config_func,
128 struct selabel_handle *sehnd, int verbose, time_t fixed_time)
131 struct dentry *dentries;
132 struct dirent **namelist = NULL;
139 bool needs_lost_and_found = false;
142 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
145 /* The scandir function implemented in glibc has a bug that makes it
146 erroneously fail with ENOMEM under certain circumstances.
147 As a workaround we can retry the scandir call with the same arguments.
148 GLIBC BZ: https://sourceware.org/bugzilla/show_bug.cgi?id=17804 */
150 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
153 error_errno("scandir");
154 return EXT4_ALLOCATE_FAILED;
159 if (dir_inode == 0) {
160 /* root directory, check if lost+found already exists */
161 for (i = 0; i < entries; i++)
162 if (strcmp(namelist[i]->d_name, "lost+found") == 0)
165 needs_lost_and_found = true;
168 dentries = calloc(entries, sizeof(struct dentry));
169 if (dentries == NULL)
170 critical_error_errno("malloc");
172 for (i = 0; i < entries; i++) {
173 dentries[i].filename = strdup(namelist[i]->d_name);
174 if (dentries[i].filename == NULL)
175 critical_error_errno("strdup");
177 asprintf(&dentries[i].path, "%s%s", dir_path, namelist[i]->d_name);
178 asprintf(&dentries[i].full_path, "%s%s", full_path, namelist[i]->d_name);
182 ret = lstat(dentries[i].full_path, &stat);
184 error_errno("lstat");
190 dentries[i].size = stat.st_size;
191 dentries[i].mode = stat.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
192 if (fixed_time == -1) {
193 dentries[i].mtime = stat.st_mtime;
195 dentries[i].mtime = fixed_time;
197 uint64_t capabilities;
198 if (fs_config_func != NULL) {
200 unsigned int mode = 0;
201 unsigned int uid = 0;
202 unsigned int gid = 0;
203 int dir = S_ISDIR(stat.st_mode);
204 fs_config_func(dentries[i].path, dir, target_out_path, &uid, &gid, &mode, &capabilities);
205 dentries[i].mode = mode;
206 dentries[i].uid = uid;
207 dentries[i].gid = gid;
208 dentries[i].capabilities = capabilities;
210 error("can't set android permissions - built without android support");
215 if (selabel_lookup(sehnd, &dentries[i].secon, dentries[i].path, stat.st_mode) < 0) {
216 error("cannot lookup security context for %s", dentries[i].path);
219 if (dentries[i].secon && verbose)
220 printf("Labeling %s as %s\n", dentries[i].path, dentries[i].secon);
224 if (S_ISREG(stat.st_mode)) {
225 dentries[i].file_type = EXT4_FT_REG_FILE;
226 } else if (S_ISDIR(stat.st_mode)) {
227 dentries[i].file_type = EXT4_FT_DIR;
229 } else if (S_ISCHR(stat.st_mode)) {
230 dentries[i].file_type = EXT4_FT_CHRDEV;
231 } else if (S_ISBLK(stat.st_mode)) {
232 dentries[i].file_type = EXT4_FT_BLKDEV;
233 } else if (S_ISFIFO(stat.st_mode)) {
234 dentries[i].file_type = EXT4_FT_FIFO;
235 } else if (S_ISSOCK(stat.st_mode)) {
236 dentries[i].file_type = EXT4_FT_SOCK;
237 } else if (S_ISLNK(stat.st_mode)) {
238 dentries[i].file_type = EXT4_FT_SYMLINK;
239 dentries[i].link = calloc(info.block_size, 1);
240 readlink(dentries[i].full_path, dentries[i].link, info.block_size - 1);
242 error("unknown file type on %s", dentries[i].path);
249 if (needs_lost_and_found) {
250 /* insert a lost+found directory at the beginning of the dentries */
251 struct dentry *tmp = calloc(entries + 1, sizeof(struct dentry));
252 memset(tmp, 0, sizeof(struct dentry));
253 memcpy(tmp + 1, dentries, entries * sizeof(struct dentry));
256 dentries[0].filename = strdup("lost+found");
257 asprintf(&dentries[0].path, "%slost+found", dir_path);
258 dentries[0].full_path = NULL;
259 dentries[0].size = 0;
260 dentries[0].mode = S_IRWXU;
261 dentries[0].file_type = EXT4_FT_DIR;
265 if (selabel_lookup(sehnd, &dentries[0].secon, dentries[0].path, dentries[0].mode) < 0)
266 error("cannot lookup security context for %s", dentries[0].path);
272 inode = make_directory(dir_inode, entries, dentries, dirs);
274 for (i = 0; i < entries; i++) {
275 if (dentries[i].file_type == EXT4_FT_REG_FILE) {
276 entry_inode = make_file(dentries[i].full_path, dentries[i].size);
277 } else if (dentries[i].file_type == EXT4_FT_DIR) {
278 char *subdir_full_path = NULL;
279 char *subdir_dir_path;
280 if (dentries[i].full_path) {
281 ret = asprintf(&subdir_full_path, "%s/", dentries[i].full_path);
283 critical_error_errno("asprintf");
285 ret = asprintf(&subdir_dir_path, "%s/", dentries[i].path);
287 critical_error_errno("asprintf");
288 entry_inode = build_directory_structure(subdir_full_path, subdir_dir_path, target_out_path,
289 inode, fs_config_func, sehnd, verbose, fixed_time);
290 free(subdir_full_path);
291 free(subdir_dir_path);
292 } else if (dentries[i].file_type == EXT4_FT_SYMLINK) {
293 entry_inode = make_link(dentries[i].link);
295 error("unknown file type on %s", dentries[i].path);
298 *dentries[i].inode = entry_inode;
300 ret = inode_set_permissions(entry_inode, dentries[i].mode,
301 dentries[i].uid, dentries[i].gid,
304 error("failed to set permissions on %s\n", dentries[i].path);
307 * It's important to call inode_set_selinux() before
308 * inode_set_capabilities(). Extended attributes need to
309 * be stored sorted order, and we guarantee this by making
310 * the calls in the proper order.
311 * Please see xattr_assert_sane() in contents.c
313 ret = inode_set_selinux(entry_inode, dentries[i].secon);
315 error("failed to set SELinux context on %s\n", dentries[i].path);
316 ret = inode_set_capabilities(entry_inode, dentries[i].capabilities);
318 error("failed to set capability on %s\n", dentries[i].path);
320 free(dentries[i].path);
321 free(dentries[i].full_path);
322 free(dentries[i].link);
323 free((void *)dentries[i].filename);
324 free(dentries[i].secon);
332 static u32 compute_block_size()
337 static u32 compute_journal_blocks()
339 u32 journal_blocks = DIV_ROUND_UP(info.len, info.block_size) / 64;
340 if (journal_blocks < 1024)
341 journal_blocks = 1024;
342 if (journal_blocks > 32768)
343 journal_blocks = 32768;
344 return journal_blocks;
347 static u32 compute_blocks_per_group()
349 return info.block_size * 8;
352 static u32 compute_inodes()
354 return DIV_ROUND_UP(info.len, info.block_size) / 4;
357 static u32 compute_inodes_per_group()
359 u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
360 u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
361 u32 inodes = DIV_ROUND_UP(info.inodes, block_groups);
362 inodes = EXT4_ALIGN(inodes, (info.block_size / info.inode_size));
364 /* After properly rounding up the number of inodes/group,
365 * make sure to update the total inodes field in the info struct.
367 info.inodes = inodes * block_groups;
372 static u32 compute_bg_desc_reserve_blocks()
374 u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
375 u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
376 u32 bg_desc_blocks = DIV_ROUND_UP(block_groups * sizeof(struct ext2_group_desc),
379 u32 bg_desc_reserve_blocks =
380 DIV_ROUND_UP(block_groups * 1024 * sizeof(struct ext2_group_desc),
381 info.block_size) - bg_desc_blocks;
383 if (bg_desc_reserve_blocks > info.block_size / sizeof(u32))
384 bg_desc_reserve_blocks = info.block_size / sizeof(u32);
386 return bg_desc_reserve_blocks;
389 void reset_ext4fs_info() {
390 // Reset all the global data structures used by make_ext4fs so it
391 // can be called again.
392 memset(&info, 0, sizeof(info));
393 memset(&aux_info, 0, sizeof(aux_info));
395 if (ext4_sparse_file) {
396 sparse_file_destroy(ext4_sparse_file);
397 ext4_sparse_file = NULL;
401 int make_ext4fs_sparse_fd(int fd, long long len,
402 const char *mountpoint, struct selabel_handle *sehnd)
404 return make_ext4fs_sparse_fd_directory(fd, len, mountpoint, sehnd, NULL);
407 int make_ext4fs_sparse_fd_directory(int fd, long long len,
408 const char *mountpoint, struct selabel_handle *sehnd,
409 const char *directory)
414 return make_ext4fs_internal(fd, directory, NULL, mountpoint, NULL,
419 int make_ext4fs(const char *filename, long long len,
420 const char *mountpoint, struct selabel_handle *sehnd)
422 return make_ext4fs_directory(filename, len, mountpoint, sehnd, NULL);
425 int make_ext4fs_directory(const char *filename, long long len,
426 const char *mountpoint, struct selabel_handle *sehnd,
427 const char *directory)
435 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
441 status = make_ext4fs_internal(fd, directory, NULL, mountpoint, NULL,
449 /* return a newly-malloc'd string that is a copy of str. The new string
450 is guaranteed to have a trailing slash. If absolute is true, the new string
451 is also guaranteed to have a leading slash.
453 static char *canonicalize_slashes(const char *str, bool absolute)
456 int len = strlen(str);
467 if (str[0] != '/' && absolute) {
470 if (str[len - 1] != '/') {
473 ret = malloc(newlen + 1);
475 critical_error("malloc");
479 if (str[0] != '/' && absolute) {
486 if (str[len - 1] != '/') {
490 if (ptr != ret + newlen) {
491 critical_error("assertion failed\n");
499 static char *canonicalize_abs_slashes(const char *str)
501 return canonicalize_slashes(str, true);
504 static char *canonicalize_rel_slashes(const char *str)
506 return canonicalize_slashes(str, false);
509 int make_ext4fs_internal(int fd, const char *_directory, const char *_target_out_directory,
510 const char *_mountpoint, fs_config_func_t fs_config_func, int gzip,
511 int sparse, int crc, int wipe, int real_uuid,
512 struct selabel_handle *sehnd, int verbose, time_t fixed_time,
513 FILE* block_list_file)
518 char *directory = NULL;
519 char *target_out_directory = NULL;
521 if (setjmp(setjmp_env))
522 return EXIT_FAILURE; /* Handle a call to longjmp() */
524 info.block_device = is_block_device_fd(fd);
526 if (info.block_device && (sparse || gzip || crc)) {
527 fprintf(stderr, "No sparse/gzip/crc allowed for block device\n");
531 if (_mountpoint == NULL) {
532 mountpoint = strdup("");
534 mountpoint = canonicalize_abs_slashes(_mountpoint);
538 directory = canonicalize_rel_slashes(_directory);
541 if (_target_out_directory) {
542 target_out_directory = canonicalize_rel_slashes(_target_out_directory);
546 info.len = get_file_size(fd);
549 fprintf(stderr, "Need size of filesystem\n");
553 if (info.block_size <= 0)
554 info.block_size = compute_block_size();
556 /* Round down the filesystem length to be a multiple of the block size */
557 info.len &= ~((u64)info.block_size - 1);
559 if (info.journal_blocks == 0)
560 info.journal_blocks = compute_journal_blocks();
562 if (info.no_journal == 0)
563 info.feat_compat = EXT4_FEATURE_COMPAT_HAS_JOURNAL;
565 info.journal_blocks = 0;
567 if (info.blocks_per_group <= 0)
568 info.blocks_per_group = compute_blocks_per_group();
570 if (info.inodes <= 0)
571 info.inodes = compute_inodes();
573 if (info.inode_size <= 0)
574 info.inode_size = 256;
576 if (info.label == NULL)
579 info.inodes_per_group = compute_inodes_per_group();
582 EXT4_FEATURE_COMPAT_RESIZE_INODE |
583 EXT4_FEATURE_COMPAT_EXT_ATTR;
585 info.feat_ro_compat |=
586 EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER |
587 EXT4_FEATURE_RO_COMPAT_LARGE_FILE;
589 info.feat_incompat |=
590 EXT4_FEATURE_INCOMPAT_EXTENTS |
591 EXT4_FEATURE_INCOMPAT_FILETYPE;
594 info.bg_desc_reserve_blocks = compute_bg_desc_reserve_blocks();
596 printf("Creating filesystem with parameters:\n");
597 printf(" Size: %"PRIu64"\n", info.len);
598 printf(" Block size: %d\n", info.block_size);
599 printf(" Blocks per group: %d\n", info.blocks_per_group);
600 printf(" Inodes per group: %d\n", info.inodes_per_group);
601 printf(" Inode size: %d\n", info.inode_size);
602 printf(" Journal blocks: %d\n", info.journal_blocks);
603 printf(" Label: %s\n", info.label);
605 ext4_create_fs_aux_info();
607 printf(" Blocks: %"PRIu64"\n", aux_info.len_blocks);
608 printf(" Block groups: %d\n", aux_info.groups);
609 printf(" Reserved block group size: %d\n", info.bg_desc_reserve_blocks);
611 ext4_sparse_file = sparse_file_new(info.block_size, info.len);
613 block_allocator_init();
615 ext4_fill_in_sb(real_uuid);
617 if (reserve_inodes(0, 10) == EXT4_ALLOCATE_FAILED)
618 error("failed to reserve first 10 inodes");
620 if (info.feat_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
621 ext4_create_journal_inode();
623 if (info.feat_compat & EXT4_FEATURE_COMPAT_RESIZE_INODE)
624 ext4_create_resize_inode();
627 // Windows needs only 'create an empty fs image' functionality
629 root_inode_num = build_default_directory_structure(mountpoint, sehnd);
632 root_inode_num = build_directory_structure(directory, mountpoint, target_out_directory, 0,
633 fs_config_func, sehnd, verbose, fixed_time);
635 root_inode_num = build_default_directory_structure(mountpoint, sehnd);
638 root_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
639 inode_set_permissions(root_inode_num, root_mode, 0, 0, 0);
643 char *secontext = NULL;
645 if (selabel_lookup(sehnd, &secontext, mountpoint, S_IFDIR) < 0) {
646 error("cannot lookup security context for %s", mountpoint);
650 printf("Labeling %s as %s\n", mountpoint, secontext);
652 inode_set_selinux(root_inode_num, secontext);
660 if (block_list_file) {
661 size_t dirlen = directory ? strlen(directory) : 0;
662 struct block_allocation* p = get_saved_allocation_chain();
664 if (directory && strncmp(p->filename, directory, dirlen) == 0) {
665 // substitute mountpoint for the leading directory in the filename, in the output file
666 fprintf(block_list_file, "%s%s", mountpoint, p->filename + dirlen);
668 fprintf(block_list_file, "%s", p->filename);
670 print_blocks(block_list_file, p);
671 struct block_allocation* pn = p->next;
677 printf("Created filesystem with %d/%d inodes and %d/%d blocks\n",
678 aux_info.sb->s_inodes_count - aux_info.sb->s_free_inodes_count,
679 aux_info.sb->s_inodes_count,
680 aux_info.sb->s_blocks_count_lo - aux_info.sb->s_free_blocks_count_lo,
681 aux_info.sb->s_blocks_count_lo);
683 if (wipe && WIPE_IS_SUPPORTED) {
684 wipe_block_device(fd, info.len);
687 write_ext4_image(fd, gzip, sparse, crc);
689 sparse_file_destroy(ext4_sparse_file);
690 ext4_sparse_file = NULL;