~nabijaczleweli/voreutils

ref: e1ceab83cf67024f2c17967c8dda436109981b31 voreutils/cmd/dd.cpp -rw-r--r-- 28.9 KiB
e1ceab83наб Add head 2 months ago
                                                                                
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
// SPDX-License-Identifier: 0BSD


#include <algorithm>
#include <cstring>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <numeric>
#include <optional>
#include <signal.h>
#include <string_view>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <tuple>
#include <unistd.h>
#include <vector>
#include <vore-advice>
#include <vore-exec>
#include <vore-getopt>
#include <vore-human>
#include <vore-numeric>
#include <vore-optarg>
#include <vore-size>
#include <vore-span>
#include <vore-stdio>
#include <vore-token>


using namespace std::literals;

#if CLOCK_REALTIME_FAST
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME_FAST  // FreeBSD
#elif !CLOCK_REALTIME_COARSE
#define CLOCK_REALTIME_COARSE CLOCK_REALTIME
#endif

#if !O_DIRECT  // OpenBSD
#define O_DIRECT 0
#endif
#if !O_NOATIME  // FreeBSD, OpenBSD
#define O_NOATIME 0
#endif


// ebcdic and ibm transcribed from POSIX.1-2008; de_ebcdic is find(begin(ebcdic_map), end(ebcdic_map), c) - begin(ebcdic_map) for c in [0,0xFF]
static const constexpr std::uint8_t ebcdic_map[]    = {0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x25, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,  //
                                                    0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F,  //
                                                    0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61,  //
                                                    0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F,  //
                                                    0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6,  //
                                                    0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x9A, 0x6D,  //
                                                    0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,  //
                                                    0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0x5F, 0x07,  //
                                                    0x20, 0x21, 0x22, 0x23, 0x24, 0x15, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B,  //
                                                    0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xE1,  //
                                                    0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,  //
                                                    0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
                                                    0x76, 0x77, 0x78, 0x80, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x6A, 0x9B, 0x9C, 0x9D, 0x9E,
                                                    0x9F, 0xA0, 0xAA, 0xAB, 0xAC, 0x4A, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
                                                    0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xA1, 0xBE, 0xBF, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xDA, 0xDB,
                                                    0xDC, 0xDD, 0xDE, 0xDF, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF};
static const constexpr std::uint8_t de_ebcdic_map[] = {0x00, 0x01, 0x02, 0x03, 0x9C, 0x09, 0x86, 0x7F, 0x97, 0x8D, 0x8E, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,  //
                                                       0x10, 0x11, 0x12, 0x13, 0x9D, 0x85, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8F, 0x1C, 0x1D, 0x1E, 0x1F,  //
                                                       0x80, 0x81, 0x82, 0x83, 0x84, 0x0A, 0x17, 0x1B, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x05, 0x06, 0x07,  //
                                                       0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9A, 0x9B, 0x14, 0x15, 0x9E, 0x1A,  //
                                                       0x20, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xD5, 0x2E, 0x3C, 0x28, 0x2B, 0x7C,  //
                                                       0x26, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x7E,  //
                                                       0x2D, 0x2F, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xCB, 0x2C, 0x25, 0x5F, 0x3E, 0x3F,  //
                                                       0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22,  //
                                                       0xC3, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9,  //
                                                       0xCA, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x5E, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,  //
                                                       0xD1, 0xE5, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xD2, 0xD3, 0xD4, 0x5B, 0xD6, 0xD7,  //
                                                       0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0x5D, 0xE6, 0xE7,
                                                       0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED,
                                                       0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3,
                                                       0x5C, 0x9F, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9,
                                                       0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF};
static const constexpr std::uint8_t ibm_map[]       = {0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F, 0x16, 0x05, 0x25, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,  //
                                                 0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26, 0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F,  //
                                                 0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D, 0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61,  //
                                                 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F,  //
                                                 0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6,  //
                                                 0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D,  //
                                                 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,  //
                                                 0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xC0, 0x4F, 0xD0, 0xA1, 0x07,  //
                                                 0x20, 0x21, 0x22, 0x23, 0x24, 0x15, 0x06, 0x17, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x09, 0x0A, 0x1B,  //
                                                 0x30, 0x31, 0x1A, 0x33, 0x34, 0x35, 0x36, 0x08, 0x38, 0x39, 0x3A, 0x3B, 0x04, 0x14, 0x3E, 0xE1,  //
                                                 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,  //
                                                 0x58, 0x59, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
                                                 0x76, 0x77, 0x78, 0x80, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E,
                                                 0x9F, 0xA0, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
                                                 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xDA, 0xDB,
                                                 0xDC, 0xDD, 0xDE, 0xDF, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF};


#define USAGE(self)                                                                                                                                           \
	"usage: %s [if=file] [of=file] [[ioc]bs=size]... [skip|seek|count=blocks]... [status=none|noxfer|xfer|progress]\n"                                          \
	"       %*.s [iflag|oflag=append|direct|directory|sync|dsync|fullblock|nonblock|noatime|nocache|noctty|nofollow|skip_bytes|seek_bytes|count_bytes[,...]]\n" \
	"       %*.s [conv=ucase|lcase|swab|block|unblock|ascii|ebcdic|ibm|sparse|sync|fdatasync|fsync|noerror|excl|nocreat|notrunc[,...]]\n",                      \
	    self, (int)std::strlen(self), "", (int)std::strlen(self), ""

#define WITH_BLOCKED(signals, ...)           \
	[&] {                                      \
		sigset_t old;                            \
		sigprocmask(SIG_BLOCK, signals, &old);   \
		__VA_ARGS__;                             \
		sigprocmask(SIG_SETMASK, &old, nullptr); \
	}()


enum class nonmode_flags : std::uint8_t { fullblock = 1 << 0, nocache = 1 << 1 };
nonmode_flags operator|(nonmode_flags lhs, nonmode_flags rhs) {
	return static_cast<nonmode_flags>(static_cast<std::uint8_t>(lhs) | static_cast<std::uint8_t>(rhs));
}
bool operator&(nonmode_flags lhs, nonmode_flags rhs) {
	return static_cast<std::uint8_t>(lhs) & static_cast<std::uint8_t>(rhs);
}
nonmode_flags & operator|=(nonmode_flags & lhs, nonmode_flags rhs) {
	return lhs = lhs | rhs;
}


enum class status_t : std::uint8_t { none, noxfer, xfer, progress };
static const constexpr std::string_view status_s[] = {"none"sv, "noxfer"sv, "xfer"sv, "progress"sv};


struct conv_t {
	bool ucase, lcase, swab, ascii, ebcdic, ibm;
	bool block, unblock;
	bool sparse, sync;
	bool fdatasync, fsync;
	bool noerror;
	bool notrunc;
};


static std::optional<std::uint64_t> parse_bs(const char * bs, bool zero_ok) {
	std::uint64_t ret = 1;
	for(;;) {
		if(!bs[0] || bs[0] == 'x')
			return errno = EINVAL, std::nullopt;
		if(bs[0] == '-')
			return errno = ERANGE, std::nullopt;

		char * end{};
		errno    = 0;
		auto out = static_cast<std::uint64_t>(std::strtoull(bs, &end, 10));
		if(errno)
			return {};
		if((out == 0 && !zero_ok) || out > std::numeric_limits<std::uint64_t>::max())
			return errno = ERANGE, std::nullopt;

		std::uint64_t mul = 1;
		for(; *end && *end != 'x'; ++end)
			switch(*end) {
				case 'c':
					mul = 1;
					break;
				case 'w':
					mul = 2;
					break;
				case 'b':
					mul = 512;
					break;
				VORE_SIZE_POWER_CASE:
					mul = 1 << (10 * vore::size_power(*end));
					break;
				case 'B':
					mul = 1;
					for(auto i = vore::size_power(*(end - 1)); i; --i)
						mul *= 1000;
					break;
				default:
					return errno = EINVAL, std::nullopt;
			}

		ret *= out * mul;

		if(*end)
			bs = end + 1;
		else
			break;
	}
	return ret;
}


static std::uint64_t blocks_input_full{}, blocks_input_partial{}, blocks_output_full{}, blocks_output_partial{}, blocks_truncated{};

static std::uint64_t copied_data{};
static timespec time_start{};

static auto status = status_t::xfer;


/// Signal-safed by blocking the signals in the main execution path
/// TODO? might also just do dprintf() instead?
static void do_speed_stats(timespec * ts) {
	timespec rnow, *now = ts;
	if(!ts) {
		clock_gettime(CLOCK_REALTIME, &rnow);
		now = &rnow;
	}

	auto elapsed = (now->tv_sec - time_start.tv_sec) + ((now->tv_nsec - time_start.tv_nsec) / 1000000000.);
	char human[12], si___[12], speed[12];
	human_size(human, sizeof(human), copied_data /* ___ */, vore::human_size_t::human_1024, true);
	human_size(si___, sizeof(si___), copied_data /* ___ */, vore::human_size_t::si_1000, true);
	human_size(speed, sizeof(speed), copied_data / elapsed, vore::human_size_t::human_1024, true);

	if(ts) {
		std::fprintf(stderr, "\r%" PRIu64 "B (%siB, %sB) / % 3.0fs; %siB/s", copied_data, human, si___, elapsed, speed);
		vore::fflush(stderr);
	} else
		std::fprintf(stderr, "%" PRIu64 "B (%siB, %sB) / %gs; %siB/s\n", copied_data, human, si___, elapsed, speed);
}

static void do_final_stats() {
	if(status >= status_t::noxfer) {
		std::fprintf(stderr, "%" PRIu64 "+%" PRIu64 " records in\n", blocks_input_full, blocks_input_partial);
		std::fprintf(stderr, "%" PRIu64 "+%" PRIu64 " records out\n", blocks_output_full, blocks_output_partial);
		if(blocks_truncated)
			std::fprintf(stderr, "%" PRIu64 " truncated record%s\n", blocks_truncated, blocks_truncated == 1 ? "" : "s");
		if(status >= status_t::xfer)
			do_speed_stats(nullptr);
	}
}


int main(int, const char * const * argv) {
	std::optional<std::uint64_t> opt_bs, opt_ibs, opt_obs, opt_cbs, skip, seek, count;
	std::pair<int, nonmode_flags> iflags{O_RDONLY, {}}, oflags{O_RDWR | O_CREAT, {}};
	conv_t conv{};
	bool skip_bytes{}, seek_bytes{}, count_bytes{};
	const char *opt_if{}, *opt_of{};
	if(*argv)
		for(std::string_view arg : vore::opt::args{argv + 1}) {
			std::string_view k, v;
			if(auto idx = arg.find('='); idx != std::string_view::npos) {
				k = arg.substr(0, idx);
				v = arg.substr(idx + 1);
			} else
				k = arg;

			if(k == "if"sv)
				opt_if = v.data();
			else if(k == "of"sv)
				opt_of = v.data();
			else if(k == "bs"sv || k == "ibs"sv || k == "obs"sv || k == "cbs"sv || k == "skip"sv || k == "seek"sv || k == "count"sv) {
				auto opt = k == "bs"sv      ? &opt_bs
				           : k == "ibs"sv   ? &opt_ibs
				           : k == "obs"sv   ? &opt_obs
				           : k == "cbs"sv   ? &opt_cbs
				           : k == "skip"sv  ? &skip
				           : k == "seek"sv  ? &seek
				           : k == "count"sv ? &count
				                            : (__builtin_unreachable(), nullptr);
				if(!(*opt = parse_bs(v.data(), k == "skip"sv || k == "seek"sv || k == "count"sv)))
					return std::fprintf(stderr, "%s: %.*s=%.*s: %s\n", argv[0], (int)k.size(), k.data(), (int)v.size(), v.data(), std::strerror(errno)), 1;
			} else if(k == "iflag"sv || k == "oflag"sv) {
				auto opt = k == "iflag"sv ? &iflags : k == "oflag"sv ? &oflags : (__builtin_unreachable(), nullptr);
				for(auto fl : vore::soft_tokenise<false>{v.data(), ","}) {
					if((k != "iflag"sv && (fl == "fullblock"sv || fl == "skip_bytes"sv || fl == "count_bytes"sv)) || (k != "oflag"sv && (fl == "seek_bytes"sv)))
						return std::fprintf(stderr, "%s: %.*s=%.*s: only valid for %cflag\n", argv[0], (int)k.size(), k.data(), (int)fl.size(), fl.data(),
						                    k == "iflag"sv ? 'o' : 'i'),
						       1;

					if(fl == "append"sv)
						opt->first |= O_APPEND;
					else if(fl == "direct"sv)
						opt->first |= O_DIRECT;
					else if(fl == "directory"sv)
						opt->first |= O_DIRECTORY;
					else if(fl == "sync"sv)
						opt->first |= O_SYNC;
					else if(fl == "dsync"sv)
						opt->first |= O_DSYNC;
					else if(fl == "fullblock"sv)
						opt->second |= nonmode_flags::fullblock;
					else if(fl == "nonblock"sv)
						opt->first |= O_NONBLOCK;
					else if(fl == "noatime"sv)
						opt->first |= O_NOATIME;
					else if(fl == "nocache"sv)
						opt->second |= nonmode_flags::nocache;
					else if(fl == "noctty"sv)
						opt->first |= O_NOCTTY;
					else if(fl == "nofollow"sv)
						opt->first |= O_NOFOLLOW;
					else if(fl == "skip_bytes"sv)
						skip_bytes = true;
					else if(fl == "seek_bytes"sv)
						seek_bytes = true;
					else if(fl == "count_bytes"sv)
						count_bytes = true;
					else
						return std::fprintf(stderr, "%s: %.*s=%.*s: unknown\n", argv[0], (int)k.size(), k.data(), (int)fl.size(), fl.data()),
						       std::fprintf(stderr, USAGE(argv[0])), 1;
				}
			} else if(k == "conv"sv)
				for(auto fl : vore::soft_tokenise<false>{v.data(), ","})
					if(fl == "ucase"sv)
						conv.ucase = true;
					else if(fl == "lcase"sv)
						conv.lcase = true;
					else if(fl == "swab"sv)
						conv.swab = true;
					else if(fl == "block"sv)
						conv.block = true;
					else if(fl == "unblock"sv)
						conv.unblock = true;
					else if(fl == "ascii"sv)
						conv.ascii = conv.unblock = true;
					else if(fl == "ebcdic"sv)
						conv.ebcdic = conv.block = true;
					else if(fl == "ibm"sv)
						conv.ibm = conv.block = true;
					else if(fl == "sparse"sv)
						conv.sparse = true;
					else if(fl == "sync"sv)
						conv.sync = true;
					else if(fl == "fdatasync"sv)
						conv.fdatasync = true;
					else if(fl == "fsync"sv)
						conv.fsync = true;
					else if(fl == "noerror"sv)
						conv.noerror = true;
					else if(fl == "excl"sv)
						oflags.first |= O_EXCL;
					else if(fl == "nocreat"sv)
						oflags.first &= ~O_CREAT;
					else if(fl == "notrunc"sv)
						conv.notrunc = true;
					else
						return std::fprintf(stderr, "%s: %.*s=%.*s: unknown\n", argv[0], (int)k.size(), k.data(), (int)fl.size(), fl.data()),
						       std::fprintf(stderr, USAGE(argv[0])), 1;
			else if(k == "status"sv) {
				if(auto itr = std::find(std::begin(status_s), std::end(status_s), v); itr != std::end(status_s))
					status = static_cast<status_t>(itr - std::begin(status_s));
				else
					return std::fprintf(stderr, "%s: %.*s=%.*s: unknown\n", argv[0], (int)k.size(), k.data(), (int)v.size(), v.data()),
					       std::fprintf(stderr, USAGE(argv[0])), 1;
			} else
				return std::fprintf(stderr, USAGE(argv[0])), 1;
		}

	if(conv.ucase && conv.lcase)
		return std::fprintf(stderr, "%s: conv=ucase: excludes lcase\n", argv[0]), 1;

	if(conv.ascii + conv.ebcdic + conv.ibm > 1) {
		const char * abi[] = {"ascii", "ebcdic", "ibm"};
		if(!conv.ascii && conv.ebcdic)
			std::swap(abi[1], abi[0]);
		return std::fprintf(stderr, "%s: conv=%s: excludes %s and %s\n", argv[0], abi[0], abi[1], abi[2]), 1;
	}

	if(conv.block && conv.unblock)
		return std::fprintf(stderr, "%s: conv=block: excludes unblock\n", argv[0]), 1;

	if((conv.block || conv.unblock) && !opt_cbs)
		return std::fprintf(stderr, "%s: conv=%s: requires cbs=\n", argv[0], conv.block ? "block" : "unblock"), 1;


	auto ibs = opt_bs.value_or(opt_ibs.value_or(512));
	auto obs = opt_bs.value_or(opt_obs.value_or(512));
	if(!(conv.block || conv.unblock))
		opt_cbs = {};

	off_t skip_off = skip.value_or(0) * (skip_bytes ? 1 : ibs);
	off_t seek_off = seek.value_or(0) * (seek_bytes ? 1 : obs);

	if(!conv.notrunc && !seek_off && opt_of) {  // common fast path, saves ftruncate() call later
		oflags.first |= O_TRUNC;
		conv.notrunc = true;
	}

	for(auto && [f, fd, fl] : std::initializer_list<std::tuple<const char *, int, int>>{{opt_if, 0, iflags.first}, {opt_of, 1, oflags.first}})
		if(f) {
			close(fd);
			if(open(f, fl, 0666) == -1)
				return std::fprintf(stderr, "%s: %s: %s\n", argv[0], f, std::strerror(errno)), 1;
		} else {
			if(fcntl(fd, F_SETFL, fl) == -1)
				return std::fprintf(stderr, "%s: %s: %s\n", argv[0], fd == 0 ? "stdin" : "stdout", std::strerror(errno)), 1;
		}


	auto direct_copy = opt_bs && !(conv.block || conv.unblock || conv.lcase || conv.ucase || conv.swab);

	// We assume a tentative stack depth of 64 * 1024 for static allocations, do the same here and we can avoid dynamic allocation altogether
	auto buffer_in  = static_cast<std::uint8_t *>((ibs <= 64 * 1024) ? alloca(ibs) : std::malloc(ibs));
	auto buffer_out = direct_copy ? nullptr : static_cast<std::uint8_t *>((ibs + obs <= 64 * 1024) ? alloca(obs) : std::malloc(obs)), buffer_out_cur = buffer_out;
	auto buffer_conv     = opt_cbs ? static_cast<std::uint8_t *>(std::malloc(*opt_cbs + conv.unblock)) : nullptr,
	     buffer_conv_end = buffer_conv + opt_cbs.value_or(0) + conv.unblock, buffer_conv_cur = buffer_conv;
	if(!buffer_in || (!direct_copy && !buffer_out) || (opt_cbs && !buffer_conv))
		return std::fprintf(stderr, "%s: %s\n", argv[0], std::strerror(errno)), 1;
	bool buffer_conv_trunc{};


	std::optional<struct stat> stats[2];
	auto do_fstat = [&](auto fd, auto & sb) {
		if(!stats[fd])
			if(fstat(fd, &stats[fd].emplace()) == -1) {
				stats[fd] = {};
				return -1;
			}

		sb = *stats[fd];
		return 0;
	};

	if(!conv.notrunc) {
		struct stat sb;
		if(oflags.first & O_APPEND && do_fstat(1, sb) != -1 && S_ISREG(sb.st_mode) && isatty(2))
			std::fprintf(stderr, "%s: oflag=append: no effect on regular files w/o conv=notrunc\n", argv[0]);

		if(ftruncate(1, seek_off) == -1 && errno != EINVAL)
			return std::fprintf(stderr, "%s: trunc: %s: %s\n", argv[0], opt_of ?: "stdout", std::strerror(errno)), 1;
	}

	off_t page_size = ((oflags.second | iflags.second) & nonmode_flags::nocache) ? sysconf(_SC_PAGESIZE) : 0;


	bool out_seekable{};
	auto do_seek = [&](auto fd, auto off, auto bs) {
		auto err = lseek(fd, off, SEEK_SET);  // Can't use SEEK_DATA, even where available, since it doesn't work on devices
		if(err != -1) {
			if(fd == 1)
				out_seekable = true;

			// Assume only regular files can exhibit the seek-past-end->read(N)=[0;N] behaviour and all others are valid or will fail on read
			// TODO: This might not be correct for /dev/tty-style chardevs on some systems! also, what's tapes' deal
			struct stat sb;
			if((err = do_fstat(fd, sb)) != -1 && S_ISREG(sb.st_mode) && sb.st_size < off) {
				err   = -1;
				errno = ENXIO;
			}
		}
		if(err == -1 && errno == ESPIPE) {
			err = 0;
			for(auto remaining = off; remaining;) {
				auto to_read = std::min(static_cast<std::uint64_t>(remaining), bs);
				if((err = read(fd, buffer_in, to_read)) == -1) {
					if(errno == EINTR)
						continue;
					else
						break;
				}
				remaining -= to_read;
			}
		}
		if(err == -1)
			return std::fprintf(stderr, "%s: %s: %s\n", argv[0], fd == 0 ? "skip" : "seek", std::strerror(errno)), 1;
		else
			return 0;
	};
	if(do_seek(0, skip_off, ibs) || do_seek(1, seek_off, obs))
		return 1;


	struct sigaction act {};
	act.sa_flags   = SA_RESTART | SA_RESETHAND;
	act.sa_handler = [](int) {
		do_final_stats();
		raise(SIGINT);
	};
	sigemptyset(&act.sa_mask);
	sigaddset(&act.sa_mask, SIGINT);
	sigaddset(&act.sa_mask, SIGUSR1);
#if SIGINFO
	sigaddset(&act.sa_mask, SIGINFO);
#endif
	sigaction(SIGINT, &act, nullptr);

	act.sa_flags &= ~SA_RESETHAND;
	act.sa_handler = [](int) { do_final_stats(); };
	sigaction(SIGUSR1, &act, nullptr);
#if SIGINFO
	sigaction(SIGINFO, &act, nullptr);
#endif

	clock_gettime(CLOCK_REALTIME, &time_start);


	auto advise = [&](auto fd, auto off, auto & adv_off) {
		if(off - adv_off >= page_size) {
			auto range = (off - adv_off) - (off - adv_off) % page_size;
			posix_fadvise(fd, adv_off, range, POSIX_FADV_DONTNEED);
			adv_off += range;
		}
	};

	bool write_err{};
	auto write_off = seek_off, write_adv_off = write_off;
	auto commit_write = [&](auto iovs_beg, auto iovs_end) {
		ssize_t wr;
		if(conv.sparse && out_seekable &&
		   std::all_of(iovs_beg, iovs_end,
		               [](auto && iov) {
			               return std::all_of(static_cast<std::uint8_t *>(iov.iov_base), static_cast<std::uint8_t *>(iov.iov_base) + iov.iov_len,
			                                  [](auto b) { return b == '\0'; });
		               }) &&
		   lseek(1, wr = std::accumulate(iovs_beg, iovs_end, static_cast<off_t>(0), [](auto acc, auto && iov) { return acc + iov.iov_len; }), SEEK_CUR) != -1) {
			write_off += wr;
			write_adv_off = write_off;
		} else {
			while((wr = writev(1, iovs_beg, iovs_end - iovs_beg)) == -1 && errno == EINTR)
				;
			if(wr == -1)
				return std::fprintf(stderr, "%s: %s: %s\n", argv[0], opt_of ?: "stdout", std::strerror(errno)), write_err = true, false;
			if(oflags.second & nonmode_flags::nocache) {
				write_off += wr;
				advise(1, write_off, write_adv_off);
			}
		}
		copied_data += wr;
		++*(static_cast<std::size_t>(wr) == obs ? &blocks_output_full : &blocks_output_partial);
		return true;
	};

	auto append_writebuf = [&](auto beg, auto end) {
		auto ret = true;
		while(ret && static_cast<std::size_t>((end - beg) + (buffer_out_cur - buffer_out)) >= obs) {
			const auto ichunk         = std::min(obs - static_cast<std::size_t>(buffer_out_cur - buffer_out), static_cast<std::size_t>(end - beg));
			const struct iovec iovs[] = {{buffer_out, static_cast<std::size_t>(buffer_out_cur - buffer_out)}, {beg, ichunk}};
			ret                       = commit_write(std::begin(iovs), std::end(iovs));
			buffer_out_cur            = buffer_out;
			beg += ichunk;
		}
		std::memcpy(buffer_out_cur, beg, end - beg);
		buffer_out_cur += end - beg;
		return ret;
	};

	auto conv_block_commit = [&] {
		std::memset(buffer_conv_cur, ' ', buffer_conv_end - buffer_conv_cur);
		if(conv.ebcdic || conv.ibm)
			std::transform(buffer_conv, buffer_conv_end, buffer_conv,
			               conv.ebcdic ? static_cast<std::uint8_t (*)(std::uint8_t)>([](auto c) { return ebcdic_map[c]; })
			                           : static_cast<std::uint8_t (*)(std::uint8_t)>([](auto c) { return ibm_map[c]; }));
		auto ret        = append_writebuf(buffer_conv, buffer_conv_end);
		buffer_conv_cur = buffer_conv;
		if(buffer_conv_trunc) {
			++blocks_truncated;
			buffer_conv_trunc = false;
		}
		return ret;
	};

	auto conv_unblock_commit = [&] {
		while(buffer_conv_cur != buffer_conv && *(buffer_conv_cur - 1) == ' ')
			--buffer_conv_cur;
		*(buffer_conv_cur++) = '\n';

		auto ret        = append_writebuf(buffer_conv, buffer_conv_cur);
		buffer_conv_cur = buffer_conv;
		return ret;
	};

	bool read_err{};
	off_t seek_over{};
	auto read_off = skip_off, read_adv_off = read_off;
	auto prev = time_start;
	for(auto c_left = count.value_or(0); !count || c_left > 0;) {
		if(status == status_t::progress) {
			timespec now;
			clock_gettime(CLOCK_REALTIME_COARSE, &now);
			if(now.tv_sec > prev.tv_sec && now.tv_nsec >= prev.tv_nsec) {
				WITH_BLOCKED(&act.sa_mask, do_speed_stats(&now));
				prev = now;
			}
		}

		if(seek_over) {
			lseek(0, seek_over, SEEK_CUR);
			seek_over = 0;
		}

		ssize_t rd{};
		while((rd = read(0, buffer_in, count_bytes && c_left < ibs ? c_left : ibs)) == -1 && errno == EINTR)
			;
		if(rd != -1 && iflags.second & nonmode_flags::fullblock) {
			for(ssize_t pr = -1; pr && static_cast<size_t>(rd) != ibs;) {
				while((pr = read(0, buffer_in + rd, ibs - rd)) == -1 && errno == EINTR)
					;
				if(pr == -1) {
					if(conv.noerror) {
						WITH_BLOCKED(&act.sa_mask, [&] {
							std::fprintf(stderr, "%s: %s: %s\n", argv[0], opt_if ?: "stdin", std::strerror(errno));
							do_final_stats();
						}());
						rd        = 0;
						seek_over = ibs - rd;
						continue;
					} else {
						read_err = true;
						rd       = -1;
						break;
					}
				}
				rd += pr;
			}
		}
		if(rd == -1) {
			WITH_BLOCKED(&act.sa_mask, [&] {
				std::fprintf(stderr, "%s: %s: %s\n", argv[0], opt_if ?: "stdin", std::strerror(errno));
				if(conv.noerror)
					do_final_stats();
			}());
			if(conv.noerror) {
				seek_over = ibs;
				if(conv.sync) {
					std::memset(buffer_in, '\0', ibs);
					rd = ibs;
				} else
					continue;
			} else {
				read_err = true;
				break;
			}
		}
		if(rd == 0)
			break;
		if(iflags.second & nonmode_flags::nocache) {
			read_off += rd;
			advise(0, read_off, read_adv_off);
		}
		c_left -= count_bytes ? std::min(static_cast<std::uint64_t>(rd), c_left) : 1;
		if(count_bytes && seek_over)
			c_left -= std::min(static_cast<std::uint64_t>(seek_over), c_left);

		++*(static_cast<std::uint64_t>(rd) == ibs ? &blocks_input_full : &blocks_input_partial);

		if(static_cast<std::uint64_t>(rd) < ibs && conv.sync) {
			std::memset(buffer_in + rd, (conv.block || conv.unblock) ? ' ' : '\0', ibs - rd);
			rd = ibs;
		}

		if(direct_copy) {
			const struct iovec iov { buffer_in, static_cast<std::size_t>(rd) };
			if(!commit_write(&iov, &iov + 1))
				goto break2;
			continue;
		}

		if(conv.swab)
			for(ssize_t i = 0; i + 1 < rd; i += 2)
				std::swap(buffer_in[i], buffer_in[i + 1]);

		if(conv.ascii)
			std::transform(buffer_in, buffer_in + rd, buffer_in, [](auto c) { return de_ebcdic_map[c]; });

		if(conv.ucase || conv.lcase)
			std::transform(buffer_in, buffer_in + rd, buffer_in, conv.ucase ? static_cast<int (*)(int)>(std::toupper) : static_cast<int (*)(int)>(std::tolower));

		if(conv.block)
			for(auto b : vore::span{buffer_in, buffer_in + rd})
				if(b == '\n') {
					if(!conv_block_commit())
						goto break2;
				} else {
					if(buffer_conv_cur == buffer_conv_end)
						buffer_conv_trunc = true;
					else
						*buffer_conv_cur++ = b;
				}
		else if(conv.unblock) {
			auto buf_cur = buffer_in, buf_end = buffer_in + rd;
			while(static_cast<std::uint64_t>((buffer_conv_cur - buffer_conv) + (buf_end - buf_cur)) >= *opt_cbs) {
				const auto partlen = *opt_cbs - (buffer_conv_cur - buffer_conv);
				std::memcpy(buffer_conv_cur, buf_cur, partlen);
				buffer_conv_cur += partlen;
				buf_cur += partlen;

				if(!conv_unblock_commit())
					goto break2;
			}
			std::memcpy(buffer_conv_cur, buf_cur, buf_end - buf_cur);
			buffer_conv_cur += buf_end - buf_cur;
		} else {
			if(!append_writebuf(buffer_in, buffer_in + rd))
				goto break2;
		}
	}

	if(buffer_conv_cur != buffer_conv) {
		if(conv.block)
			conv_block_commit();
		else if(conv.unblock)
			conv_unblock_commit();
		else
			__builtin_unreachable();
	}

	if(buffer_out_cur != buffer_out) {
		const struct iovec iov { buffer_out, static_cast<std::size_t>(buffer_out_cur - buffer_out) };
		commit_write(&iov, &iov + 1);
	}
break2:;


	if(conv.fsync || conv.fdatasync)
		if((conv.fsync ? &fsync : &fdatasync)(1) == -1) {
			std::fprintf(stderr, "%s: %s: sync: %s\n", argv[0], opt_if ?: "stdin", std::strerror(errno));
			write_err = true;
		}


	WITH_BLOCKED(&act.sa_mask, do_final_stats());
	return read_err || write_err;
}