OSDN Git Service

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