fa04263cb00640e3fb07ee29e548d9ee76d4c26c
[project/make_ext4fs.git] / make_ext4fs.c
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "make_ext4fs.h"
18 #include "ext4_utils.h"
19 #include "allocate.h"
20 #include "contents.h"
21 #include "uuid.h"
22 #include "wipe.h"
23
24 #include <sparse/sparse.h>
25
26 #include <assert.h>
27 #include <dirent.h>
28 #include <fcntl.h>
29 #include <inttypes.h>
30 #include <libgen.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37
38 #ifndef USE_MINGW
39
40 #define O_BINARY 0
41
42 #endif
43
44 /* TODO: Not implemented:
45    Allocating blocks in the same block group as the file inode
46    Hash or binary tree directories
47    Special files: sockets, devices, fifos
48  */
49
50 static int filter_dot(const struct dirent *d)
51 {
52         return (strcmp(d->d_name, "..") && strcmp(d->d_name, "."));
53 }
54
55 static u32 build_default_directory_structure(const char *dir_path)
56 {
57         u32 inode;
58         u32 root_inode;
59         struct dentry dentries = {
60                         .filename = "lost+found",
61                         .file_type = EXT4_FT_DIR,
62                         .mode = S_IRWXU,
63                         .uid = 0,
64                         .gid = 0,
65                         .mtime = 0,
66         };
67         root_inode = make_directory(0, 1, &dentries, 1);
68         inode = make_directory(root_inode, 0, NULL, 0);
69         *dentries.inode = inode;
70         inode_set_permissions(inode, dentries.mode,
71                 dentries.uid, dentries.gid, dentries.mtime);
72
73         return root_inode;
74 }
75
76 #ifndef USE_MINGW
77 /* Read a local directory and create the same tree in the generated filesystem.
78    Calls itself recursively with each directory in the given directory.
79    full_path is an absolute or relative path, with a trailing slash, to the
80    directory on disk that should be copied, or NULL if this is a directory
81    that does not exist on disk (e.g. lost+found).
82    dir_path is an absolute path, with trailing slash, to the same directory
83    if the image were mounted at the specified mount point */
84 static u32 build_directory_structure(const char *full_path, const char *dir_path,
85                 u32 dir_inode, fs_config_func_t fs_config_func,
86                 int verbose, time_t fixed_time)
87 {
88         int entries = 0;
89         struct dentry *dentries;
90         struct dirent **namelist = NULL;
91         struct stat stat;
92         int ret;
93         int i;
94         u32 inode;
95         u32 entry_inode;
96         u32 dirs = 0;
97         bool needs_lost_and_found = false;
98
99         if (full_path) {
100                 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
101                 if (entries < 0) {
102 #ifdef __GLIBC__
103                         /* The scandir function implemented in glibc has a bug that makes it
104                            erroneously fail with ENOMEM under certain circumstances.
105                            As a workaround we can retry the scandir call with the same arguments.
106                            GLIBC BZ: https://sourceware.org/bugzilla/show_bug.cgi?id=17804 */
107                         if (errno == ENOMEM)
108                                 entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
109 #endif
110                         if (entries < 0) {
111                                 error_errno("scandir");
112                                 return EXT4_ALLOCATE_FAILED;
113                         }
114                 }
115         }
116
117         if (dir_inode == 0) {
118                 /* root directory, check if lost+found already exists */
119                 for (i = 0; i < entries; i++)
120                         if (strcmp(namelist[i]->d_name, "lost+found") == 0)
121                                 break;
122                 if (i == entries)
123                         needs_lost_and_found = true;
124         }
125
126         dentries = calloc(entries, sizeof(struct dentry));
127         if (dentries == NULL)
128                 critical_error_errno("malloc");
129
130         for (i = 0; i < entries; i++) {
131                 dentries[i].filename = strdup(namelist[i]->d_name);
132                 if (dentries[i].filename == NULL)
133                         critical_error_errno("strdup");
134
135                 asprintf(&dentries[i].path, "%s%s", dir_path, namelist[i]->d_name);
136                 asprintf(&dentries[i].full_path, "%s%s", full_path, namelist[i]->d_name);
137
138                 free(namelist[i]);
139
140                 ret = lstat(dentries[i].full_path, &stat);
141                 if (ret < 0) {
142                         error_errno("lstat");
143                         i--;
144                         entries--;
145                         continue;
146                 }
147
148                 dentries[i].size = stat.st_size;
149                 dentries[i].mode = stat.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
150                 if (fixed_time == -1) {
151                         dentries[i].mtime = stat.st_mtime;
152                 } else {
153                         dentries[i].mtime = fixed_time;
154                 }
155                 uint64_t capabilities;
156                 if (fs_config_func != NULL) {
157 #ifdef ANDROID
158                         unsigned int mode = 0;
159                         unsigned int uid = 0;
160                         unsigned int gid = 0;
161                         int dir = S_ISDIR(stat.st_mode);
162                         fs_config_func(dentries[i].path, dir, &uid, &gid, &mode, &capabilities);
163                         dentries[i].mode = mode;
164                         dentries[i].uid = uid;
165                         dentries[i].gid = gid;
166                         dentries[i].capabilities = capabilities;
167 #else
168                         error("can't set android permissions - built without android support");
169 #endif
170                 }
171
172                 if (S_ISREG(stat.st_mode)) {
173                         dentries[i].file_type = EXT4_FT_REG_FILE;
174                 } else if (S_ISDIR(stat.st_mode)) {
175                         dentries[i].file_type = EXT4_FT_DIR;
176                         dirs++;
177                 } else if (S_ISCHR(stat.st_mode)) {
178                         dentries[i].file_type = EXT4_FT_CHRDEV;
179                 } else if (S_ISBLK(stat.st_mode)) {
180                         dentries[i].file_type = EXT4_FT_BLKDEV;
181                 } else if (S_ISFIFO(stat.st_mode)) {
182                         dentries[i].file_type = EXT4_FT_FIFO;
183                 } else if (S_ISSOCK(stat.st_mode)) {
184                         dentries[i].file_type = EXT4_FT_SOCK;
185                 } else if (S_ISLNK(stat.st_mode)) {
186                         dentries[i].file_type = EXT4_FT_SYMLINK;
187                         dentries[i].link = calloc(info.block_size, 1);
188                         readlink(dentries[i].full_path, dentries[i].link, info.block_size - 1);
189                 } else {
190                         error("unknown file type on %s", dentries[i].path);
191                         i--;
192                         entries--;
193                 }
194         }
195         free(namelist);
196
197         if (needs_lost_and_found) {
198                 /* insert a lost+found directory at the beginning of the dentries */
199                 struct dentry *tmp = calloc(entries + 1, sizeof(struct dentry));
200                 memset(tmp, 0, sizeof(struct dentry));
201                 memcpy(tmp + 1, dentries, entries * sizeof(struct dentry));
202                 dentries = tmp;
203
204                 dentries[0].filename = strdup("lost+found");
205                 asprintf(&dentries[0].path, "%slost+found", dir_path);
206                 dentries[0].full_path = NULL;
207                 dentries[0].size = 0;
208                 dentries[0].mode = S_IRWXU;
209                 dentries[0].file_type = EXT4_FT_DIR;
210                 dentries[0].uid = 0;
211                 dentries[0].gid = 0;
212                 entries++;
213                 dirs++;
214         }
215
216         inode = make_directory(dir_inode, entries, dentries, dirs);
217
218         for (i = 0; i < entries; i++) {
219                 if (dentries[i].file_type == EXT4_FT_REG_FILE) {
220                         entry_inode = make_file(dentries[i].full_path, dentries[i].size);
221                 } else if (dentries[i].file_type == EXT4_FT_DIR) {
222                         char *subdir_full_path = NULL;
223                         char *subdir_dir_path;
224                         if (dentries[i].full_path) {
225                                 ret = asprintf(&subdir_full_path, "%s/", dentries[i].full_path);
226                                 if (ret < 0)
227                                         critical_error_errno("asprintf");
228                         }
229                         ret = asprintf(&subdir_dir_path, "%s/", dentries[i].path);
230                         if (ret < 0)
231                                 critical_error_errno("asprintf");
232                         entry_inode = build_directory_structure(subdir_full_path,
233                                         subdir_dir_path, inode, fs_config_func, verbose, fixed_time);
234                         free(subdir_full_path);
235                         free(subdir_dir_path);
236                 } else if (dentries[i].file_type == EXT4_FT_SYMLINK) {
237                         entry_inode = make_link(dentries[i].link);
238                 } else {
239                         error("unknown file type on %s", dentries[i].path);
240                         entry_inode = 0;
241                 }
242                 *dentries[i].inode = entry_inode;
243
244                 ret = inode_set_permissions(entry_inode, dentries[i].mode,
245                         dentries[i].uid, dentries[i].gid,
246                         dentries[i].mtime);
247                 if (ret)
248                         error("failed to set permissions on %s\n", dentries[i].path);
249
250                 /*
251                  * It's important to call inode_set_selinux() before
252                  * inode_set_capabilities(). Extended attributes need to
253                  * be stored sorted order, and we guarantee this by making
254                  * the calls in the proper order.
255                  * Please see xattr_assert_sane() in contents.c
256                  */
257                 ret = inode_set_selinux(entry_inode, dentries[i].secon);
258                 if (ret)
259                         error("failed to set SELinux context on %s\n", dentries[i].path);
260                 ret = inode_set_capabilities(entry_inode, dentries[i].capabilities);
261                 if (ret)
262                         error("failed to set capability on %s\n", dentries[i].path);
263
264                 free(dentries[i].path);
265                 free(dentries[i].full_path);
266                 free(dentries[i].link);
267                 free((void *)dentries[i].filename);
268                 free(dentries[i].secon);
269         }
270
271         free(dentries);
272         return inode;
273 }
274 #endif
275
276 static u32 compute_block_size()
277 {
278         return 4096;
279 }
280
281 static u32 compute_journal_blocks()
282 {
283         u32 journal_blocks = DIV_ROUND_UP(info.len, info.block_size) / 64;
284         if (journal_blocks < 1024)
285                 journal_blocks = 1024;
286         if (journal_blocks > 32768)
287                 journal_blocks = 32768;
288         return journal_blocks;
289 }
290
291 static u32 compute_blocks_per_group()
292 {
293         return info.block_size * 8;
294 }
295
296 static u32 compute_inodes()
297 {
298         return DIV_ROUND_UP(info.len, info.block_size) / 4;
299 }
300
301 static u32 compute_inodes_per_group()
302 {
303         u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
304         u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
305         u32 inodes = DIV_ROUND_UP(info.inodes, block_groups);
306         inodes = EXT4_ALIGN(inodes, (info.block_size / info.inode_size));
307
308         /* After properly rounding up the number of inodes/group,
309          * make sure to update the total inodes field in the info struct.
310          */
311         info.inodes = inodes * block_groups;
312
313         return inodes;
314 }
315
316 static u32 compute_bg_desc_reserve_blocks()
317 {
318         u32 blocks = DIV_ROUND_UP(info.len, info.block_size);
319         u32 block_groups = DIV_ROUND_UP(blocks, info.blocks_per_group);
320         u32 bg_desc_blocks = DIV_ROUND_UP(block_groups * sizeof(struct ext2_group_desc),
321                         info.block_size);
322
323         u32 bg_desc_reserve_blocks =
324                         DIV_ROUND_UP(block_groups * 1024 * sizeof(struct ext2_group_desc),
325                                         info.block_size) - bg_desc_blocks;
326
327         if (bg_desc_reserve_blocks > info.block_size / sizeof(u32))
328                 bg_desc_reserve_blocks = info.block_size / sizeof(u32);
329
330         return bg_desc_reserve_blocks;
331 }
332
333 void reset_ext4fs_info() {
334         // Reset all the global data structures used by make_ext4fs so it
335         // can be called again.
336         memset(&info, 0, sizeof(info));
337         memset(&aux_info, 0, sizeof(aux_info));
338
339         if (ext4_sparse_file) {
340                 sparse_file_destroy(ext4_sparse_file);
341                 ext4_sparse_file = NULL;
342         }
343 }
344
345 int make_ext4fs_sparse_fd(int fd, long long len,
346                                 const char *mountpoint)
347 {
348         reset_ext4fs_info();
349         info.len = len;
350
351         return make_ext4fs_internal(fd, NULL, mountpoint, NULL, 0, 1, 0, 0, 0, -1, NULL);
352 }
353
354 int make_ext4fs(const char *filename, long long len,
355                                 const char *mountpoint)
356 {
357         int fd;
358         int status;
359
360         reset_ext4fs_info();
361         info.len = len;
362
363         fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
364         if (fd < 0) {
365                 error_errno("open");
366                 return EXIT_FAILURE;
367         }
368
369         status = make_ext4fs_internal(fd, NULL, mountpoint, NULL, 0, 0, 0, 1, 0, -1, NULL);
370         close(fd);
371
372         return status;
373 }
374
375 /* return a newly-malloc'd string that is a copy of str.  The new string
376    is guaranteed to have a trailing slash.  If absolute is true, the new string
377    is also guaranteed to have a leading slash.
378 */
379 static char *canonicalize_slashes(const char *str, bool absolute)
380 {
381         char *ret;
382         int len = strlen(str);
383         int newlen = len;
384         char *ptr;
385
386         if (len == 0) {
387                 if (absolute)
388                         return strdup("/");
389                 else
390                         return strdup("");
391         }
392
393         if (str[0] != '/' && absolute) {
394                 newlen++;
395         }
396         if (str[len - 1] != '/') {
397                 newlen++;
398         }
399         ret = malloc(newlen + 1);
400         if (!ret) {
401                 critical_error("malloc");
402         }
403
404         ptr = ret;
405         if (str[0] != '/' && absolute) {
406                 *ptr++ = '/';
407         }
408
409         strcpy(ptr, str);
410         ptr += len;
411
412         if (str[len - 1] != '/') {
413                 *ptr++ = '/';
414         }
415
416         if (ptr != ret + newlen) {
417                 critical_error("assertion failed\n");
418         }
419
420         *ptr = '\0';
421
422         return ret;
423 }
424
425 static char *canonicalize_abs_slashes(const char *str)
426 {
427         return canonicalize_slashes(str, true);
428 }
429
430 static char *canonicalize_rel_slashes(const char *str)
431 {
432         return canonicalize_slashes(str, false);
433 }
434
435 int make_ext4fs_internal(int fd, const char *_directory,
436                                                  const char *_mountpoint, fs_config_func_t fs_config_func, int gzip,
437                                                  int sparse, int crc, int wipe,
438                                                  int verbose, time_t fixed_time,
439                                                  FILE* block_list_file)
440 {
441         u32 root_inode_num;
442         u16 root_mode;
443         char *mountpoint;
444         char *directory = NULL;
445
446         if (setjmp(setjmp_env))
447                 return EXIT_FAILURE; /* Handle a call to longjmp() */
448
449         if (_mountpoint == NULL) {
450                 mountpoint = strdup("");
451         } else {
452                 mountpoint = canonicalize_abs_slashes(_mountpoint);
453         }
454
455         if (_directory) {
456                 directory = canonicalize_rel_slashes(_directory);
457         }
458
459         if (info.len <= 0)
460                 info.len = get_file_size(fd);
461
462         if (info.len <= 0) {
463                 fprintf(stderr, "Need size of filesystem\n");
464                 return EXIT_FAILURE;
465         }
466
467         if (info.block_size <= 0)
468                 info.block_size = compute_block_size();
469
470         /* Round down the filesystem length to be a multiple of the block size */
471         info.len &= ~((u64)info.block_size - 1);
472
473         if (info.journal_blocks == 0)
474                 info.journal_blocks = compute_journal_blocks();
475
476         if (info.no_journal == 0)
477                 info.feat_compat = EXT4_FEATURE_COMPAT_HAS_JOURNAL;
478         else
479                 info.journal_blocks = 0;
480
481         if (info.blocks_per_group <= 0)
482                 info.blocks_per_group = compute_blocks_per_group();
483
484         if (info.inodes <= 0)
485                 info.inodes = compute_inodes();
486
487         if (info.inode_size <= 0)
488                 info.inode_size = 256;
489
490         if (info.label == NULL)
491                 info.label = "";
492
493         info.inodes_per_group = compute_inodes_per_group();
494
495         info.feat_compat |=
496                         EXT4_FEATURE_COMPAT_RESIZE_INODE |
497                         EXT4_FEATURE_COMPAT_EXT_ATTR;
498
499         info.feat_ro_compat |=
500                         EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER |
501                         EXT4_FEATURE_RO_COMPAT_LARGE_FILE |
502                         EXT4_FEATURE_RO_COMPAT_GDT_CSUM;
503
504         info.feat_incompat |=
505                         EXT4_FEATURE_INCOMPAT_EXTENTS |
506                         EXT4_FEATURE_INCOMPAT_FILETYPE;
507
508
509         info.bg_desc_reserve_blocks = compute_bg_desc_reserve_blocks();
510
511         printf("Creating filesystem with parameters:\n");
512         printf("    Size: %"PRIu64"\n", info.len);
513         printf("    Block size: %d\n", info.block_size);
514         printf("    Blocks per group: %d\n", info.blocks_per_group);
515         printf("    Inodes per group: %d\n", info.inodes_per_group);
516         printf("    Inode size: %d\n", info.inode_size);
517         printf("    Journal blocks: %d\n", info.journal_blocks);
518         printf("    Label: %s\n", info.label);
519
520         ext4_create_fs_aux_info();
521
522         printf("    Blocks: %"PRIu64"\n", aux_info.len_blocks);
523         printf("    Block groups: %d\n", aux_info.groups);
524         printf("    Reserved block group size: %d\n", info.bg_desc_reserve_blocks);
525
526         ext4_sparse_file = sparse_file_new(info.block_size, info.len);
527
528         block_allocator_init();
529
530         ext4_fill_in_sb();
531
532         if (reserve_inodes(0, 10) == EXT4_ALLOCATE_FAILED)
533                 error("failed to reserve first 10 inodes");
534
535         if (info.feat_compat & EXT4_FEATURE_COMPAT_HAS_JOURNAL)
536                 ext4_create_journal_inode();
537
538         if (info.feat_compat & EXT4_FEATURE_COMPAT_RESIZE_INODE)
539                 ext4_create_resize_inode();
540
541 #ifdef USE_MINGW
542         // Windows needs only 'create an empty fs image' functionality
543         assert(!directory);
544         root_inode_num = build_default_directory_structure(mountpoint);
545 #else
546         if (directory)
547                 root_inode_num = build_directory_structure(directory, mountpoint, 0,
548                         fs_config_func, verbose, fixed_time);
549         else
550                 root_inode_num = build_default_directory_structure(mountpoint);
551 #endif
552
553         root_mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
554         inode_set_permissions(root_inode_num, root_mode, 0, 0, 0);
555
556         ext4_update_free();
557
558         ext4_queue_sb();
559
560         if (block_list_file) {
561                 size_t dirlen = directory ? strlen(directory) : 0;
562                 struct block_allocation* p = get_saved_allocation_chain();
563                 while (p) {
564                         if (directory && strncmp(p->filename, directory, dirlen) == 0) {
565                                 // substitute mountpoint for the leading directory in the filename, in the output file
566                                 fprintf(block_list_file, "%s%s", mountpoint, p->filename + dirlen);
567                         } else {
568                                 fprintf(block_list_file, "%s", p->filename);
569                         }
570                         print_blocks(block_list_file, p);
571                         struct block_allocation* pn = p->next;
572                         free_alloc(p);
573                         p = pn;
574                 }
575         }
576
577         printf("Created filesystem with %d/%d inodes and %d/%d blocks\n",
578                         aux_info.sb->s_inodes_count - aux_info.sb->s_free_inodes_count,
579                         aux_info.sb->s_inodes_count,
580                         aux_info.sb->s_blocks_count_lo - aux_info.sb->s_free_blocks_count_lo,
581                         aux_info.sb->s_blocks_count_lo);
582
583         if (wipe && WIPE_IS_SUPPORTED) {
584                 wipe_block_device(fd, info.len);
585         }
586
587         write_ext4_image(fd, gzip, sparse, crc);
588
589         sparse_file_destroy(ext4_sparse_file);
590         ext4_sparse_file = NULL;
591
592         free(mountpoint);
593         free(directory);
594
595         return 0;
596 }