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