Whamcloud - gitweb
Check fgets(3) return value
[tools/e2fsprogs.git] / debugfs / debugfs.c
1 /*
2  * debugfs.c --- a program which allows you to attach an ext2fs
3  * filesystem and play with it.
4  *
5  * Copyright (C) 1993 Theodore Ts'o.  This file may be redistributed
6  * under the terms of the GNU Public License.
7  * 
8  * Modifications by Robert Sanders <gt8134b@prism.gatech.edu>
9  */
10
11 #include <stdio.h>
12 #include <unistd.h>
13 #include <stdlib.h>
14 #include <ctype.h>
15 #include <string.h>
16 #include <time.h>
17 #ifdef HAVE_GETOPT_H
18 #include <getopt.h>
19 #else 
20 extern int optind;
21 extern char *optarg;
22 #endif
23 #ifdef HAVE_ERRNO_H
24 #include <errno.h>
25 #endif
26 #include <fcntl.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include "et/com_err.h"
31 #include "ss/ss.h"
32 #include "debugfs.h"
33 #include "uuid/uuid.h"
34 #include "e2p/e2p.h"
35
36 #include <ext2fs/ext2_ext_attr.h>
37
38 #include "../version.h"
39
40 extern ss_request_table debug_cmds;
41
42 ext2_filsys     current_fs = NULL;
43 ext2_ino_t      root, cwd;
44
45 static void open_filesystem(char *device, int open_flags, blk_t superblock,
46                             blk_t blocksize, int catastrophic, 
47                             char *data_filename)
48 {
49         int     retval;
50         io_channel data_io = 0;
51
52         if (superblock != 0 && blocksize == 0) {
53                 com_err(device, 0, "if you specify the superblock, you must also specify the block size");
54                 current_fs = NULL;
55                 return;
56         }
57
58         if (data_filename) {
59                 if ((open_flags & EXT2_FLAG_IMAGE_FILE) == 0) {
60                         com_err(device, 0, 
61                                 "The -d option is only valid when reading an e2image file");
62                         current_fs = NULL;
63                         return;
64                 }
65                 retval = unix_io_manager->open(data_filename, 0, &data_io);
66                 if (retval) {
67                         com_err(data_filename, 0, "while opening data source");
68                         current_fs = NULL;
69                         return;
70                 }
71         }
72
73         if (catastrophic && (open_flags & EXT2_FLAG_RW)) {
74                 com_err(device, 0,
75                         "opening read-only because of catastrophic mode");
76                 open_flags &= ~EXT2_FLAG_RW;
77         }
78         
79         retval = ext2fs_open(device, open_flags, superblock, blocksize,
80                              unix_io_manager, &current_fs);
81         if (retval) {
82                 com_err(device, retval, "while opening filesystem");
83                 current_fs = NULL;
84                 return;
85         }
86
87         if (catastrophic)
88                 com_err(device, 0, "catastrophic mode - not reading inode or group bitmaps");
89         else {
90                 retval = ext2fs_read_inode_bitmap(current_fs);
91                 if (retval) {
92                         com_err(device, retval, "while reading inode bitmap");
93                         goto errout;
94                 }
95                 retval = ext2fs_read_block_bitmap(current_fs);
96                 if (retval) {
97                         com_err(device, retval, "while reading block bitmap");
98                         goto errout;
99                 }
100         }
101
102         if (data_io) {
103                 retval = ext2fs_set_data_io(current_fs, data_io);
104                 if (retval) {
105                         com_err(device, retval, 
106                                 "while setting data source");
107                         goto errout;
108                 }
109         }
110
111         root = cwd = EXT2_ROOT_INO;
112         return;
113
114 errout:
115         retval = ext2fs_close(current_fs);
116         if (retval)
117                 com_err(device, retval, "while trying to close filesystem");
118         current_fs = NULL;
119 }
120
121 void do_open_filesys(int argc, char **argv)
122 {
123         int     c, err;
124         int     catastrophic = 0;
125         blk_t   superblock = 0;
126         blk_t   blocksize = 0;
127         int     open_flags = EXT2_FLAG_SOFTSUPP_FEATURES;
128         char    *data_filename = 0;
129         
130         reset_getopt();
131         while ((c = getopt (argc, argv, "iwfecb:s:d:")) != EOF) {
132                 switch (c) {
133                 case 'i':
134                         open_flags |= EXT2_FLAG_IMAGE_FILE;
135                         break;
136                 case 'w':
137                         open_flags |= EXT2_FLAG_RW;
138                         break;
139                 case 'f':
140                         open_flags |= EXT2_FLAG_FORCE;
141                         break;
142                 case 'e':
143                         open_flags |= EXT2_FLAG_EXCLUSIVE;
144                         break;
145                 case 'c':
146                         catastrophic = 1;
147                         break;
148                 case 'd':
149                         data_filename = optarg;
150                         break;
151                 case 'b':
152                         blocksize = parse_ulong(optarg, argv[0],
153                                                 "block size", &err);
154                         if (err)
155                                 return;
156                         break;
157                 case 's':
158                         superblock = parse_ulong(optarg, argv[0],
159                                                  "superblock number", &err);
160                         if (err)
161                                 return;
162                         break;
163                 default:
164                         goto print_usage;
165                 }
166         }
167         if (optind != argc-1) {
168                 goto print_usage;
169         }
170         if (check_fs_not_open(argv[0]))
171                 return;
172         open_filesystem(argv[optind], open_flags,
173                         superblock, blocksize, catastrophic, 
174                         data_filename);
175         return;
176
177 print_usage:
178         fprintf(stderr, "%s: Usage: open [-s superblock] [-b blocksize] "
179                 "[-c] [-w] <device>\n", argv[0]);
180 }
181
182 void do_lcd(int argc, char **argv)
183 {
184         if (argc != 2) {
185                 com_err(argv[0], 0, "Usage: %s %s", argv[0], "<native dir>");
186                 return;
187         }
188
189         if (chdir(argv[1]) == -1) {
190                 com_err(argv[0], errno,
191                         "while trying to change native directory to %s",
192                         argv[1]);
193                 return;
194         }
195 }
196
197 static void close_filesystem(NOARGS)
198 {
199         int     retval;
200         
201         if (current_fs->flags & EXT2_FLAG_IB_DIRTY) {
202                 retval = ext2fs_write_inode_bitmap(current_fs);
203                 if (retval)
204                         com_err("ext2fs_write_inode_bitmap", retval, 0);
205         }
206         if (current_fs->flags & EXT2_FLAG_BB_DIRTY) {
207                 retval = ext2fs_write_block_bitmap(current_fs);
208                 if (retval)
209                         com_err("ext2fs_write_block_bitmap", retval, 0);
210         }
211         retval = ext2fs_close(current_fs);
212         if (retval)
213                 com_err("ext2fs_close", retval, 0);
214         current_fs = NULL;
215         return;
216 }
217
218 void do_close_filesys(int argc, char **argv)
219 {
220         if (common_args_process(argc, argv, 1, 1, "close_filesys", "", 0))
221                 return;
222         close_filesystem();
223 }
224
225 void do_init_filesys(int argc, char **argv)
226 {
227         struct ext2_super_block param;
228         errcode_t       retval;
229         int             err;
230         
231         if (common_args_process(argc, argv, 3, 3, "initialize",
232                                 "<device> <blocksize>", CHECK_FS_NOTOPEN))
233                 return;
234
235         memset(&param, 0, sizeof(struct ext2_super_block));
236         param.s_blocks_count = parse_ulong(argv[2], argv[0],
237                                            "blocks count", &err);
238         if (err)
239                 return;
240         retval = ext2fs_initialize(argv[1], 0, &param,
241                                    unix_io_manager, &current_fs);
242         if (retval) {
243                 com_err(argv[1], retval, "while initializing filesystem");
244                 current_fs = NULL;
245                 return;
246         }
247         root = cwd = EXT2_ROOT_INO;
248         return;
249 }
250
251 static void print_features(struct ext2_super_block * s, FILE *f)
252 {
253         int     i, j, printed=0;
254         __u32   *mask = &s->s_feature_compat, m;
255
256         fputs("Filesystem features:", f);
257         for (i=0; i <3; i++,mask++) {
258                 for (j=0,m=1; j < 32; j++, m<<=1) {
259                         if (*mask & m) {
260                                 fprintf(f, " %s", e2p_feature2string(i, m));
261                                 printed++;
262                         }
263                 }
264         }
265         if (printed == 0)
266                 fputs("(none)", f);
267         fputs("\n", f);
268 }
269
270 static void print_bg_opts(struct ext2_group_desc *gdp, int mask,
271                           const char *str, int *first, FILE *f)
272 {
273         if (gdp->bg_flags & mask) {
274                 if (*first) {
275                         fputs("           [", f);
276                         *first = 0;
277                 } else
278                         fputs(", ", f);
279                 fputs(str, f);
280         }
281 }
282
283 void do_show_super_stats(int argc, char *argv[])
284 {
285         dgrp_t  i;
286         FILE    *out;
287         struct ext2_group_desc *gdp;
288         int     c, header_only = 0;
289         int     numdirs = 0, first;
290
291         reset_getopt();
292         while ((c = getopt (argc, argv, "h")) != EOF) {
293                 switch (c) {
294                 case 'h':
295                         header_only++;
296                         break;
297                 default:
298                         goto print_usage;
299                 }
300         }
301         if (optind != argc) {
302                 goto print_usage;
303         }
304         if (check_fs_open(argv[0]))
305                 return;
306         out = open_pager();
307
308         list_super2(current_fs->super, out);
309         for (i=0; i < current_fs->group_desc_count; i++)
310                 numdirs += current_fs->group_desc[i].bg_used_dirs_count;
311         fprintf(out, "Directories:              %d\n", numdirs);
312         
313         if (header_only) {
314                 close_pager(out);
315                 return;
316         }
317         
318         gdp = &current_fs->group_desc[0];
319         for (i = 0; i < current_fs->group_desc_count; i++, gdp++) {
320                 fprintf(out, " Group %2d: block bitmap at %u, "
321                         "inode bitmap at %u, "
322                         "inode table at %u\n"
323                         "           %d free %s, "
324                         "%d free %s, "
325                         "%d used %s\n",
326                         i, gdp->bg_block_bitmap,
327                         gdp->bg_inode_bitmap, gdp->bg_inode_table,
328                         gdp->bg_free_blocks_count,
329                         gdp->bg_free_blocks_count != 1 ? "blocks" : "block",
330                         gdp->bg_free_inodes_count,
331                         gdp->bg_free_inodes_count != 1 ? "inodes" : "inode",
332                         gdp->bg_used_dirs_count,
333                         gdp->bg_used_dirs_count != 1 ? "directories"
334                                 : "directory");
335                 first = 1;
336                 print_bg_opts(gdp, EXT2_BG_INODE_UNINIT, "Inode not init",
337                               &first, out);
338                 print_bg_opts(gdp, EXT2_BG_BLOCK_UNINIT, "Block not init",
339                               &first, out);
340                 if (!first)
341                         fputs("]\n", out);
342         }
343         close_pager(out);
344         return;
345 print_usage:
346         fprintf(stderr, "%s: Usage: show_super [-h]\n", argv[0]);
347 }
348
349 void do_dirty_filesys(int argc EXT2FS_ATTR((unused)), 
350                       char **argv EXT2FS_ATTR((unused)))
351 {
352         if (check_fs_open(argv[0]))
353                 return;
354         if (check_fs_read_write(argv[0]))
355                 return;
356
357         if (argv[1] && !strcmp(argv[1], "-clean"))
358                 current_fs->super->s_state |= EXT2_VALID_FS;
359         else
360                 current_fs->super->s_state &= ~EXT2_VALID_FS;
361         ext2fs_mark_super_dirty(current_fs);
362 }
363
364 struct list_blocks_struct {
365         FILE            *f;
366         e2_blkcnt_t     total;
367         blk_t           first_block, last_block;
368         e2_blkcnt_t     first_bcnt, last_bcnt;
369         e2_blkcnt_t     first;
370 };
371
372 static void finish_range(struct list_blocks_struct *lb)
373 {
374         if (lb->first_block == 0)
375                 return;
376         if (lb->first)
377                 lb->first = 0;
378         else
379                 fprintf(lb->f, ", ");
380         if (lb->first_block == lb->last_block)
381                 fprintf(lb->f, "(%lld):%u",
382                         (long long)lb->first_bcnt, lb->first_block);
383         else
384                 fprintf(lb->f, "(%lld-%lld):%u-%u",
385                         (long long)lb->first_bcnt, (long long)lb->last_bcnt,
386                         lb->first_block, lb->last_block);
387         lb->first_block = 0;
388 }
389
390 static int list_blocks_proc(ext2_filsys fs EXT2FS_ATTR((unused)), 
391                             blk_t *blocknr, e2_blkcnt_t blockcnt, 
392                             blk_t ref_block EXT2FS_ATTR((unused)),
393                             int ref_offset EXT2FS_ATTR((unused)), 
394                             void *private)
395 {
396         struct list_blocks_struct *lb = (struct list_blocks_struct *) private;
397
398         lb->total++;
399         if (blockcnt >= 0) {
400                 /*
401                  * See if we can add on to the existing range (if it exists)
402                  */
403                 if (lb->first_block &&
404                     (lb->last_block+1 == *blocknr) &&
405                     (lb->last_bcnt+1 == blockcnt)) {
406                         lb->last_block = *blocknr;
407                         lb->last_bcnt = blockcnt;
408                         return 0;
409                 }
410                 /*
411                  * Start a new range.
412                  */
413                 finish_range(lb);
414                 lb->first_block = lb->last_block = *blocknr;
415                 lb->first_bcnt = lb->last_bcnt = blockcnt;
416                 return 0;
417         }
418         /*
419          * Not a normal block.  Always force a new range.
420          */
421         finish_range(lb);
422         if (lb->first)
423                 lb->first = 0;
424         else
425                 fprintf(lb->f, ", ");
426         if (blockcnt == -1)
427                 fprintf(lb->f, "(IND):%u", *blocknr);
428         else if (blockcnt == -2)
429                 fprintf(lb->f, "(DIND):%u", *blocknr);
430         else if (blockcnt == -3)
431                 fprintf(lb->f, "(TIND):%u", *blocknr);
432         return 0;
433 }
434
435 static void dump_xattr_string(FILE *out, const char *str, int len)
436 {
437         int printable = 1;
438         int i;
439         
440         /* check is string printable? */
441         for (i = 0; i < len; i++)
442                 if (!isprint(str[i])) {
443                         printable = 0;
444                         break;
445                 }
446
447         for (i = 0; i < len; i++)
448                 if (printable)
449                         fprintf(out, "%c", (unsigned char)str[i]);
450                 else
451                         fprintf(out, "%02x ", (unsigned char)str[i]);
452 }
453
454 static void internal_dump_inode_extra(FILE *out, 
455                                       const char *prefix EXT2FS_ATTR((unused)),
456                                       ext2_ino_t inode_num EXT2FS_ATTR((unused)), 
457                                       struct ext2_inode_large *inode)
458 {
459         struct ext2_ext_attr_entry *entry;
460         __u32 *magic;
461         char *start, *end;
462         unsigned int storage_size;
463
464         fprintf(out, "Size of extra inode fields: %u\n", inode->i_extra_isize);
465         if (inode->i_extra_isize > EXT2_INODE_SIZE(current_fs->super) -
466                         EXT2_GOOD_OLD_INODE_SIZE) {
467                 fprintf(stderr, "invalid inode->i_extra_isize (%u)\n",
468                                 inode->i_extra_isize);
469                 return;
470         }
471         storage_size = EXT2_INODE_SIZE(current_fs->super) -
472                         EXT2_GOOD_OLD_INODE_SIZE -
473                         inode->i_extra_isize;
474         magic = (__u32 *)((char *)inode + EXT2_GOOD_OLD_INODE_SIZE +
475                         inode->i_extra_isize);
476         if (*magic == EXT2_EXT_ATTR_MAGIC) {
477                 fprintf(out, "Extended attributes stored in inode body: \n");
478                 end = (char *) inode + EXT2_INODE_SIZE(current_fs->super);
479                 start = (char *) magic + sizeof(__u32);
480                 entry = (struct ext2_ext_attr_entry *) start;
481                 while (!EXT2_EXT_IS_LAST_ENTRY(entry)) {
482                         struct ext2_ext_attr_entry *next =
483                                 EXT2_EXT_ATTR_NEXT(entry);
484                         if (entry->e_value_size > storage_size ||
485                                         (char *) next >= end) {
486                                 fprintf(out, "invalid EA entry in inode\n");
487                                 return;
488                         }
489                         fprintf(out, "  ");
490                         dump_xattr_string(out, EXT2_EXT_ATTR_NAME(entry), 
491                                           entry->e_name_len);
492                         fprintf(out, " = \"");
493                         dump_xattr_string(out, start + entry->e_value_offs,
494                                                 entry->e_value_size);
495                         fprintf(out, "\" (%u)\n", entry->e_value_size);
496                         entry = next;
497                 }
498         }
499 }
500
501 static void dump_blocks(FILE *f, const char *prefix, ext2_ino_t inode)
502 {
503         struct list_blocks_struct lb;
504
505         fprintf(f, "%sBLOCKS:\n%s", prefix, prefix);
506         lb.total = 0;
507         lb.first_block = 0;
508         lb.f = f;
509         lb.first = 1;
510         ext2fs_block_iterate2(current_fs, inode, 0, NULL,
511                              list_blocks_proc, (void *)&lb);
512         finish_range(&lb);
513         if (lb.total)
514                 fprintf(f, "\n%sTOTAL: %lld\n", prefix, (long long)lb.total);
515         fprintf(f,"\n");
516 }
517
518
519 void internal_dump_inode(FILE *out, const char *prefix,
520                          ext2_ino_t inode_num, struct ext2_inode *inode,
521                          int do_dump_blocks)
522 {
523         const char *i_type;
524         char frag, fsize;
525         int os = current_fs->super->s_creator_os;
526         
527         if (LINUX_S_ISDIR(inode->i_mode)) i_type = "directory";
528         else if (LINUX_S_ISREG(inode->i_mode)) i_type = "regular";
529         else if (LINUX_S_ISLNK(inode->i_mode)) i_type = "symlink";
530         else if (LINUX_S_ISBLK(inode->i_mode)) i_type = "block special";
531         else if (LINUX_S_ISCHR(inode->i_mode)) i_type = "character special";
532         else if (LINUX_S_ISFIFO(inode->i_mode)) i_type = "FIFO";
533         else if (LINUX_S_ISSOCK(inode->i_mode)) i_type = "socket";
534         else i_type = "bad type";
535         fprintf(out, "%sInode: %u   Type: %s    ", prefix, inode_num, i_type);
536         fprintf(out, "%sMode:  %04o   Flags: 0x%x   Generation: %u\n",
537                 prefix, 
538                 inode->i_mode & 0777, inode->i_flags, inode->i_generation);
539         fprintf(out, "%sUser: %5d   Group: %5d   Size: ",
540                 prefix, inode_uid(*inode), inode_gid(*inode));
541         if (LINUX_S_ISREG(inode->i_mode)) {
542                 unsigned long long i_size = (inode->i_size |
543                                     ((unsigned long long)inode->i_size_high << 32));
544
545                 fprintf(out, "%llu\n", i_size);
546         } else
547                 fprintf(out, "%d\n", inode->i_size);
548         if (os == EXT2_OS_HURD)
549                 fprintf(out,
550                         "%sFile ACL: %d    Directory ACL: %d Translator: %d\n",
551                         prefix,
552                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0,
553                         inode->osd1.hurd1.h_i_translator);
554         else
555                 fprintf(out, "%sFile ACL: %d    Directory ACL: %d\n",
556                         prefix,
557                         inode->i_file_acl, LINUX_S_ISDIR(inode->i_mode) ? inode->i_dir_acl : 0);
558         if (os == EXT2_OS_LINUX) 
559                 fprintf(out, "%sLinks: %d   Blockcount: %llu\n",
560                         prefix, inode->i_links_count, 
561                         (((unsigned long long) 
562                           inode->osd2.linux2.l_i_blocks_hi << 32)) + 
563                         inode->i_blocks);
564         else
565                 fprintf(out, "%sLinks: %d   Blockcount: %u\n",
566                         prefix, inode->i_links_count, inode->i_blocks);
567         switch (os) {
568             case EXT2_OS_HURD:
569                 frag = inode->osd2.hurd2.h_i_frag;
570                 fsize = inode->osd2.hurd2.h_i_fsize;
571                 break;
572             case EXT2_OS_MASIX:
573                 frag = inode->osd2.masix2.m_i_frag;
574                 fsize = inode->osd2.masix2.m_i_fsize;
575                 break;
576             default:
577                 frag = fsize = 0;
578         }
579         fprintf(out, "%sFragment:  Address: %d    Number: %d    Size: %d\n",
580                 prefix, inode->i_faddr, frag, fsize);
581         fprintf(out, "%sctime: 0x%08x -- %s", prefix, inode->i_ctime,
582                 time_to_string(inode->i_ctime));
583         fprintf(out, "%satime: 0x%08x -- %s", prefix, inode->i_atime,
584                 time_to_string(inode->i_atime));
585         fprintf(out, "%smtime: 0x%08x -- %s", prefix, inode->i_mtime,
586                 time_to_string(inode->i_mtime));
587         if (inode->i_dtime) 
588           fprintf(out, "%sdtime: 0x%08x -- %s", prefix, inode->i_dtime,
589                   time_to_string(inode->i_dtime));
590         if (EXT2_INODE_SIZE(current_fs->super) > EXT2_GOOD_OLD_INODE_SIZE)
591                 internal_dump_inode_extra(out, prefix, inode_num,
592                                           (struct ext2_inode_large *) inode);
593         if (LINUX_S_ISLNK(inode->i_mode) && ext2fs_inode_data_blocks(current_fs,inode) == 0)
594                 fprintf(out, "%sFast_link_dest: %.*s\n", prefix,
595                         (int) inode->i_size, (char *)inode->i_block);
596         else if (LINUX_S_ISBLK(inode->i_mode) || LINUX_S_ISCHR(inode->i_mode)) {
597                 int major, minor;
598                 const char *devnote;
599
600                 if (inode->i_block[0]) {
601                         major = (inode->i_block[0] >> 8) & 255;
602                         minor = inode->i_block[0] & 255;
603                         devnote = "";
604                 } else {
605                         major = (inode->i_block[1] & 0xfff00) >> 8;
606                         minor = ((inode->i_block[1] & 0xff) | 
607                                  ((inode->i_block[1] >> 12) & 0xfff00));
608                         devnote = "(New-style) ";
609                 }
610                 fprintf(out, "%sDevice major/minor number: %02d:%02d (hex %02x:%02x)\n", 
611                         devnote, major, minor, major, minor);
612         }
613         else if (do_dump_blocks)
614                 dump_blocks(out, prefix, inode_num);
615 }
616
617 static void dump_inode(ext2_ino_t inode_num, struct ext2_inode *inode)
618 {
619         FILE    *out;
620         
621         out = open_pager();
622         internal_dump_inode(out, "", inode_num, inode, 1);
623         close_pager(out);
624 }
625
626 void do_stat(int argc, char *argv[])
627 {
628         ext2_ino_t      inode;
629         struct ext2_inode * inode_buf;
630
631         if (check_fs_open(argv[0]))
632                 return;
633
634         inode_buf = (struct ext2_inode *)
635                         malloc(EXT2_INODE_SIZE(current_fs->super));
636         if (!inode_buf) {
637                 fprintf(stderr, "do_stat: can't allocate buffer\n");
638                 return;
639         }
640
641         if (common_inode_args_process(argc, argv, &inode, 0)) {
642                 free(inode_buf);
643                 return;
644         }
645
646         if (debugfs_read_inode_full(inode, inode_buf, argv[0],
647                                         EXT2_INODE_SIZE(current_fs->super))) {
648                 free(inode_buf);
649                 return;
650         }
651
652         dump_inode(inode, inode_buf);
653         free(inode_buf);
654         return;
655 }
656
657 void do_chroot(int argc, char *argv[])
658 {
659         ext2_ino_t inode;
660         int retval;
661
662         if (common_inode_args_process(argc, argv, &inode, 0))
663                 return;
664
665         retval = ext2fs_check_directory(current_fs, inode);
666         if (retval)  {
667                 com_err(argv[1], retval, 0);
668                 return;
669         }
670         root = inode;
671 }
672
673 void do_clri(int argc, char *argv[])
674 {
675         ext2_ino_t inode;
676         struct ext2_inode inode_buf;
677
678         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
679                 return;
680
681         if (debugfs_read_inode(inode, &inode_buf, argv[0]))
682                 return;
683         memset(&inode_buf, 0, sizeof(inode_buf));
684         if (debugfs_write_inode(inode, &inode_buf, argv[0]))
685                 return;
686 }
687
688 void do_freei(int argc, char *argv[])
689 {
690         ext2_ino_t inode;
691
692         if (common_inode_args_process(argc, argv, &inode,
693                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
694                 return;
695
696         if (!ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
697                 com_err(argv[0], 0, "Warning: inode already clear");
698         ext2fs_unmark_inode_bitmap(current_fs->inode_map,inode);
699         ext2fs_mark_ib_dirty(current_fs);
700 }
701
702 void do_seti(int argc, char *argv[])
703 {
704         ext2_ino_t inode;
705
706         if (common_inode_args_process(argc, argv, &inode,
707                                       CHECK_FS_RW | CHECK_FS_BITMAPS))
708                 return;
709
710         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
711                 com_err(argv[0], 0, "Warning: inode already set");
712         ext2fs_mark_inode_bitmap(current_fs->inode_map,inode);
713         ext2fs_mark_ib_dirty(current_fs);
714 }
715
716 void do_testi(int argc, char *argv[])
717 {
718         ext2_ino_t inode;
719
720         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_BITMAPS))
721                 return;
722
723         if (ext2fs_test_inode_bitmap(current_fs->inode_map,inode))
724                 printf("Inode %u is marked in use\n", inode);
725         else
726                 printf("Inode %u is not in use\n", inode);
727 }
728
729 void do_freeb(int argc, char *argv[])
730 {
731         blk_t block;
732         blk_t count = 1;
733
734         if (common_block_args_process(argc, argv, &block, &count))
735                 return;
736         if (check_fs_read_write(argv[0]))
737                 return;
738         while (count-- > 0) {
739                 if (!ext2fs_test_block_bitmap(current_fs->block_map,block))
740                         com_err(argv[0], 0, "Warning: block %u already clear",
741                                 block);
742                 ext2fs_unmark_block_bitmap(current_fs->block_map,block);
743                 block++;
744         }
745         ext2fs_mark_bb_dirty(current_fs);
746 }
747
748 void do_setb(int argc, char *argv[])
749 {
750         blk_t block;
751         blk_t count = 1;
752
753         if (common_block_args_process(argc, argv, &block, &count))
754                 return;
755         if (check_fs_read_write(argv[0]))
756                 return;
757         while (count-- > 0) {
758                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
759                         com_err(argv[0], 0, "Warning: block %u already set",
760                                 block);
761                 ext2fs_mark_block_bitmap(current_fs->block_map,block);
762                 block++;
763         }
764         ext2fs_mark_bb_dirty(current_fs);
765 }
766
767 void do_testb(int argc, char *argv[])
768 {
769         blk_t block;
770         blk_t count = 1;
771
772         if (common_block_args_process(argc, argv, &block, &count))
773                 return;
774         while (count-- > 0) {
775                 if (ext2fs_test_block_bitmap(current_fs->block_map,block))
776                         printf("Block %u marked in use\n", block);
777                 else
778                         printf("Block %u not in use\n", block);
779                 block++;
780         }
781 }
782
783 static void modify_u8(char *com, const char *prompt,
784                       const char *format, __u8 *val)
785 {
786         char buf[200];
787         unsigned long v;
788         char *tmp;
789
790         sprintf(buf, format, *val);
791         printf("%30s    [%s] ", prompt, buf);
792         if (!fgets(buf, sizeof(buf), stdin))
793                 return;
794         if (buf[strlen (buf) - 1] == '\n')
795                 buf[strlen (buf) - 1] = '\0';
796         if (!buf[0])
797                 return;
798         v = strtoul(buf, &tmp, 0);
799         if (*tmp)
800                 com_err(com, 0, "Bad value - %s", buf);
801         else
802                 *val = v;
803 }
804
805 static void modify_u16(char *com, const char *prompt,
806                        const char *format, __u16 *val)
807 {
808         char buf[200];
809         unsigned long v;
810         char *tmp;
811
812         sprintf(buf, format, *val);
813         printf("%30s    [%s] ", prompt, buf);
814         if (!fgets(buf, sizeof(buf), stdin))
815                 return;
816         if (buf[strlen (buf) - 1] == '\n')
817                 buf[strlen (buf) - 1] = '\0';
818         if (!buf[0])
819                 return;
820         v = strtoul(buf, &tmp, 0);
821         if (*tmp)
822                 com_err(com, 0, "Bad value - %s", buf);
823         else
824                 *val = v;
825 }
826
827 static void modify_u32(char *com, const char *prompt,
828                        const char *format, __u32 *val)
829 {
830         char buf[200];
831         unsigned long v;
832         char *tmp;
833
834         sprintf(buf, format, *val);
835         printf("%30s    [%s] ", prompt, buf);
836         if (!fgets(buf, sizeof(buf), stdin))
837                 return;
838         if (buf[strlen (buf) - 1] == '\n')
839                 buf[strlen (buf) - 1] = '\0';
840         if (!buf[0])
841                 return;
842         v = strtoul(buf, &tmp, 0);
843         if (*tmp)
844                 com_err(com, 0, "Bad value - %s", buf);
845         else
846                 *val = v;
847 }
848
849
850 void do_modify_inode(int argc, char *argv[])
851 {
852         struct ext2_inode inode;
853         ext2_ino_t      inode_num;
854         int             i;
855         unsigned char   *frag, *fsize;
856         char            buf[80];
857         int             os;
858         const char      *hex_format = "0x%x";
859         const char      *octal_format = "0%o";
860         const char      *decimal_format = "%d";
861         const char      *unsignedlong_format = "%lu";
862         
863         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
864                 return;
865
866         os = current_fs->super->s_creator_os;
867
868         if (debugfs_read_inode(inode_num, &inode, argv[1]))
869                 return;
870         
871         modify_u16(argv[0], "Mode", octal_format, &inode.i_mode);
872         modify_u16(argv[0], "User ID", decimal_format, &inode.i_uid);
873         modify_u16(argv[0], "Group ID", decimal_format, &inode.i_gid);
874         modify_u32(argv[0], "Size", unsignedlong_format, &inode.i_size);
875         modify_u32(argv[0], "Creation time", decimal_format, &inode.i_ctime);
876         modify_u32(argv[0], "Modification time", decimal_format, &inode.i_mtime);
877         modify_u32(argv[0], "Access time", decimal_format, &inode.i_atime);
878         modify_u32(argv[0], "Deletion time", decimal_format, &inode.i_dtime);
879         modify_u16(argv[0], "Link count", decimal_format, &inode.i_links_count);
880         if (os == EXT2_OS_LINUX)
881                 modify_u16(argv[0], "Block count high", unsignedlong_format, 
882                            &inode.osd2.linux2.l_i_blocks_hi);
883         modify_u32(argv[0], "Block count", unsignedlong_format, &inode.i_blocks);
884         modify_u32(argv[0], "File flags", hex_format, &inode.i_flags);
885         modify_u32(argv[0], "Generation", hex_format, &inode.i_generation);
886 #if 0
887         modify_u32(argv[0], "Reserved1", decimal_format, &inode.i_reserved1);
888 #endif
889         modify_u32(argv[0], "File acl", decimal_format, &inode.i_file_acl);
890         if (LINUX_S_ISDIR(inode.i_mode))
891                 modify_u32(argv[0], "Directory acl", decimal_format, &inode.i_dir_acl);
892         else
893                 modify_u32(argv[0], "High 32bits of size", decimal_format, &inode.i_size_high);
894
895         if (os == EXT2_OS_HURD)
896                 modify_u32(argv[0], "Translator Block",
897                             decimal_format, &inode.osd1.hurd1.h_i_translator);
898         
899         modify_u32(argv[0], "Fragment address", decimal_format, &inode.i_faddr);
900         switch (os) {
901             case EXT2_OS_HURD:
902                 frag = &inode.osd2.hurd2.h_i_frag;
903                 fsize = &inode.osd2.hurd2.h_i_fsize;
904                 break;
905             case EXT2_OS_MASIX:
906                 frag = &inode.osd2.masix2.m_i_frag;
907                 fsize = &inode.osd2.masix2.m_i_fsize;
908                 break;
909             default:
910                 frag = fsize = 0;
911         }
912         if (frag)
913                 modify_u8(argv[0], "Fragment number", decimal_format, frag);
914         if (fsize)
915                 modify_u8(argv[0], "Fragment size", decimal_format, fsize);
916
917         for (i=0;  i < EXT2_NDIR_BLOCKS; i++) {
918                 sprintf(buf, "Direct Block #%d", i);
919                 modify_u32(argv[0], buf, decimal_format, &inode.i_block[i]);
920         }
921         modify_u32(argv[0], "Indirect Block", decimal_format,
922                     &inode.i_block[EXT2_IND_BLOCK]);    
923         modify_u32(argv[0], "Double Indirect Block", decimal_format,
924                     &inode.i_block[EXT2_DIND_BLOCK]);
925         modify_u32(argv[0], "Triple Indirect Block", decimal_format,
926                     &inode.i_block[EXT2_TIND_BLOCK]);
927         if (debugfs_write_inode(inode_num, &inode, argv[1]))
928                 return;
929 }
930
931 void do_change_working_dir(int argc, char *argv[])
932 {
933         ext2_ino_t      inode;
934         int             retval;
935         
936         if (common_inode_args_process(argc, argv, &inode, 0))
937                 return;
938
939         retval = ext2fs_check_directory(current_fs, inode);
940         if (retval) {
941                 com_err(argv[1], retval, 0);
942                 return;
943         }
944         cwd = inode;
945         return;
946 }
947
948 void do_print_working_directory(int argc, char *argv[])
949 {
950         int     retval;
951         char    *pathname = NULL;
952         
953         if (common_args_process(argc, argv, 1, 1,
954                                 "print_working_directory", "", 0))
955                 return;
956
957         retval = ext2fs_get_pathname(current_fs, cwd, 0, &pathname);
958         if (retval) {
959                 com_err(argv[0], retval,
960                         "while trying to get pathname of cwd");
961         }
962         printf("[pwd]   INODE: %6u  PATH: %s\n",
963                cwd, pathname ? pathname : "NULL");
964         if (pathname) {
965                 free(pathname);
966                 pathname = NULL;
967         }
968         retval = ext2fs_get_pathname(current_fs, root, 0, &pathname);
969         if (retval) {
970                 com_err(argv[0], retval,
971                         "while trying to get pathname of root");
972         }
973         printf("[root]  INODE: %6u  PATH: %s\n",
974                root, pathname ? pathname : "NULL");
975         if (pathname) {
976                 free(pathname);
977                 pathname = NULL;
978         }
979         return;
980 }
981
982 /*
983  * Given a mode, return the ext2 file type
984  */
985 static int ext2_file_type(unsigned int mode)
986 {
987         if (LINUX_S_ISREG(mode))
988                 return EXT2_FT_REG_FILE;
989
990         if (LINUX_S_ISDIR(mode))
991                 return EXT2_FT_DIR;
992         
993         if (LINUX_S_ISCHR(mode))
994                 return EXT2_FT_CHRDEV;
995         
996         if (LINUX_S_ISBLK(mode))
997                 return EXT2_FT_BLKDEV;
998         
999         if (LINUX_S_ISLNK(mode))
1000                 return EXT2_FT_SYMLINK;
1001
1002         if (LINUX_S_ISFIFO(mode))
1003                 return EXT2_FT_FIFO;
1004         
1005         if (LINUX_S_ISSOCK(mode))
1006                 return EXT2_FT_SOCK;
1007         
1008         return 0;
1009 }
1010
1011 static void make_link(char *sourcename, char *destname)
1012 {
1013         ext2_ino_t      ino;
1014         struct ext2_inode inode;
1015         int             retval;
1016         ext2_ino_t      dir;
1017         char            *dest, *cp, *base_name;
1018
1019         /*
1020          * Get the source inode
1021          */
1022         ino = string_to_inode(sourcename);
1023         if (!ino)
1024                 return;
1025         base_name = strrchr(sourcename, '/');
1026         if (base_name)
1027                 base_name++;
1028         else
1029                 base_name = sourcename;
1030         /*
1031          * Figure out the destination.  First see if it exists and is
1032          * a directory.  
1033          */
1034         if (! (retval=ext2fs_namei(current_fs, root, cwd, destname, &dir)))
1035                 dest = base_name;
1036         else {
1037                 /*
1038                  * OK, it doesn't exist.  See if it is
1039                  * '<dir>/basename' or 'basename'
1040                  */
1041                 cp = strrchr(destname, '/');
1042                 if (cp) {
1043                         *cp = 0;
1044                         dir = string_to_inode(destname);
1045                         if (!dir)
1046                                 return;
1047                         dest = cp+1;
1048                 } else {
1049                         dir = cwd;
1050                         dest = destname;
1051                 }
1052         }
1053
1054         if (debugfs_read_inode(ino, &inode, sourcename))
1055                 return;
1056         
1057         retval = ext2fs_link(current_fs, dir, dest, ino, 
1058                              ext2_file_type(inode.i_mode));
1059         if (retval)
1060                 com_err("make_link", retval, 0);
1061         return;
1062 }
1063
1064
1065 void do_link(int argc, char *argv[])
1066 {
1067         if (common_args_process(argc, argv, 3, 3, "link",
1068                                 "<source file> <dest_name>", CHECK_FS_RW))
1069                 return;
1070
1071         make_link(argv[1], argv[2]);
1072 }
1073
1074 static int mark_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1075                             int blockcnt EXT2FS_ATTR((unused)), 
1076                             void *private EXT2FS_ATTR((unused)))
1077 {
1078         blk_t   block;
1079
1080         block = *blocknr;
1081         ext2fs_block_alloc_stats(fs, block, +1);
1082         return 0;
1083 }
1084
1085 void do_undel(int argc, char *argv[])
1086 {
1087         ext2_ino_t      ino;
1088         struct ext2_inode inode;
1089
1090         if (common_args_process(argc, argv, 3, 3, "undelete",
1091                                 "<inode_num> <dest_name>",
1092                                 CHECK_FS_RW | CHECK_FS_BITMAPS))
1093                 return;
1094
1095         ino = string_to_inode(argv[1]);
1096         if (!ino)
1097                 return;
1098
1099         if (debugfs_read_inode(ino, &inode, argv[1]))
1100                 return;
1101
1102         if (ext2fs_test_inode_bitmap(current_fs->inode_map, ino)) {
1103                 com_err(argv[1], 0, "Inode is not marked as deleted");
1104                 return;
1105         }
1106
1107         /*
1108          * XXX this function doesn't handle changing the links count on the
1109          * parent directory when undeleting a directory.  
1110          */
1111         inode.i_links_count = LINUX_S_ISDIR(inode.i_mode) ? 2 : 1;
1112         inode.i_dtime = 0;
1113
1114         if (debugfs_write_inode(ino, &inode, argv[0]))
1115                 return;
1116
1117         ext2fs_block_iterate(current_fs, ino, 0, NULL,
1118                              mark_blocks_proc, NULL);
1119
1120         ext2fs_inode_alloc_stats2(current_fs, ino, +1, 0);
1121
1122         make_link(argv[1], argv[2]);
1123 }
1124
1125 static void unlink_file_by_name(char *filename)
1126 {
1127         int             retval;
1128         ext2_ino_t      dir;
1129         char            *base_name;
1130         
1131         base_name = strrchr(filename, '/');
1132         if (base_name) {
1133                 *base_name++ = '\0';
1134                 dir = string_to_inode(filename);
1135                 if (!dir)
1136                         return;
1137         } else {
1138                 dir = cwd;
1139                 base_name = filename;
1140         }
1141         retval = ext2fs_unlink(current_fs, dir, base_name, 0, 0);
1142         if (retval)
1143                 com_err("unlink_file_by_name", retval, 0);
1144         return;
1145 }
1146
1147 void do_unlink(int argc, char *argv[])
1148 {
1149         if (common_args_process(argc, argv, 2, 2, "link",
1150                                 "<pathname>", CHECK_FS_RW))
1151                 return;
1152
1153         unlink_file_by_name(argv[1]);
1154 }
1155
1156 void do_find_free_block(int argc, char *argv[])
1157 {
1158         blk_t   free_blk, goal;
1159         int             count;
1160         errcode_t       retval;
1161         char            *tmp;
1162         
1163         if ((argc > 3) || (argc==2 && *argv[1] == '?')) {
1164                 com_err(argv[0], 0, "Usage: find_free_block [count [goal]]");
1165                 return;
1166         }
1167         if (check_fs_open(argv[0]))
1168                 return;
1169
1170         if (argc > 1) {
1171                 count = strtol(argv[1],&tmp,0);
1172                 if (*tmp) {
1173                         com_err(argv[0], 0, "Bad count - %s", argv[1]);
1174                         return;
1175                 }
1176         } else
1177                 count = 1;
1178
1179         if (argc > 2) {
1180                 goal = strtol(argv[2], &tmp, 0);
1181                 if (*tmp) {
1182                         com_err(argv[0], 0, "Bad goal - %s", argv[1]);
1183                         return;
1184                 }
1185         }
1186         else
1187                 goal = current_fs->super->s_first_data_block;
1188
1189         printf("Free blocks found: ");
1190         free_blk = goal - 1;    
1191         while (count-- > 0) {
1192                 retval = ext2fs_new_block(current_fs, free_blk + 1, 0,
1193                                           &free_blk);
1194                 if (retval) {
1195                         com_err("ext2fs_new_block", retval, 0);
1196                         return;
1197                 } else
1198                         printf("%u ", free_blk);
1199         }
1200         printf("\n");
1201 }
1202
1203 void do_find_free_inode(int argc, char *argv[])
1204 {
1205         ext2_ino_t      free_inode, dir;
1206         int             mode;
1207         int             retval;
1208         char            *tmp;
1209         
1210         if (argc > 3 || (argc>1 && *argv[1] == '?')) {
1211                 com_err(argv[0], 0, "Usage: find_free_inode [dir] [mode]");
1212                 return;
1213         }
1214         if (check_fs_open(argv[0]))
1215                 return;
1216
1217         if (argc > 1) {
1218                 dir = strtol(argv[1], &tmp, 0);
1219                 if (*tmp) {
1220                         com_err(argv[0], 0, "Bad dir - %s", argv[1]);
1221                         return;
1222                 }
1223         }
1224         else
1225                 dir = root;
1226         if (argc > 2) {
1227                 mode = strtol(argv[2], &tmp, 0);
1228                 if (*tmp) {
1229                         com_err(argv[0], 0, "Bad mode - %s", argv[2]);
1230                         return;
1231                 }
1232         } else
1233                 mode = 010755;
1234
1235         retval = ext2fs_new_inode(current_fs, dir, mode, 0, &free_inode);
1236         if (retval)
1237                 com_err("ext2fs_new_inode", retval, 0);
1238         else
1239                 printf("Free inode found: %u\n", free_inode);
1240 }
1241
1242 static errcode_t copy_file(int fd, ext2_ino_t newfile)
1243 {
1244         ext2_file_t     e2_file;
1245         errcode_t       retval;
1246         int             got;
1247         unsigned int    written;
1248         char            buf[8192];
1249         char            *ptr;
1250
1251         retval = ext2fs_file_open(current_fs, newfile,
1252                                   EXT2_FILE_WRITE, &e2_file);
1253         if (retval)
1254                 return retval;
1255
1256         while (1) {
1257                 got = read(fd, buf, sizeof(buf));
1258                 if (got == 0)
1259                         break;
1260                 if (got < 0) {
1261                         retval = errno;
1262                         goto fail;
1263                 }
1264                 ptr = buf;
1265                 while (got > 0) {
1266                         retval = ext2fs_file_write(e2_file, ptr,
1267                                                    got, &written);
1268                         if (retval)
1269                                 goto fail;
1270
1271                         got -= written;
1272                         ptr += written;
1273                 }
1274         }
1275         retval = ext2fs_file_close(e2_file);
1276         return retval;
1277
1278 fail:
1279         (void) ext2fs_file_close(e2_file);
1280         return retval;
1281 }
1282
1283
1284 void do_write(int argc, char *argv[])
1285 {
1286         int             fd;
1287         struct stat     statbuf;
1288         ext2_ino_t      newfile;
1289         errcode_t       retval;
1290         struct ext2_inode inode;
1291
1292         if (common_args_process(argc, argv, 3, 3, "write",
1293                                 "<native file> <new file>", CHECK_FS_RW))
1294                 return;
1295
1296         fd = open(argv[1], O_RDONLY);
1297         if (fd < 0) {
1298                 com_err(argv[1], errno, 0);
1299                 return;
1300         }
1301         if (fstat(fd, &statbuf) < 0) {
1302                 com_err(argv[1], errno, 0);
1303                 close(fd);
1304                 return;
1305         }
1306
1307         retval = ext2fs_namei(current_fs, root, cwd, argv[2], &newfile);
1308         if (retval == 0) {
1309                 com_err(argv[0], 0, "The file '%s' already exists\n", argv[2]);
1310                 close(fd);
1311                 return;
1312         }
1313
1314         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1315         if (retval) {
1316                 com_err(argv[0], retval, 0);
1317                 close(fd);
1318                 return;
1319         }
1320         printf("Allocated inode: %u\n", newfile);
1321         retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1322                              EXT2_FT_REG_FILE);
1323         if (retval == EXT2_ET_DIR_NO_SPACE) {
1324                 retval = ext2fs_expand_dir(current_fs, cwd);
1325                 if (retval) {
1326                         com_err(argv[0], retval, "while expanding directory");
1327                         return;
1328                 }
1329                 retval = ext2fs_link(current_fs, cwd, argv[2], newfile,
1330                                      EXT2_FT_REG_FILE);
1331         }
1332         if (retval) {
1333                 com_err(argv[2], retval, 0);
1334                 close(fd);
1335                 return;
1336         }
1337         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1338                 com_err(argv[0], 0, "Warning: inode already set");
1339         ext2fs_inode_alloc_stats2(current_fs, newfile, +1, 0);
1340         memset(&inode, 0, sizeof(inode));
1341         inode.i_mode = (statbuf.st_mode & ~LINUX_S_IFMT) | LINUX_S_IFREG;
1342         inode.i_atime = inode.i_ctime = inode.i_mtime = 
1343                 current_fs->now ? current_fs->now : time(0);
1344         inode.i_links_count = 1;
1345         inode.i_size = statbuf.st_size;
1346         if (debugfs_write_new_inode(newfile, &inode, argv[0])) {
1347                 close(fd);
1348                 return;
1349         }
1350         if (LINUX_S_ISREG(inode.i_mode)) {
1351                 retval = copy_file(fd, newfile);
1352                 if (retval)
1353                         com_err("copy_file", retval, 0);
1354         }
1355         close(fd);
1356 }
1357
1358 void do_mknod(int argc, char *argv[])
1359 {
1360         unsigned long   mode, major, minor;
1361         ext2_ino_t      newfile;
1362         errcode_t       retval;
1363         struct ext2_inode inode;
1364         int             filetype, nr;
1365
1366         if (check_fs_open(argv[0]))
1367                 return;
1368         if (argc < 3 || argv[2][1]) {
1369         usage:
1370                 com_err(argv[0], 0, "Usage: mknod <name> [p| [c|b] <major> <minor>]");
1371                 return;
1372         }
1373         mode = minor = major = 0;
1374         switch (argv[2][0]) {
1375                 case 'p':
1376                         mode = LINUX_S_IFIFO;
1377                         filetype = EXT2_FT_FIFO;
1378                         nr = 3;
1379                         break;
1380                 case 'c':
1381                         mode = LINUX_S_IFCHR;
1382                         filetype = EXT2_FT_CHRDEV;
1383                         nr = 5;
1384                         break;
1385                 case 'b':
1386                         mode = LINUX_S_IFBLK;
1387                         filetype = EXT2_FT_BLKDEV;
1388                         nr = 5;
1389                         break;
1390                 default:
1391                         filetype = 0;
1392                         nr = 0;
1393         }
1394         if (nr == 5) {
1395                 major = strtoul(argv[3], argv+3, 0);
1396                 minor = strtoul(argv[4], argv+4, 0);
1397                 if (major > 65535 || minor > 65535 || argv[3][0] || argv[4][0])
1398                         nr = 0;
1399         }
1400         if (argc != nr)
1401                 goto usage;
1402         if (check_fs_read_write(argv[0]))
1403                 return;
1404         retval = ext2fs_new_inode(current_fs, cwd, 010755, 0, &newfile);
1405         if (retval) {
1406                 com_err(argv[0], retval, 0);
1407                 return;
1408         }
1409         printf("Allocated inode: %u\n", newfile);
1410         retval = ext2fs_link(current_fs, cwd, argv[1], newfile, filetype);
1411         if (retval == EXT2_ET_DIR_NO_SPACE) {
1412                 retval = ext2fs_expand_dir(current_fs, cwd);
1413                 if (retval) {
1414                         com_err(argv[0], retval, "while expanding directory");
1415                         return;
1416                 }
1417                 retval = ext2fs_link(current_fs, cwd, argv[1], newfile,
1418                                      filetype);
1419         }
1420         if (retval) {
1421                 com_err(argv[1], retval, 0);
1422                 return;
1423         }
1424         if (ext2fs_test_inode_bitmap(current_fs->inode_map,newfile))
1425                 com_err(argv[0], 0, "Warning: inode already set");
1426         ext2fs_mark_inode_bitmap(current_fs->inode_map, newfile);
1427         ext2fs_mark_ib_dirty(current_fs);
1428         memset(&inode, 0, sizeof(inode));
1429         inode.i_mode = mode;
1430         inode.i_atime = inode.i_ctime = inode.i_mtime = 
1431                 current_fs->now ? current_fs->now : time(0);
1432         if ((major < 256) && (minor < 256)) {
1433                 inode.i_block[0] = major*256+minor;
1434                 inode.i_block[1] = 0;
1435         } else {
1436                 inode.i_block[0] = 0;
1437                 inode.i_block[1] = (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
1438         }
1439         inode.i_links_count = 1;
1440         if (debugfs_write_new_inode(newfile, &inode, argv[0]))
1441                 return;
1442 }
1443
1444 void do_mkdir(int argc, char *argv[])
1445 {
1446         char    *cp;
1447         ext2_ino_t      parent;
1448         char    *name;
1449         errcode_t retval;
1450
1451         if (common_args_process(argc, argv, 2, 2, "mkdir",
1452                                 "<filename>", CHECK_FS_RW))
1453                 return;
1454
1455         cp = strrchr(argv[1], '/');
1456         if (cp) {
1457                 *cp = 0;
1458                 parent = string_to_inode(argv[1]);
1459                 if (!parent) {
1460                         com_err(argv[1], ENOENT, 0);
1461                         return;
1462                 }
1463                 name = cp+1;
1464         } else {
1465                 parent = cwd;
1466                 name = argv[1];
1467         }
1468
1469 try_again:
1470         retval = ext2fs_mkdir(current_fs, parent, 0, name);
1471         if (retval == EXT2_ET_DIR_NO_SPACE) {
1472                 retval = ext2fs_expand_dir(current_fs, parent);
1473                 if (retval) {
1474                         com_err("argv[0]", retval, "while expanding directory");
1475                         return;
1476                 }
1477                 goto try_again;
1478         }
1479         if (retval) {
1480                 com_err("ext2fs_mkdir", retval, 0);
1481                 return;
1482         }
1483
1484 }
1485
1486 static int release_blocks_proc(ext2_filsys fs, blk_t *blocknr,
1487                                int blockcnt EXT2FS_ATTR((unused)), 
1488                                void *private EXT2FS_ATTR((unused)))
1489 {
1490         blk_t   block;
1491
1492         block = *blocknr;
1493         ext2fs_block_alloc_stats(fs, block, -1);
1494         return 0;
1495 }
1496
1497 static void kill_file_by_inode(ext2_ino_t inode)
1498 {
1499         struct ext2_inode inode_buf;
1500
1501         if (debugfs_read_inode(inode, &inode_buf, 0))
1502                 return;
1503         inode_buf.i_dtime = current_fs->now ? current_fs->now : time(0);
1504         if (debugfs_write_inode(inode, &inode_buf, 0))
1505                 return;
1506         if (!ext2fs_inode_has_valid_blocks(&inode_buf))
1507                 return;
1508
1509         ext2fs_block_iterate(current_fs, inode, 0, NULL,
1510                              release_blocks_proc, NULL);
1511         printf("\n");
1512         ext2fs_inode_alloc_stats2(current_fs, inode, -1,
1513                                   LINUX_S_ISDIR(inode_buf.i_mode));
1514 }
1515
1516
1517 void do_kill_file(int argc, char *argv[])
1518 {
1519         ext2_ino_t inode_num;
1520
1521         if (common_inode_args_process(argc, argv, &inode_num, CHECK_FS_RW))
1522                 return;
1523
1524         kill_file_by_inode(inode_num);
1525 }
1526
1527 void do_rm(int argc, char *argv[])
1528 {
1529         int retval;
1530         ext2_ino_t inode_num;
1531         struct ext2_inode inode;
1532
1533         if (common_args_process(argc, argv, 2, 2, "rm",
1534                                 "<filename>", CHECK_FS_RW))
1535                 return;
1536
1537         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1538         if (retval) {
1539                 com_err(argv[0], retval, "while trying to resolve filename");
1540                 return;
1541         }
1542
1543         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1544                 return;
1545
1546         if (LINUX_S_ISDIR(inode.i_mode)) {
1547                 com_err(argv[0], 0, "file is a directory");
1548                 return;
1549         }
1550
1551         --inode.i_links_count;
1552         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1553                 return;
1554
1555         unlink_file_by_name(argv[1]);
1556         if (inode.i_links_count == 0)
1557                 kill_file_by_inode(inode_num);
1558 }
1559
1560 struct rd_struct {
1561         ext2_ino_t      parent;
1562         int             empty;
1563 };
1564
1565 static int rmdir_proc(ext2_ino_t dir EXT2FS_ATTR((unused)),
1566                       int       entry EXT2FS_ATTR((unused)),
1567                       struct ext2_dir_entry *dirent,
1568                       int       offset EXT2FS_ATTR((unused)),
1569                       int       blocksize EXT2FS_ATTR((unused)),
1570                       char      *buf EXT2FS_ATTR((unused)),
1571                       void      *private)
1572 {
1573         struct rd_struct *rds = (struct rd_struct *) private;
1574
1575         if (dirent->inode == 0)
1576                 return 0;
1577         if (((dirent->name_len&0xFF) == 1) && (dirent->name[0] == '.'))
1578                 return 0;
1579         if (((dirent->name_len&0xFF) == 2) && (dirent->name[0] == '.') &&
1580             (dirent->name[1] == '.')) {
1581                 rds->parent = dirent->inode;
1582                 return 0;
1583         }
1584         rds->empty = 0;
1585         return 0;
1586 }
1587         
1588 void do_rmdir(int argc, char *argv[])
1589 {
1590         int retval;
1591         ext2_ino_t inode_num;
1592         struct ext2_inode inode;
1593         struct rd_struct rds;
1594
1595         if (common_args_process(argc, argv, 2, 2, "rmdir",
1596                                 "<filename>", CHECK_FS_RW))
1597                 return;
1598
1599         retval = ext2fs_namei(current_fs, root, cwd, argv[1], &inode_num);
1600         if (retval) {
1601                 com_err(argv[0], retval, "while trying to resolve filename");
1602                 return;
1603         }
1604
1605         if (debugfs_read_inode(inode_num, &inode, argv[0]))
1606                 return;
1607
1608         if (!LINUX_S_ISDIR(inode.i_mode)) {
1609                 com_err(argv[0], 0, "file is not a directory");
1610                 return;
1611         }
1612
1613         rds.parent = 0;
1614         rds.empty = 1;
1615
1616         retval = ext2fs_dir_iterate2(current_fs, inode_num, 0,
1617                                     0, rmdir_proc, &rds);
1618         if (retval) {
1619                 com_err(argv[0], retval, "while iterating over directory");
1620                 return;
1621         }
1622         if (rds.empty == 0) {
1623                 com_err(argv[0], 0, "directory not empty");
1624                 return;
1625         }
1626
1627         inode.i_links_count = 0;
1628         if (debugfs_write_inode(inode_num, &inode, argv[0]))
1629                 return;
1630
1631         unlink_file_by_name(argv[1]);
1632         kill_file_by_inode(inode_num);
1633
1634         if (rds.parent) {
1635                 if (debugfs_read_inode(rds.parent, &inode, argv[0]))
1636                         return;
1637                 if (inode.i_links_count > 1)
1638                         inode.i_links_count--;
1639                 if (debugfs_write_inode(rds.parent, &inode, argv[0]))
1640                         return;
1641         }
1642 }
1643
1644 void do_show_debugfs_params(int argc EXT2FS_ATTR((unused)), 
1645                             char *argv[] EXT2FS_ATTR((unused)))
1646 {
1647         FILE *out = stdout;
1648
1649         if (current_fs)
1650                 fprintf(out, "Open mode: read-%s\n",
1651                         current_fs->flags & EXT2_FLAG_RW ? "write" : "only");
1652         fprintf(out, "Filesystem in use: %s\n",
1653                 current_fs ? current_fs->device_name : "--none--");
1654 }
1655
1656 void do_expand_dir(int argc, char *argv[])
1657 {
1658         ext2_ino_t inode;
1659         int retval;
1660
1661         if (common_inode_args_process(argc, argv, &inode, CHECK_FS_RW))
1662                 return;
1663
1664         retval = ext2fs_expand_dir(current_fs, inode);
1665         if (retval)
1666                 com_err("ext2fs_expand_dir", retval, 0);
1667         return;
1668 }
1669
1670 void do_features(int argc, char *argv[])
1671 {
1672         int     i;
1673         
1674         if (check_fs_open(argv[0]))
1675                 return;
1676
1677         if ((argc != 1) && check_fs_read_write(argv[0]))
1678                 return;
1679         for (i=1; i < argc; i++) {
1680                 if (e2p_edit_feature(argv[i],
1681                                      &current_fs->super->s_feature_compat, 0))
1682                         com_err(argv[0], 0, "Unknown feature: %s\n",
1683                                 argv[i]);
1684                 else
1685                         ext2fs_mark_super_dirty(current_fs);
1686         }
1687         print_features(current_fs->super, stdout);
1688 }
1689
1690 void do_bmap(int argc, char *argv[])
1691 {
1692         ext2_ino_t      ino;
1693         blk_t           blk, pblk;
1694         int             err;
1695         errcode_t       errcode;
1696         
1697         if (common_args_process(argc, argv, 3, 3, argv[0],
1698                                 "<file> logical_blk", 0))
1699                 return;
1700
1701         ino = string_to_inode(argv[1]);
1702         if (!ino)
1703                 return;
1704         blk = parse_ulong(argv[2], argv[0], "logical_block", &err);
1705
1706         errcode = ext2fs_bmap(current_fs, ino, 0, 0, 0, blk, &pblk);
1707         if (errcode) {
1708                 com_err("argv[0]", errcode,
1709                         "while mapping logical block %u\n", blk);
1710                 return;
1711         }
1712         printf("%u\n", pblk);
1713 }
1714
1715 void do_imap(int argc, char *argv[])
1716 {
1717         ext2_ino_t      ino;
1718         unsigned long   group, block, block_nr, offset;
1719
1720         if (common_args_process(argc, argv, 2, 2, argv[0],
1721                                 "<file>", 0))
1722                 return;
1723         ino = string_to_inode(argv[1]);
1724         if (!ino)
1725                 return;
1726
1727         group = (ino - 1) / EXT2_INODES_PER_GROUP(current_fs->super);
1728         offset = ((ino - 1) % EXT2_INODES_PER_GROUP(current_fs->super)) *
1729                 EXT2_INODE_SIZE(current_fs->super);
1730         block = offset >> EXT2_BLOCK_SIZE_BITS(current_fs->super);
1731         if (!current_fs->group_desc[(unsigned)group].bg_inode_table) {
1732                 com_err(argv[0], 0, "Inode table for group %lu is missing\n",
1733                         group);
1734                 return;
1735         }
1736         block_nr = current_fs->group_desc[(unsigned)group].bg_inode_table + 
1737                 block;
1738         offset &= (EXT2_BLOCK_SIZE(current_fs->super) - 1);
1739
1740         printf("Inode %d is part of block group %lu\n"
1741                "\tlocated at block %lu, offset 0x%04lx\n", ino, group,
1742                block_nr, offset);
1743
1744 }
1745
1746 void do_set_current_time(int argc, char *argv[])
1747 {
1748         time_t now;
1749
1750         if (common_args_process(argc, argv, 2, 2, argv[0],
1751                                 "<time>", 0))
1752                 return;
1753
1754         now = string_to_time(argv[1]);
1755         if (now == ((time_t) -1)) {
1756                 com_err(argv[0], 0, "Couldn't parse argument as a time: %s\n",
1757                         argv[1]);
1758                 return;
1759
1760         } else {
1761                 printf("Setting current time to %s\n", time_to_string(now));
1762                 current_fs->now = now;
1763         }
1764 }
1765
1766 static int source_file(const char *cmd_file, int sci_idx)
1767 {
1768         FILE            *f;
1769         char            buf[256];
1770         char            *cp;
1771         int             exit_status = 0;
1772         int             retval;
1773
1774         if (strcmp(cmd_file, "-") == 0)
1775                 f = stdin;
1776         else {
1777                 f = fopen(cmd_file, "r");
1778                 if (!f) {
1779                         perror(cmd_file);
1780                         exit(1);
1781                 }
1782         }
1783         setbuf(stdout, NULL);
1784         setbuf(stderr, NULL);
1785         while (!feof(f)) {
1786                 if (fgets(buf, sizeof(buf), f) == NULL)
1787                         break;
1788                 cp = strchr(buf, '\n');
1789                 if (cp)
1790                         *cp = 0;
1791                 cp = strchr(buf, '\r');
1792                 if (cp)
1793                         *cp = 0;
1794                 printf("debugfs: %s\n", buf);
1795                 retval = ss_execute_line(sci_idx, buf);
1796                 if (retval) {
1797                         ss_perror(sci_idx, retval, buf);
1798                         exit_status++;
1799                 }
1800         }
1801         return exit_status;
1802 }
1803
1804 int main(int argc, char **argv)
1805 {
1806         int             retval;
1807         int             sci_idx;
1808         const char      *usage = "Usage: debugfs [-b blocksize] [-s superblock] [-f cmd_file] [-R request] [-V] [[-w] [-c] device]";
1809         int             c;
1810         int             open_flags = EXT2_FLAG_SOFTSUPP_FEATURES;
1811         char            *request = 0;
1812         int             exit_status = 0;
1813         char            *cmd_file = 0;
1814         blk_t           superblock = 0;
1815         blk_t           blocksize = 0;
1816         int             catastrophic = 0;
1817         char            *data_filename = 0;
1818         
1819         add_error_table(&et_ext2_error_table);
1820         fprintf (stderr, "debugfs %s (%s)\n", E2FSPROGS_VERSION,
1821                  E2FSPROGS_DATE);
1822
1823         while ((c = getopt (argc, argv, "iwcR:f:b:s:Vd:")) != EOF) {
1824                 switch (c) {
1825                 case 'R':
1826                         request = optarg;
1827                         break;
1828                 case 'f':
1829                         cmd_file = optarg;
1830                         break;
1831                 case 'd':
1832                         data_filename = optarg;
1833                         break;
1834                 case 'i':
1835                         open_flags |= EXT2_FLAG_IMAGE_FILE;
1836                         break;
1837                 case 'w':
1838                         open_flags |= EXT2_FLAG_RW;
1839                         break;
1840                 case 'b':
1841                         blocksize = parse_ulong(optarg, argv[0], 
1842                                                 "block size", 0);
1843                         break;
1844                 case 's':
1845                         superblock = parse_ulong(optarg, argv[0], 
1846                                                  "superblock number", 0);
1847                         break;
1848                 case 'c':
1849                         catastrophic = 1;
1850                         break;
1851                 case 'V':
1852                         /* Print version number and exit */
1853                         fprintf(stderr, "\tUsing %s\n",
1854                                 error_message(EXT2_ET_BASE));
1855                         exit(0);
1856                 default:
1857                         com_err(argv[0], 0, usage);
1858                         return 1;
1859                 }
1860         }
1861         if (optind < argc)
1862                 open_filesystem(argv[optind], open_flags,
1863                                 superblock, blocksize, catastrophic,
1864                                 data_filename);
1865         
1866         sci_idx = ss_create_invocation("debugfs", "0.0", (char *) NULL,
1867                                        &debug_cmds, &retval);
1868         if (retval) {
1869                 ss_perror(sci_idx, retval, "creating invocation");
1870                 exit(1);
1871         }
1872         ss_get_readline(sci_idx);
1873
1874         (void) ss_add_request_table (sci_idx, &ss_std_requests, 1, &retval);
1875         if (retval) {
1876                 ss_perror(sci_idx, retval, "adding standard requests");
1877                 exit (1);
1878         }
1879         if (request) {
1880                 retval = 0;
1881                 retval = ss_execute_line(sci_idx, request);
1882                 if (retval) {
1883                         ss_perror(sci_idx, retval, request);
1884                         exit_status++;
1885                 }
1886         } else if (cmd_file) {
1887                 exit_status = source_file(cmd_file, sci_idx);
1888         } else {
1889                 ss_listen(sci_idx);
1890         }
1891
1892         if (current_fs)
1893                 close_filesystem();
1894         
1895         remove_error_table(&et_ext2_error_table);
1896         return exit_status;
1897 }