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