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