forked from npitre/cramfs-tools
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkcramfs.c
1614 lines (1434 loc) · 42.9 KB
/
mkcramfs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vi: set sw=8 ts=8: */
/*
* mkcramfs - make a cramfs file system
*
* Copyright (C) 1999-2002 Transmeta Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Added device table support (code taken from mkfs.jffs2.c, credit to
* Erik Andersen <[email protected]>) as well as an option to squash
* permissions. - Russ Dill <[email protected]> September 2002
*
* Reworked, cleaned up, and updated for cramfs-1.1, December 2002
* - Erik Andersen <[email protected]>
*
*/
/*
* If you change the disk format of cramfs, please update fs/cramfs/README.
*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <libgen.h>
#include <ctype.h>
#include <assert.h>
#include <getopt.h>
#include <linux/cramfs_fs.h>
#include <zlib.h>
#ifdef DMALLOC
#include <dmalloc.h>
#endif
#ifndef __APPLE__
#include <sys/sysmacros.h>
#include <elf.h>
#include <endian.h>
#include <byteswap.h>
#else
#define loff_t off_t
#define bswap_16(value) \
((((value) & 0xff) << 8) | ((value) >> 8))
#define bswap_32(value) \
(((uint32_t)bswap_16((uint16_t)((value) & 0xffff)) << 16) | \
(uint32_t)bswap_16((uint16_t)((value) >> 16)))
// these constants mean nothing
#define PF_R 1
#define PF_W 2
#define PF_X 3
#endif
/* Exit codes used by mkfs-type programs */
#define MKFS_OK 0 /* No errors */
#define MKFS_ERROR 8 /* Operational error */
#define MKFS_USAGE 16 /* Usage or syntax error */
/* The kernel only supports PAD_SIZE of 0 and 512. */
#define PAD_SIZE 512
/* The kernel assumes PAGE_SIZE as block size. */
#undef PAGE_SIZE
#define PAGE_SIZE (4096)
/*
* The longest filename component to allow for in the input directory tree.
* ext2fs (and many others) allow up to 255 bytes. A couple of filesystems
* allow longer (e.g. smbfs 1024), but there isn't much use in supporting
* >255-byte names in the input directory tree given that such names get
* truncated to CRAMFS_MAXPATHLEN (252 bytes) when written to cramfs.
*
* Old versions of mkcramfs generated corrupted filesystems if any input
* filenames exceeded CRAMFS_MAXPATHLEN (252 bytes), however old
* versions of cramfsck seem to have been able to detect the corruption.
*/
#define MAX_INPUT_NAMELEN 255
/*
* Maximum size fs you can create is roughly 256MB. (The last file's
* data must begin within 256MB boundary but can extend beyond that.)
*
* Note that if you want it to fit in a ROM then you're limited to what the
* hardware and kernel can support.
*/
#define MAXFSLEN ((((1 << CRAMFS_OFFSET_WIDTH) - 1) << 2) /* offset */ \
+ (1 << CRAMFS_SIZE_WIDTH) - 1 /* filesize */ \
+ (1 << CRAMFS_SIZE_WIDTH) * 4 / PAGE_SIZE /* block pointers */ )
/* The kernel assumes PAGE_SIZE as block size. */
#define PAGE_SIZE (4096)
static const char *progname = "mkcramfs";
static unsigned int blksize = PAGE_SIZE;
static long total_blocks = 0, total_nodes = 1; /* pre-count the root node */
static int image_length = 0;
static int super_flags = CRAMFS_FLAG_FSID_VERSION_2 | CRAMFS_FLAG_SORTED_DIRS;
/*
* If opt_holes is set, then mkcramfs can create explicit holes in the
* data, which saves 26 bytes per hole (which is a lot smaller a
* saving than most most filesystems).
*
* Note that kernels up to at least 2.3.39 don't support cramfs holes,
* which is why this is turned off by default.
*
* If opt_verbose is 1, be verbose. If it is higher, be even more verbose.
*/
static u32 opt_edition = 0;
static int opt_errors = 0;
static int opt_extblkptr = 0;
static int opt_holes = 0;
static int opt_pad = 0;
static int opt_squash = 0;
static int opt_verbose = 0;
static int opt_xip = 0;
static int opt_xip_mmu = 0;
static int opt_bswap = 0;
static char *opt_image = NULL;
static char *opt_name = NULL;
static int warn_dev, warn_gid, warn_namelen, warn_skip, warn_size, warn_uid;
static const char *const memory_exhausted = "memory exhausted";
/* In-core version of inode / directory entry. */
struct entry {
/* stats */
char *name;
unsigned int mode, size, uid, gid;
/* these are only used for non-empty files */
char *path; /* always null except non-empty files */
int fd; /* temporarily open files while mmapped */
/* FS data */
void *uncompressed;
/* points to other identical file */
struct entry *same;
unsigned int offset; /* pointer to compressed data in archive */
unsigned int dir_offset; /* Where in the archive is the directory entry? */
/* organization */
struct entry *child; /* null for non-directories and empty directories */
struct entry *next;
};
/* Input status of 0 to print help and exit without an error. */
static void __attribute__((noreturn)) usage(int status)
{
FILE *stream = status ? stderr : stdout;
fprintf(stream, "usage: %s [-h] [-e edition] [-i file] [-n name] [-D file] dirname outfile\n"
" -h print this help\n"
" -E make all warnings errors (non-zero exit status)\n"
" -e edition set edition number (part of fsid)\n"
" -i file insert a file image into the filesystem (requires >= 2.4.0)\n"
" -n name set name of cramfs filesystem\n"
" -p pad by %d bytes for boot code\n"
" -s sort directory entries (old option, ignored)\n"
" -v be more verbose\n"
" -x use extended block pointers (requires >= 4.15)\n"
" -X allow XIP of ELF files (imply -x)\n"
" -z make explicit holes (requires >= 2.3.39)\n"
" -D Use the named FILE as a device table file\n"
" -q squash permissions (make everything owned by root)\n"
" -B force big-endian filesystem creation\n"
" -L force little-endian filesystem creation\n"
" dirname root of the filesystem to be compressed\n"
" outfile output file\n", progname, PAD_SIZE);
exit(status);
}
static void verror_msg(const char *s, va_list p)
{
fflush(stdout);
fprintf(stderr, "mkcramfs: ");
vfprintf(stderr, s, p);
}
static void vperror_msg(const char *s, va_list p)
{
int err = errno;
if (s == 0)
s = "";
verror_msg(s, p);
if (*s)
s = ": ";
fprintf(stderr, "%s%s\n", s, strerror(err));
}
static void perror_msg(const char *s, ...)
{
va_list p;
va_start(p, s);
vperror_msg(s, p);
va_end(p);
}
static void error_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
verror_msg(s, p);
va_end(p);
putc('\n', stderr);
exit(MKFS_ERROR);
}
static void perror_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
vperror_msg(s, p);
va_end(p);
exit(MKFS_ERROR);
}
#ifndef DMALLOC
extern char *xstrdup(const char *s)
{
char *t;
if (s == NULL)
return NULL;
t = strdup(s);
if (t == NULL)
error_msg_and_die(memory_exhausted);
return t;
}
extern void *xmalloc(size_t size)
{
void *ptr = malloc(size);
if (ptr == NULL && size != 0)
error_msg_and_die(memory_exhausted);
return ptr;
}
extern void *xcalloc(size_t nmemb, size_t size)
{
void *ptr = calloc(nmemb, size);
if (ptr == NULL && nmemb != 0 && size != 0)
error_msg_and_die(memory_exhausted);
return ptr;
}
extern void *xrealloc(void *ptr, size_t size)
{
ptr = realloc(ptr, size);
if (ptr == NULL && size != 0)
error_msg_and_die(memory_exhausted);
return ptr;
}
#endif
static FILE *xfopen(const char *path, const char *mode)
{
FILE *fp;
if ((fp = fopen(path, mode)) == NULL)
perror_msg_and_die("%s", path);
return fp;
}
extern int xopen(const char *pathname, int flags, mode_t mode)
{
int ret;
if (flags & O_CREAT)
ret = open(pathname, flags, mode);
else
ret = open(pathname, flags);
if (ret == -1) {
perror_msg_and_die("%s", pathname);
}
return ret;
}
extern char *xreadlink(const char *path)
{
static const int GROWBY = 80; /* how large we will grow strings by */
char *buf = NULL;
int bufsize = 0, readsize = 0;
do {
buf = xrealloc(buf, bufsize += GROWBY);
readsize = readlink(path, buf, bufsize); /* 1st try */
if (readsize == -1) {
perror_msg("%s:%s", progname, path);
return NULL;
}
}
while (bufsize < readsize + 1);
buf[readsize] = '\0';
return buf;
}
static void map_entry(struct entry *entry)
{
if (entry->path) {
entry->fd = open(entry->path, O_RDONLY);
if (entry->fd < 0) {
error_msg_and_die("open failed: %s", entry->path);
}
entry->uncompressed = mmap(NULL, entry->size, PROT_READ, MAP_PRIVATE, entry->fd, 0);
if (entry->uncompressed == MAP_FAILED) {
error_msg_and_die("mmap failed: %s", entry->path);
}
}
}
static void unmap_entry(struct entry *entry)
{
if (entry->path) {
if (munmap(entry->uncompressed, entry->size) < 0) {
error_msg_and_die("munmap failed: %s", entry->path);
}
entry->uncompressed=NULL;
close(entry->fd);
}
}
static int find_identical_file(struct entry *orig, struct entry *newfile)
{
if (orig == newfile)
return 1;
if (!orig)
return 0;
if (orig->size == newfile->size && (orig->path || orig->uncompressed))
{
map_entry(orig);
map_entry(newfile);
if (!memcmp(orig->uncompressed, newfile->uncompressed, orig->size))
{
newfile->same = orig;
unmap_entry(newfile);
unmap_entry(orig);
return 1;
}
unmap_entry(newfile);
unmap_entry(orig);
}
return (find_identical_file(orig->child, newfile) ||
find_identical_file(orig->next, newfile));
}
static void eliminate_doubles(struct entry *root, struct entry *orig)
{
if (orig) {
if (orig->size && (orig->path || orig->uncompressed))
find_identical_file(root, orig);
eliminate_doubles(root, orig->child);
eliminate_doubles(root, orig->next);
}
}
/*
* We define our own sorting function instead of using alphasort which
* uses strcoll and changes ordering based on locale information.
*/
static int cramsort (const struct dirent **a, const struct dirent **b)
{
return strcmp ((*a)->d_name,
(*b)->d_name);
}
static unsigned int parse_directory(struct entry *root_entry, const char *name, struct entry **prev, loff_t *fslen_ub)
{
struct dirent **dirlist;
int totalsize = 0, dircount, dirindex;
char *path, *endpath;
size_t len = strlen(name);
/* Set up the path. */
/* TODO: Reuse the parent's buffer to save memcpy'ing and duplication. */
path = xmalloc(len + 1 + MAX_INPUT_NAMELEN + 1);
memcpy(path, name, len);
endpath = path + len;
*endpath = '/';
endpath++;
/* read in the directory and sort */
dircount = scandir(name, &dirlist, 0, cramsort);
if (dircount < 0) {
error_msg_and_die("scandir failed: %s", name);
}
/* process directory */
for (dirindex = 0; dirindex < dircount; dirindex++) {
struct dirent *dirent;
struct entry *entry;
struct stat st;
int size;
size_t namelen;
dirent = dirlist[dirindex];
/* Ignore "." and ".." - we won't be adding them to the archive */
if (dirent->d_name[0] == '.') {
if (dirent->d_name[1] == '\0')
continue;
if (dirent->d_name[1] == '.') {
if (dirent->d_name[2] == '\0')
continue;
}
}
namelen = strlen(dirent->d_name);
if (namelen > MAX_INPUT_NAMELEN) {
error_msg_and_die(
"Very long (%u bytes) filename `%s' found.\n"
" Please increase MAX_INPUT_NAMELEN in mkcramfs.c and recompile. Exiting.\n",
namelen, dirent->d_name);
}
memcpy(endpath, dirent->d_name, namelen + 1);
if (lstat(path, &st) < 0) {
perror(endpath);
warn_skip = 1;
continue;
}
entry = xcalloc(1, sizeof(struct entry));
entry->name = xstrdup(dirent->d_name);
/* truncate multi-byte UTF-8 filenames on character boundary */
if (namelen > CRAMFS_MAXPATHLEN) {
namelen = CRAMFS_MAXPATHLEN;
warn_namelen = 1;
/* the first lost byte must not be a trail byte */
while ((entry->name[namelen] & 0xc0) == 0x80) {
namelen--;
/* are we reasonably certain it was UTF-8 ? */
if (!(entry->name[namelen] & 0x80) || !namelen) {
error_msg_and_die("cannot truncate filenames not encoded in UTF-8");
}
}
entry->name[namelen] = '\0';
}
entry->mode = st.st_mode;
entry->size = st.st_size;
entry->uid = opt_squash ? 0 : st.st_uid;
if (entry->uid >= 1 << CRAMFS_UID_WIDTH)
warn_uid = 1;
entry->gid = opt_squash ? 0 : st.st_gid;
if (entry->gid >= 1 << CRAMFS_GID_WIDTH) {
/* TODO: We ought to replace with a default
gid instead of truncating; otherwise there
are security problems. Maybe mode should
be &= ~070. Same goes for uid once Linux
supports >16-bit uids. */
warn_gid = 1;
}
size = sizeof(struct cramfs_inode) + ((namelen + 3) & ~3);
*fslen_ub += size;
if (S_ISDIR(st.st_mode)) {
entry->size = parse_directory(root_entry, path, &entry->child, fslen_ub);
} else if (S_ISREG(st.st_mode)) {
if (entry->size) {
if (access(path, R_OK) < 0) {
warn_skip = 1;
continue;
}
entry->path = xstrdup(path);
if ((entry->size >= 1 << CRAMFS_SIZE_WIDTH)) {
warn_size = 1;
entry->size = (1 << CRAMFS_SIZE_WIDTH) - 1;
}
}
} else if (S_ISLNK(st.st_mode)) {
entry->uncompressed = xreadlink(path);
if (!entry->uncompressed) {
warn_skip = 1;
continue;
}
} else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
/* maybe we should skip sockets */
entry->size = 0;
} else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
entry->size = st.st_rdev;
if (entry->size & -(1<<CRAMFS_SIZE_WIDTH))
warn_dev = 1;
} else {
error_msg_and_die("bogus file type: %s", entry->name);
}
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
int blocks = ((entry->size - 1) / blksize + 1);
/* block pointers & data expansion allowance + data */
if (entry->size)
*fslen_ub += (4+26)*blocks + entry->size + 3;
}
/* Link it into the list */
*prev = entry;
prev = &entry->next;
totalsize += size;
}
free(path);
free(dirlist); /* allocated by scandir() with malloc() */
return totalsize;
}
static void fs_store_bytes(void *dst, void *src, unsigned int size)
{
memcpy(dst, src, size);
}
static void fs_store_u16(void *dst, u16 val)
{
if (opt_bswap)
val = bswap_16(val);
*(u16 *)dst = val;
}
static void fs_store_u32(void *dst, u32 val)
{
if (opt_bswap)
val = bswap_32(val);
*(u32 *)dst = val;
}
static void fs_store_mode(struct cramfs_inode *inode, u32 val)
{
if (opt_bswap)
val = bswap_16(val);
inode->mode = val;
}
static void fs_store_uid(struct cramfs_inode *inode, u32 val)
{
if (opt_bswap)
val = bswap_16(val);
inode->uid = val;
}
static void fs_store_gid(struct cramfs_inode *inode, u32 val)
{
inode->gid = val;
}
static void fs_store_size(struct cramfs_inode *inode, u32 val)
{
if (opt_bswap)
val = bswap_32(val << (32 - CRAMFS_SIZE_WIDTH));
inode->size = val;
}
/*
* The namelen and offset fields don't fall on a byte boundary and
* must be treated specially when switching endianness.
*/
#define CRAMFS__OFFSET0_WIDTH (8 - CRAMFS_NAMELEN_WIDTH)
#define CRAMFS__OFFSET1_WIDTH (CRAMFS_OFFSET_WIDTH - CRAMFS__OFFSET0_WIDTH)
struct cramfs_inode_bswap {
u32 __pad[2];
u32 _offset0:CRAMFS__OFFSET0_WIDTH;
u32 _namelen:CRAMFS_NAMELEN_WIDTH;
u32 _offset1:CRAMFS__OFFSET1_WIDTH;
};
static void fs_store_namelen(struct cramfs_inode *inode, u32 val)
{
if (opt_bswap) {
struct cramfs_inode_bswap *__inode = (void *)inode;
__inode->_namelen = val;
} else {
inode->namelen = val;
}
}
static void fs_store_offset(struct cramfs_inode *inode, u32 val)
{
if (opt_bswap) {
struct cramfs_inode_bswap *__inode = (void *)inode;
#if __BYTE_ORDER == __LITTLE_ENDIAN
__inode->_offset0 = val >> CRAMFS__OFFSET1_WIDTH;
val = bswap_32(val << (32 - CRAMFS__OFFSET1_WIDTH));
__inode->_offset1 = val;
#elif __BYTE_ORDER == __BIG_ENDIAN
__inode->_offset0 = val;
val >>= CRAMFS__OFFSET0_WIDTH;
val = bswap_32(val << (32 - CRAMFS__OFFSET1_WIDTH));
__inode->_offset1 = val;
#else
#error "unknown endianness"
#endif
} else {
inode->offset = val;
}
}
/* Returns sizeof(struct cramfs_super), which includes the root inode. */
static unsigned int write_superblock(struct entry *root, unsigned char *base,
int size)
{
struct cramfs_super *super = (struct cramfs_super *) base;
unsigned int offset = sizeof(struct cramfs_super) + image_length;
if (opt_pad) {
offset += opt_pad; /* 0 if no padding */
}
fs_store_u32(&super->magic, CRAMFS_MAGIC);
if (image_length > 0)
super_flags |= CRAMFS_FLAG_SHIFTED_ROOT_OFFSET;
fs_store_u32(&super->flags, super_flags);
fs_store_u32(&super->size, size);
memcpy(super->signature, CRAMFS_SIGNATURE, sizeof(super->signature));
fs_store_u32(&super->fsid.crc, crc32(0L, Z_NULL, 0));
fs_store_u32(&super->fsid.edition, opt_edition);
fs_store_u32(&super->fsid.blocks, total_blocks);
fs_store_u32(&super->fsid.files, total_nodes);
memset(super->name, 0x00, sizeof(super->name));
if (opt_name) {
unsigned l = strlen(opt_name);
if (l > sizeof(super->name))
l = sizeof(super->name);
memcpy(super->name, opt_name, l);
} else
strncpy((char *)super->name, "Compressed", sizeof(super->name));
fs_store_mode(&super->root, root->mode);
fs_store_uid(&super->root, root->uid);
fs_store_gid(&super->root, root->gid);
fs_store_size(&super->root, root->size);
fs_store_namelen(&super->root, 0);
fs_store_offset(&super->root, offset >> 2);
return offset;
}
static void set_data_offset(struct entry *entry, unsigned char *base, unsigned long offset)
{
struct cramfs_inode *inode = (struct cramfs_inode *) (base + entry->dir_offset);
if ((offset & 3) != 0) {
error_msg_and_die("illegal offset of %lu bytes", offset);
}
if (offset >= (1 << (2 + CRAMFS_OFFSET_WIDTH))) {
error_msg_and_die("filesystem too big");
}
fs_store_offset(inode, offset >> 2);
}
/*
* TODO: Does this work for chars >= 0x80? Most filesystems use UTF-8
* encoding for filenames, whereas the console is a single-byte
* character set like iso-latin-1.
*/
static void print_node(struct entry *e)
{
char info[20];
char type = '?';
if (S_ISREG(e->mode)) type = 'f';
else if (S_ISDIR(e->mode)) type = 'd';
else if (S_ISLNK(e->mode)) type = 'l';
else if (S_ISCHR(e->mode)) type = 'c';
else if (S_ISBLK(e->mode)) type = 'b';
else if (S_ISFIFO(e->mode)) type = 'p';
else if (S_ISSOCK(e->mode)) type = 's';
if (S_ISCHR(e->mode) || (S_ISBLK(e->mode))) {
/* major/minor numbers can be as high as 2^12 or 4096 */
snprintf(info, sizeof(info), "%4d,%4d", major(e->size), minor(e->size));
}
else {
/* size be as high as 2^24 or 16777216 */
snprintf(info, sizeof(info), "%9d", e->size);
}
printf("%c %04o %s %5d:%-3d %s\n",
type, e->mode & ~S_IFMT, info, e->uid, e->gid, e->name);
}
/*
* We do a width-first printout of the directory
* entries, using a stack to remember the directories
* we've seen.
*/
static unsigned int write_directory_structure(struct entry *entry,
unsigned char *base, unsigned int offset)
{
int stack_entries = 0;
int stack_size = 64;
struct entry **entry_stack = NULL;
entry_stack = xmalloc(stack_size * sizeof(struct entry *));
for (;;) {
int dir_start = stack_entries;
while (entry) {
struct cramfs_inode *inode = (struct cramfs_inode *) (base + offset);
size_t len = strlen(entry->name);
entry->dir_offset = offset;
fs_store_mode(inode, entry->mode);
fs_store_uid(inode, entry->uid);
fs_store_gid(inode, entry->gid);
fs_store_size(inode, entry->size);
fs_store_offset(inode, 0);
/* Non-empty directories, regfiles and symlinks will
write over inode->offset later. */
offset += sizeof(struct cramfs_inode);
total_nodes++; /* another node */
fs_store_bytes(base + offset, entry->name, len);
/* Pad up the name to a 4-byte boundary */
while (len & 3) {
*(base + offset + len) = '\0';
len++;
}
fs_store_namelen(inode, len >> 2);
offset += len;
if (opt_verbose)
print_node(entry);
if (entry->child) {
if (stack_entries >= stack_size) {
stack_size *= 2;
entry_stack = xrealloc(entry_stack, stack_size * sizeof(struct entry *));
}
entry_stack[stack_entries] = entry;
stack_entries++;
}
entry = entry->next;
}
/*
* Reverse the order the stack entries pushed during
* this directory, for a small optimization of disk
* access in the created fs. This change makes things
* `ls -UR' order.
*/
{
struct entry **lo = entry_stack + dir_start;
struct entry **hi = entry_stack + stack_entries;
struct entry *tmp;
while (lo < --hi) {
tmp = *lo;
*lo++ = *hi;
*hi = tmp;
}
}
/* Pop a subdirectory entry from the stack, and recurse. */
if (!stack_entries)
break;
stack_entries--;
entry = entry_stack[stack_entries];
set_data_offset(entry, base, offset);
if (opt_verbose) {
printf("'%s':\n", entry->name);
}
entry = entry->child;
}
free(entry_stack);
return offset;
}
static int is_zero(unsigned char const *begin, unsigned len)
{
if (opt_holes)
/* Returns non-zero iff the first LEN bytes from BEGIN are
all NULs. */
return (len-- == 0 ||
(begin[0] == '\0' &&
(len-- == 0 ||
(begin[1] == '\0' &&
(len-- == 0 ||
(begin[2] == '\0' &&
(len-- == 0 ||
(begin[3] == '\0' &&
memcmp(begin, begin + 4, len) == 0))))))));
else
/* Never create holes. */
return 0;
}
/*
* This is used to determine what part of a file should be kept
* uncompressed. This returns true if the block at given offset contains
* at least one loadable segment with given flags set and cleared.
*/
static int is_elf_loadable(struct entry *entry, unsigned int offset,
int flags_set, int flags_clear)
{
#ifndef __APPLE__
Elf32_Ehdr *hdr;
Elf32_Phdr *phdr;
int i, flags;
hdr = (Elf32_Ehdr *)entry->uncompressed;
if (sizeof(*hdr) > entry->size ||
hdr->e_ident[EI_MAG0] != ELFMAG0 ||
hdr->e_ident[EI_MAG1] != ELFMAG1 ||
hdr->e_ident[EI_MAG2] != ELFMAG2 ||
hdr->e_ident[EI_MAG3] != ELFMAG3 ||
hdr->e_ident[EI_CLASS] != ELFCLASS32 ||
hdr->e_ident[EI_VERSION] != EV_CURRENT ||
hdr->e_phoff + hdr->e_phnum * sizeof(*phdr) > entry->size)
return 0;
phdr = (Elf32_Phdr *)(entry->uncompressed + hdr->e_phoff);
for (i = 0; i < hdr->e_phnum; i++) {
if (phdr[i].p_type != PT_LOAD)
continue;
if (phdr[i].p_offset >= offset + blksize)
continue;
if (phdr[i].p_offset + phdr[i].p_filesz <= offset)
continue;
flags = phdr[i].p_flags;
if ((flags & flags_set) && !(flags & flags_clear))
return 1;
}
#endif
return 0;
}
static unsigned int fs_store_compressed(unsigned char *outbuf,
unsigned char *inbuf,
unsigned int size)
{
unsigned long insize = size, outsize = 2 * blksize;
int ret;
ret = compress2(outbuf, &outsize, inbuf, insize, Z_BEST_COMPRESSION);
if (ret != Z_OK)
error_msg_and_die("compression error: %s\n", zError(ret));
return outsize;
}
/*
* One 4-byte pointer per block and then the actual blocked
* output. The block data may or may not be compressed, and
* may or may not be contiguous with previous blocks. Those
* variations are encoded in the block pointer top bits.
*
* Note that size > 0, as a zero-sized file wouldn't ever
* have gotten here in the first place.
*/
static unsigned int write_blocks(unsigned char *base, unsigned int offset, struct entry *entry)
{
unsigned int size = entry->size;
unsigned int blocks = (size - 1) / blksize + 1;
unsigned int curr = offset + 4 * blocks;
unsigned char *data = entry->uncompressed;
total_blocks += blocks;
do {
u32 blockptr_val;
unsigned int do_direct_aligned = 0;
unsigned long len;
unsigned int input = size;
if (input > blksize)
input = blksize;
if (opt_xip) {
/*
* Find out if the current block contains
* (part of) a loadable segment we want to
* keep uncompressed. For MMU-less Linux the
* only XIPable segments are read-only/executable
* and alignment is not important. With a MMU
* the writable segments may also be XIPable
* as they will be COWed but the tradeoff is
* questionable. With a MMU this must be page
* aligned and would benefit from an out-of-line
* placement but that's for the TODO list.
*/
unsigned int file_offset = entry->size - size;
if (is_elf_loadable(entry, file_offset,
PF_R|PF_X, PF_W))
do_direct_aligned =
opt_xip_mmu ? blksize : 8;
}
if (do_direct_aligned) {
int mask = do_direct_aligned - 1;
curr = (curr + mask) & ~mask;
blockptr_val = (curr >> CRAMFS_BLK_DIRECT_PTR_SHIFT)
| CRAMFS_BLK_FLAG_DIRECT_PTR
| CRAMFS_BLK_FLAG_UNCOMPRESSED;
fs_store_bytes(base + curr, data, input);
if (opt_verbose > 2)
printf("XIP at %#x for file offset %#x\n",
curr, entry->size - size);
curr += input;
} else if (is_zero(data, input)) {
/* just mark the hole */
blockptr_val = curr;
super_flags |= CRAMFS_FLAG_HOLES;
} else if (0) {
/*
* Compressed block with a direct block pointer:
* Minimum alignment is 4 bytes and the size
* is included in the block data.
*/
curr = (curr + 3) & ~3;
blockptr_val = (curr >> CRAMFS_BLK_DIRECT_PTR_SHIFT)
| CRAMFS_BLK_FLAG_DIRECT_PTR;
len = fs_store_compressed(base + curr + 2, data, input);
if (2 + len < input) {
fs_store_u16(base + curr, len);
curr += 2 + len;
} else {
/*
* Uncompressed is not smaller than
* the original. Let's use a direct
* uncompressed block instead.
*/
len = input;
fs_store_bytes(base + curr, data, len);
curr += len;
blockptr_val |= CRAMFS_BLK_FLAG_UNCOMPRESSED;
}
} else {
/*
* Normal compressed block with no particular
* alignment requirement. We still opportunistically
* do uncompressed blocks if allowed and beneficial.
*/
unsigned int flags = 0;
len = fs_store_compressed(base + curr, data, input);
if (opt_extblkptr && len >= input) {
/* Better keep it uncompressed */
if (opt_verbose > 2)
printf("literal %d vs compressed %ld\n",
input, len);
len = input;
fs_store_bytes(base + curr, data, len);
flags = CRAMFS_BLK_FLAG_UNCOMPRESSED;
}
curr += len;
blockptr_val = curr | flags;
}
data += input;
size -= input;
fs_store_u32(base + offset, blockptr_val);
offset += 4;
if (blockptr_val & CRAMFS_BLK_FLAGS)
super_flags |= CRAMFS_FLAG_EXT_BLOCK_POINTERS;
} while (size);
if (opt_verbose > 1) {
/* offset now points at the first block */
int new_size = curr - offset;
int change = new_size - entry->size;
int last_alignment = (4 - curr) & 3;
int overhead = blocks * 4 + last_alignment;
printf("%6.2f%% (%+d bytes, %d overhead)\t%s\n",
(change + overhead)*100.0 / entry->size,
change, overhead, entry->name);
}
curr = (curr + 3) & ~3;
return curr;
}