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#define FOR_du
40#include "toys.h"
41
42GLOBALS(
43 long d;
44
45 unsigned long depth, total;
46 dev_t st_dev;
47 void *inodes;
48)
49
50typedef struct node_size {
51 struct dirtree *node;
52 long size;
53} node_size;
54
55
56static void print(long long size, struct dirtree *node)
57{
58 char *name = "total";
59
60 if (TT.depth > TT.d) return;
61
62 if (FLAG(h)) {
63 human_readable(toybuf, size, 0);
64 printf("%s", toybuf);
65 } else {
66 int bits = 10;
67
68 if (FLAG(K)) bits = 9;
69 else if (FLAG(m)) bits = 20;
70
71 if (FLAG(b) && bits == 10 && !FLAG(k)) printf("%llu", size);
72 else printf("%llu", (size>>bits)+!!(size&((1<<bits)-1)));
73 }
74 if (node) name = dirtree_path(node, NULL);
75 xprintf("\t%s\n", name);
76 if (node) free(name);
77}
78
79
80
81static int seen_inode(void **list, struct stat *st)
82{
83 if (!st) llist_traverse(st, free);
84
85
86
87
88
89 else if (!S_ISDIR(st->st_mode) && st->st_nlink > 1) {
90 struct inode_list {
91 struct inode_list *next;
92 ino_t ino;
93 dev_t dev;
94 } *new;
95
96 for (new = *list; new; new = new->next)
97 if(new->ino == st->st_ino && new->dev == st->st_dev)
98 return 1;
99
100 new = xzalloc(sizeof(*new));
101 new->ino = st->st_ino;
102 new->dev = st->st_dev;
103 new->next = *list;
104 *list = new;
105 }
106
107 return 0;
108}
109
110
111static int do_du(struct dirtree *node)
112{
113 unsigned long blocks;
114
115 if (!node->parent) TT.st_dev = node->st.st_dev;
116 else if (!dirtree_notdotdot(node)) return 0;
117
118
119 if (FLAG(x) && (TT.st_dev != node->st.st_dev))
120 return 0;
121
122
123 if (FLAG(L)) {
124 struct dirtree *try = node;
125
126 while ((try = try->parent))
127 if (node->st.st_dev==try->st.st_dev && node->st.st_ino==try->st.st_ino)
128 return 0;
129 }
130
131
132 if (!FLAG(l) && !node->again)
133 if (seen_inode(&TT.inodes, &node->st)) return 0;
134
135
136 if (S_ISDIR(node->st.st_mode)) {
137 if (!node->again) {
138 TT.depth++;
139 return DIRTREE_COMEAGAIN|(DIRTREE_SYMFOLLOW*!!FLAG(L));
140 } else TT.depth--;
141 }
142
143
144
145 blocks = FLAG(b) ? node->st.st_size : node->st.st_blocks;
146 blocks += (unsigned long)node->extra;
147 node->extra = blocks;
148 if (node->parent)
149 node->parent->extra = (unsigned long)node->parent->extra+blocks;
150 else TT.total += node->extra;
151
152 if (FLAG(a) || !node->parent || (S_ISDIR(node->st.st_mode) && !FLAG(s))) {
153 blocks = node->extra;
154 print(FLAG(b) ? blocks : blocks*512LL, node);
155 }
156
157 return 0;
158}
159
160void du_main(void)
161{
162 char *noargs[] = {".", 0}, **args;
163
164
165 for (args = toys.optc ? toys.optargs : noargs; *args; args++)
166 dirtree_flagread(*args, DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L)),
167 do_du);
168 if (FLAG(c)) print(FLAG(b) ? TT.total : TT.total*512, 0);
169
170 if (CFG_TOYBOX_FREE) seen_inode(TT.inodes, 0);
171}
172