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"
24 #include <sparse/sparse.h>
36 #include <sys/types.h>
42 /* These match the Linux definitions of these flags.
43 L_xx is defined to avoid conflicting with the win32 versions.
45 #define L_S_IRUSR 00400
46 #define L_S_IWUSR 00200
47 #define L_S_IXUSR 00100
48 #define S_IRWXU (L_S_IRUSR | L_S_IWUSR | L_S_IXUSR)
52 #define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP)
56 #define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH)
57 #define S_ISUID 0004000
58 #define S_ISGID 0002000
59 #define S_ISVTX 0001000
63 #include <selinux/selinux.h>
64 #include <selinux/label.h>
65 #include <selinux/android.h>
71 /* TODO: Not implemented:
72 Allocating blocks in the same block group as the file inode
73 Hash or binary tree directories
74 Special files: sockets, devices, fifos
77 static int filter_dot(const struct dirent *d)
79 return (strcmp(d->d_name, "..") && strcmp(d->d_name, "."));
82 static u32 build_default_directory_structure(const char *dir_path,
83 struct selabel_handle *sehnd)
87 struct dentry dentries = {
88 .filename = "lost+found",
89 .file_type = EXT4_FT_DIR,
95 root_inode = make_directory(0, 1, &dentries, 1);
96 inode = make_directory(root_inode, 0, NULL, 0);
97 *dentries.inode = inode;
98 inode_set_permissions(inode, dentries.mode,
99 dentries.uid, dentries.gid, dentries.mtime);
104 char *secontext = NULL;
106 asprintf(&path, "%slost+found", dir_path);
107 if (selabel_lookup(sehnd, &secontext, path, S_IFDIR) < 0) {
108 error("cannot lookup security context for %s", path);
110 inode_set_selinux(inode, secontext);
121 /* Read a local directory and create the same tree in the generated filesystem.
122 Calls itself recursively with each directory in the given directory.
123 full_path is an absolute or relative path, with a trailing slash, to the
124 directory on disk that should be copied, or NULL if this is a directory
125 that does not exist on disk (e.g. lost+found).
126 dir_path is an absolute path, with trailing slash, to the same directory
127 if the image were mounted at the specified mount point */
128 static u32 build_directory_structure(const char *full_path, const char *dir_path,
129 u32 dir_inode, fs_config_func_t fs_config_func,
130 struct selabel_handle *sehnd, int verbose, time_t fixed_time)
133 struct dentry *dentries;
134 struct dirent **namelist = NULL;
141 bool needs_lost_and_found = false;
144 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
147 /* The scandir function implemented in glibc has a bug that makes it
148 erroneously fail with ENOMEM under certain circumstances.
149 As a workaround we can retry the scandir call with the same arguments.
150 GLIBC BZ: https://sourceware.org/bugzilla/show_bug.cgi?id=17804 */
152 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
155 error_errno("scandir");
156 return EXT4_ALLOCATE_FAILED;
161 if (dir_inode == 0) {
162 /* root directory, check if lost+found already exists */
163 for (i = 0; i < entries; i++)
164 if (strcmp(namelist[i]->d_name, "lost+found") == 0)
167 needs_lost_and_found = true;
170 dentries = calloc(entries, sizeof(struct dentry));
171 if (dentries == NULL)
172 critical_error_errno("malloc");
174 for (i = 0; i < entries; i++) {
175 dentries[i].filename = strdup(namelist[i]->d_name);
176 if (dentries[i].filename == NULL)
177 critical_error_errno("strdup");
179 asprintf(&dentries[i].path, "%s%s", dir_path, namelist[i]->d_name);
180 asprintf(&dentries[i].full_path, "%s%s", full_path, namelist[i]->d_name);
184 ret = lstat(dentries[i].full_path, &stat);
186 error_errno("lstat");
192 dentries[i].size = stat.st_size;
193 dentries[i].mode = stat.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
194 if (fixed_time == -1) {
195 dentries[i].mtime = stat.st_mtime;
197 dentries[i].mtime = fixed_time;
199 uint64_t capabilities;
200 if (fs_config_func != NULL) {
202 unsigned int mode = 0;
203 unsigned int uid = 0;
204 unsigned int gid = 0;
205 int dir = S_ISDIR(stat.st_mode);
206 fs_config_func(dentries[i].path, dir, &uid, &gid, &mode, &capabilities);
207 dentries[i].mode = mode;
208 dentries[i].uid = uid;
209 dentries[i].gid = gid;
210 dentries[i].capabilities = capabilities;
212 error("can't set android permissions - built without android support");
217 if (selabel_lookup(sehnd, &dentries[i].secon, dentries[i].path, stat.st_mode) < 0) {
218 error("cannot lookup security context for %s", dentries[i].path);
221 if (dentries[i].secon && verbose)
222 printf("Labeling %s as %s\n", dentries[i].path, dentries[i].secon);
226 if (S_ISREG(stat.st_mode)) {
227 dentries[i].file_type = EXT4_FT_REG_FILE;
228 } else if (S_ISDIR(stat.st_mode)) {
229 dentries[i].file_type = EXT4_FT_DIR;
231 } else if (S_ISCHR(stat.st_mode)) {
232 dentries[i].file_type = EXT4_FT_CHRDEV;
233 } else if (S_ISBLK(stat.st_mode)) {
234 dentries[i].file_type = EXT4_FT_BLKDEV;
235 } else if (S_ISFIFO(stat.st_mode)) {
236 dentries[i].file_type = EXT4_FT_FIFO;
237 } else if (S_ISSOCK(stat.st_mode)) {
238 dentries[i].file_type = EXT4_FT_SOCK;
239 } else if (S_ISLNK(stat.st_mode)) {
240 dentries[i].file_type = EXT4_FT_SYMLINK;
241 dentries[i].link = calloc(info.block_size, 1);
242 readlink(dentries[i].full_path, dentries[i].link, info.block_size - 1);
244 error("unknown file type on %s", dentries[i].path);
251 if (needs_lost_and_found) {
252 /* insert a lost+found directory at the beginning of the dentries */
253 struct dentry *tmp = calloc(entries + 1, sizeof(struct dentry));
254 memset(tmp, 0, sizeof(struct dentry));
255 memcpy(tmp + 1, dentries, entries * sizeof(struct dentry));
258 dentries[0].filename = strdup("lost+found");
259 asprintf(&dentries[0].path, "%slost+found", dir_path);
260 dentries[0].full_path = NULL;
261 dentries[0].size = 0;
262 dentries[0].mode = S_IRWXU;
263 dentries[0].file_type = EXT4_FT_DIR;
267 if (selabel_lookup(sehnd, &dentries[0].secon, dentries[0].path, dentries[0].mode) < 0)
268 error("cannot lookup security context for %s", dentries[0].path);
274 inode = make_directory(dir_inode, entries, dentries, dirs);
276 for (i = 0; i < entries; i++) {
277 if (dentries[i].file_type == EXT4_FT_REG_FILE) {
278 entry_inode = make_file(dentries[i].full_path, dentries[i].size);
279 } else if (dentries[i].file_type == EXT4_FT_DIR) {
280 char *subdir_full_path = NULL;
281 char *subdir_dir_path;
282 if (dentries[i].full_path) {
283 ret = asprintf(&subdir_full_path, "%s/", dentries[i].full_path);
285 critical_error_errno("asprintf");
287 ret = asprintf(&subdir_dir_path, "%s/", dentries[i].path);
289 critical_error_errno("asprintf");
290 entry_inode = build_directory_structure(subdir_full_path,
291 subdir_dir_path, inode, fs_config_func, sehnd, verbose, fixed_time);
292 free(subdir_full_path);
293 free(subdir_dir_path);
294 } else if (dentries[i].file_type == EXT4_FT_SYMLINK) {
295 entry_inode = make_link(dentries[i].link);
297 error("unknown file type on %s", dentries[i].path);
300 *dentries[i].inode = entry_inode;
302 ret = inode_set_permissions(entry_inode, dentries[i].mode,
303 dentries[i].uid, dentries[i].gid,
306 error("failed to set permissions on %s\n", dentries[i].path);
309 * It's important to call inode_set_selinux() before
310 * inode_set_capabilities(). Extended attributes need to
311 * be stored sorted order, and we guarantee this by making
312 * the calls in the proper order.
313 * Please see xattr_assert_sane() in contents.c
315 ret = inode_set_selinux(entry_inode, dentries[i].secon);
317 error("failed to set SELinux context on %s\n", dentries[i].path);
318 ret = inode_set_capabilities(entry_inode, dentries[i].capabilities);
320 error("failed to set capability on %s\n", dentries[i].path);
322 free(dentries[i].path);
323 free(dentries[i].full_path);
324 free(dentries[i].link);
325 free((void *)dentries[i].filename);
326 free(dentries[i].secon);
334 static u32 compute_block_size()
339 static u32 compute_journal_blocks()
341 u32 journal_blocks = DIV_ROUND_UP(info.len, info.block_size) / 64;
342 if (journal_blocks < 1024)
343 journal_blocks = 1024;
344 if (journal_blocks > 32768)
345 journal_blocks = 32768;
346 return journal_blocks;
349 static u32 compute_blocks_per_group()
351 return info.block_size * 8;
354 static u32 compute_inodes()
356 return DIV_ROUND_UP(info.len, info.block_size) / 4;
359 static u32 compute_inodes_per_group()
361 u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
362 u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
363 u32 inodes = DIV_ROUND_UP(info.inodes, block_groups);
364 inodes = EXT4_ALIGN(inodes, (info.block_size / info.inode_size));
366 /* After properly rounding up the number of inodes/group,
367 * make sure to update the total inodes field in the info struct.
369 info.inodes = inodes * block_groups;
374 static u32 compute_bg_desc_reserve_blocks()
376 u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
377 u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
378 u32 bg_desc_blocks = DIV_ROUND_UP(block_groups * sizeof(struct ext2_group_desc),
381 u32 bg_desc_reserve_blocks =
382 DIV_ROUND_UP(block_groups * 1024 * sizeof(struct ext2_group_desc),
383 info.block_size) - bg_desc_blocks;
385 if (bg_desc_reserve_blocks > info.block_size / sizeof(u32))
386 bg_desc_reserve_blocks = info.block_size / sizeof(u32);
388 return bg_desc_reserve_blocks;
391 void reset_ext4fs_info() {
392 // Reset all the global data structures used by make_ext4fs so it
393 // can be called again.
394 memset(&info, 0, sizeof(info));
395 memset(&aux_info, 0, sizeof(aux_info));
397 if (ext4_sparse_file) {
398 sparse_file_destroy(ext4_sparse_file);
399 ext4_sparse_file = NULL;
403 int make_ext4fs_sparse_fd(int fd, long long len,
404 const char *mountpoint, struct selabel_handle *sehnd)
409 return make_ext4fs_internal(fd, NULL, mountpoint, NULL, 0, 1, 0, 0, sehnd, 0, -1, NULL);
412 int make_ext4fs(const char *filename, long long len,
413 const char *mountpoint, struct selabel_handle *sehnd)
421 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
427 status = make_ext4fs_internal(fd, NULL, mountpoint, NULL, 0, 0, 0, 1, sehnd, 0, -1, NULL);
433 /* return a newly-malloc'd string that is a copy of str. The new string
434 is guaranteed to have a trailing slash. If absolute is true, the new string
435 is also guaranteed to have a leading slash.
437 static char *canonicalize_slashes(const char *str, bool absolute)
440 int len = strlen(str);
451 if (str[0] != '/' && absolute) {
454 if (str[len - 1] != '/') {
457 ret = malloc(newlen + 1);
459 critical_error("malloc");
463 if (str[0] != '/' && absolute) {
470 if (str[len - 1] != '/') {
474 if (ptr != ret + newlen) {
475 critical_error("assertion failed\n");
483 static char *canonicalize_abs_slashes(const char *str)
485 return canonicalize_slashes(str, true);
488 static char *canonicalize_rel_slashes(const char *str)
490 return canonicalize_slashes(str, false);
493 int make_ext4fs_internal(int fd, const char *_directory,
494 const char *_mountpoint, fs_config_func_t fs_config_func, int gzip,
495 int sparse, int crc, int wipe,
496 struct selabel_handle *sehnd, int verbose, time_t fixed_time,
497 FILE* block_list_file)
502 char *directory = NULL;
504 if (setjmp(setjmp_env))
505 return EXIT_FAILURE; /* Handle a call to longjmp() */
507 if (_mountpoint == NULL) {
508 mountpoint = strdup("");
510 mountpoint = canonicalize_abs_slashes(_mountpoint);
514 directory = canonicalize_rel_slashes(_directory);
518 info.len = get_file_size(fd);
521 fprintf(stderr, "Need size of filesystem\n");
525 if (info.block_size <= 0)
526 info.block_size = compute_block_size();
528 /* Round down the filesystem length to be a multiple of the block size */
529 info.len &= ~((u64)info.block_size - 1);
531 if (info.journal_blocks == 0)
532 info.journal_blocks = compute_journal_blocks();
534 if (info.no_journal == 0)
535 info.feat_compat = EXT4_FEATURE_COMPAT_HAS_JOURNAL;
537 info.journal_blocks = 0;
539 if (info.blocks_per_group <= 0)
540 info.blocks_per_group = compute_blocks_per_group();
542 if (info.inodes <= 0)
543 info.inodes = compute_inodes();
545 if (info.inode_size <= 0)
546 info.inode_size = 256;
548 if (info.label == NULL)
551 info.inodes_per_group = compute_inodes_per_group();
554 EXT4_FEATURE_COMPAT_RESIZE_INODE |
555 EXT4_FEATURE_COMPAT_EXT_ATTR;
557 info.feat_ro_compat |=
558 EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER |
559 EXT4_FEATURE_RO_COMPAT_LARGE_FILE |
560 EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
562 info.feat_incompat |=
563 EXT4_FEATURE_INCOMPAT_EXTENTS |
564 EXT4_FEATURE_INCOMPAT_FILETYPE;
567 info.bg_desc_reserve_blocks = compute_bg_desc_reserve_blocks();
569 printf("Creating filesystem with parameters:\n");
570 printf(" Size: %"PRIu64"\n", info.len);
571 printf(" Block size: %d\n", info.block_size);
572 printf(" Blocks per group: %d\n", info.blocks_per_group);
573 printf(" Inodes per group: %d\n", info.inodes_per_group);
574 printf(" Inode size: %d\n", info.inode_size);
575 printf(" Journal blocks: %d\n", info.journal_blocks);
576 printf(" Label: %s\n", info.label);
578 ext4_create_fs_aux_info();
580 printf(" Blocks: %"PRIu64"\n", aux_info.len_blocks);
581 printf(" Block groups: %d\n", aux_info.groups);
582 printf(" Reserved block group size: %d\n", info.bg_desc_reserve_blocks);
584 ext4_sparse_file = sparse_file_new(info.block_size, info.len);
586 block_allocator_init();
590 if (reserve_inodes(0, 10) == EXT4_ALLOCATE_FAILED)
591 error("failed to reserve first 10 inodes");
593 if (info.feat_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
594 ext4_create_journal_inode();
596 if (info.feat_compat & EXT4_FEATURE_COMPAT_RESIZE_INODE)
597 ext4_create_resize_inode();
600 // Windows needs only 'create an empty fs image' functionality
602 root_inode_num = build_default_directory_structure(mountpoint, sehnd);
605 root_inode_num = build_directory_structure(directory, mountpoint, 0,
606 fs_config_func, sehnd, verbose, fixed_time);
608 root_inode_num = build_default_directory_structure(mountpoint, sehnd);
611 root_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
612 inode_set_permissions(root_inode_num, root_mode, 0, 0, 0);
616 char *secontext = NULL;
618 if (selabel_lookup(sehnd, &secontext, mountpoint, S_IFDIR) < 0) {
619 error("cannot lookup security context for %s", mountpoint);
623 printf("Labeling %s as %s\n", mountpoint, secontext);
625 inode_set_selinux(root_inode_num, secontext);
635 if (block_list_file) {
636 size_t dirlen = directory ? strlen(directory) : 0;
637 struct block_allocation* p = get_saved_allocation_chain();
639 if (directory && strncmp(p->filename, directory, dirlen) == 0) {
640 // substitute mountpoint for the leading directory in the filename, in the output file
641 fprintf(block_list_file, "%s%s", mountpoint, p->filename + dirlen);
643 fprintf(block_list_file, "%s", p->filename);
645 print_blocks(block_list_file, p);
646 struct block_allocation* pn = p->next;
652 printf("Created filesystem with %d/%d inodes and %d/%d blocks\n",
653 aux_info.sb->s_inodes_count - aux_info.sb->s_free_inodes_count,
654 aux_info.sb->s_inodes_count,
655 aux_info.sb->s_blocks_count_lo - aux_info.sb->s_free_blocks_count_lo,
656 aux_info.sb->s_blocks_count_lo);
658 if (wipe && WIPE_IS_SUPPORTED) {
659 wipe_block_device(fd, info.len);
662 write_ext4_image(fd, gzip, sparse, crc);
664 sparse_file_destroy(ext4_sparse_file);
665 ext4_sparse_file = NULL;