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