s/disk_sector_no/disk_sector_t/g
[pintos-anon] / src / filesys / fsutil.c
1 #include "fsutil.h"
2 #include <stdbool.h>
3 #include "debug.h"
4 #include "filesys.h"
5 #include "file.h"
6 #include "lib.h"
7 #include "mmu.h"
8 #include "palloc.h"
9
10 char *fsutil_copy_arg;
11 char *fsutil_print_file;
12 char *fsutil_remove_file;
13 bool fsutil_list_files;
14 bool fsutil_dump_filesys;
15
16 static void
17 copy (const char *filename, off_t size) 
18 {
19   struct disk *src;
20   struct file dst;
21   disk_sector_t sector;
22   void *buffer;
23
24   /* Open source disk. */
25   src = disk_get (1, 0);
26   if (src == NULL)
27     PANIC ("couldn't open source disk (hdc or hd1:0)");
28   if (size > (off_t) disk_size (src) * DISK_SECTOR_SIZE)
29     PANIC ("source disk is too small for %Ld-byte file",
30            (unsigned long long) size);
31   
32   /* Create destination file. */
33   if (!filesys_create (filename, size))
34     PANIC ("%s: create failed", filename);
35   if (!filesys_open (filename, &dst))
36     PANIC ("%s: open failed", filename);
37
38   /* Do copy. */
39   buffer = palloc_get (PAL_ASSERT);
40   sector = 0;
41   while (size > 0)
42     {
43       int chunk_size = size > DISK_SECTOR_SIZE ? DISK_SECTOR_SIZE : size;
44       disk_read (src, sector++, buffer);
45       if (file_write (&dst, buffer, chunk_size) != chunk_size)
46         PANIC ("%s: write failed with %Ld bytes unwritten",
47                filename, (unsigned long long) size);
48       size -= chunk_size;
49     }
50   palloc_free (buffer);
51
52   file_close (&dst);
53 }
54
55 void
56 fsutil_run (void) 
57 {
58   if (fsutil_copy_arg != NULL) 
59     {
60       char *save;
61       char *filename = strtok_r (fsutil_copy_arg, ":", &save);
62       char *size = strtok_r (NULL, "", &save);
63
64       if (filename == NULL || size == NULL)
65         PANIC ("bad format for -cp option; use -u for usage");
66
67       copy (filename, atoi (size));
68     }
69
70   if (fsutil_print_file != NULL)
71     fsutil_print (fsutil_print_file);
72
73   if (fsutil_remove_file != NULL) 
74     {
75       if (filesys_remove (fsutil_remove_file))
76         printk ("%s: removed\n", fsutil_remove_file);
77       else
78         PANIC ("%s: remove failed\n", fsutil_remove_file);
79     }
80
81   if (fsutil_list_files)
82     filesys_list ();
83
84   if (fsutil_dump_filesys)
85     filesys_dump ();
86 }
87
88 void
89 fsutil_print (const char *filename) 
90 {
91   struct file file;
92   char *buffer;
93
94   if (!filesys_open (filename, &file))
95     PANIC ("%s: open failed", filename);
96   buffer = palloc_get (PAL_ASSERT);
97   for (;;) 
98     {
99       off_t n = file_read (&file, buffer, PGSIZE);
100       if (n == 0)
101         break;
102
103       hex_dump (buffer, n, true);
104     }
105   palloc_free (buffer);
106   file_close (&file);
107 }