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
|
# Code Style — Corebinutils Conventions
## Overview
The corebinutils codebase follows FreeBSD kernel style (KNF) with
Linux-specific adaptations. This document catalogs the coding
conventions observed across all utilities.
## File Organization
### Standard File Layout
```c
/*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) YYYY Project Tick
* Copyright (c) YYYY The Regents of the University of California.
* All rights reserved.
*
* Redistribution notice ...
*/
/* System headers (alphabetical) */
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Local headers */
#include "utility.h"
/* Macros */
#define BUFSIZE (128 * 1024)
/* Types and structs */
struct options { ... };
/* Static function prototypes */
static void usage(void);
/* Static globals */
static const char *progname;
/* Functions (main last or first, utility-dependent) */
```
### Header Guard Style
```c
/* No #pragma once — uses traditional guards */
#ifndef _DD_H_
#define _DD_H_
/* ... */
#endif /* !_DD_H_ */
```
## Naming Conventions
### Functions
- **Lowercase with underscores**: `parse_args()`, `copy_file_data()`
- **Static for file-scope**: All non-`main` functions are `static` unless
needed by other translation units
- **Verb-first**: `read_file()`, `write_output()`, `parse_duration()`
- **Predicate prefix**: `is_directory()`, `should_recurse()`, `has_flag()`
### Variables
- **Short names in small scopes**: `n`, `p`, `ch`, `sb`, `dp`
- **Descriptive names in structs**: `suppress_newline`, `follow_mode`
- **Constants as macros**: `BUFSIZE`, `EXIT_TIMEOUT`, `COMMLEN`
- **Global flags**: Single-word or abbreviated: `verbose`, `force`, `rflag`
### Struct Naming
```c
/* Tagged structs (no typedef for most) */
struct options { ... };
struct mount_entry { ... };
/* Typedefs only for opaque or complex types */
typedef struct line line_t;
typedef struct { ... } bitcmd_t;
typedef regex_t pattern_t;
```
## Option Processing
### getopt(3) Pattern
```c
while ((ch = getopt(argc, argv, "fhilnRsvwx")) != -1) {
switch (ch) {
case 'f':
opts.force = true;
break;
case 'v':
opts.verbose = true;
break;
/* ... */
default:
usage();
}
}
argc -= optind;
argv += optind;
```
### getopt_long(3) Pattern
```c
static const struct option long_options[] = {
{"color", optional_argument, NULL, 'G'},
{"group-directories-first", no_argument, NULL, OPT_GROUPDIRS},
{NULL, 0, NULL, 0},
};
while ((ch = getopt_long(argc, argv, optstring,
long_options, NULL)) != -1) { ... }
```
### Manual Parsing (echo)
```c
/* When getopt is too heavy */
while (*argv && strcmp(*argv, "-n") == 0) {
suppress_newline = true;
argv++;
}
```
## Error Handling
### BSD err(3) Family
```c
#include <err.h>
err(1, "open '%s'", path); /* perror-style with exit */
errx(2, "invalid mode: %s", s); /* No errno, with exit */
warn("stat '%s'", path); /* perror-style, no exit */
warnx("skipping '%s'", path); /* No errno, no exit */
```
### Custom Error Functions
Many utilities define their own for consistency:
```c
static void
error_errno(const char *fmt, ...)
{
int saved = errno;
va_list ap;
fprintf(stderr, "%s: ", progname);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, ": %s\n", strerror(saved));
}
static void
error_msg(const char *fmt, ...)
{
va_list ap;
fprintf(stderr, "%s: ", progname);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
}
```
### Usage Functions
```c
static void __dead2 /* noreturn attribute */
usage(void)
{
fprintf(stderr, "usage: %s [-fiv] source target\n", progname);
exit(2);
}
```
## Memory Management
### Dynamic Allocation Patterns
```c
/* Always check allocation */
char *buf = malloc(size);
if (buf == NULL)
err(1, "malloc");
/* strdup with check */
char *copy = strdup(str);
if (copy == NULL)
err(1, "strdup");
/* Adaptive buffer sizing */
size_t bufsize = BUFSIZE_MAX;
while (bufsize >= BUFSIZE_MIN) {
buf = malloc(bufsize);
if (buf) break;
bufsize /= 2;
}
```
### No Global malloc/free Tracking
Utilities that process-exit after completion do not free final
allocations — the OS reclaims all memory. Early-exit utilities
(cat, echo, pwd) rely on this.
## Portability Patterns
### Conditional Compilation
```c
/* Feature detection from configure */
#ifdef HAVE_SYS_XATTR_H
#include <sys/xattr.h>
#endif
/* BSD vs Linux */
#ifdef __linux__
/* Linux-specific path */
#else
/* BSD fallback (rarely used) */
#endif
/* musl compatibility */
#ifndef STAILQ_HEAD
#define STAILQ_HEAD(name, type) ...
#endif
```
### Inline Syscall Wrappers
```c
/* For syscalls not in musl headers */
static int
linux_statx(int dirfd, const char *path, int flags,
unsigned int mask, struct statx *stx)
{
return syscall(__NR_statx, dirfd, path, flags, mask, stx);
}
```
## Formatting
### Indentation
- **Tabs** for indentation (KNF style)
- **8-space tab stops** (standard)
- Continuation lines indented 4 spaces from operator
### Braces
```c
/* K&R for functions */
static void
function_name(int arg)
{
/* body */
}
/* Same-line for control flow */
if (condition) {
/* body */
} else {
/* body */
}
/* No braces for single statements */
if (error)
return -1;
```
### Line Length
- Target 80 columns
- Long function signatures wrap at parameter boundaries
- Long strings use concatenation
### Switch Statements
```c
switch (ch) {
case 'f':
force = true;
break;
case 'v':
verbose++;
break;
default:
usage();
/* NOTREACHED */
}
```
## Common Macros
```c
/* Array size */
#define nitems(x) (sizeof(x) / sizeof((x)[0]))
/* Min/Max */
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/* Noreturn */
#define __dead2 __attribute__((__noreturn__))
/* Unused parameter */
#define __unused __attribute__((__unused__))
```
## Signal Handling Conventions
```c
/* Volatile sig_atomic_t for signal flags */
static volatile sig_atomic_t info_requested;
/* Minimal signal handlers (set flag only) */
static void
handler(int sig)
{
(void)sig;
info_requested = 1;
}
/* Check flag in main loop */
if (info_requested) {
report_progress();
info_requested = 0;
}
```
## Build System Conventions
- Per-utility `GNUmakefile` is the source of truth
- Top-level `GNUmakefile` generated by `configure`
- All object files go to `build/<utility>/`
- Final binaries go to `out/bin/`
- `CFLAGS` include `-Wall -Wextra -Werror` by default
|