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
use cratec_char;
use cratedirent64;
use cratememrchr;
use Deref;
/**
Wrapper for direct getdents syscalls
# Arguments
- `fd`: Open directory file descriptor
- `buffer_ptr`: Raw pointer to output buffer
- `buffer_size`: Size of output buffer in bytes
# Safety
- Requires valid open directory descriptor
- Buffer must be valid for writes of `buffer_size` bytes
# Returns
- Positive: Number of bytes read
- 0: End of directory
- Negative: Error code (check errno)
This function is only available on Linux/Android/OpenBSD/NetBSD/Illumos/Solaris.
*/
pub unsafe
/**
Wrapper for direct getdirentries(64) syscalls
# Arguments
- `fd`: Open directory file descriptor
- `buffer_ptr`: Raw pointer to output buffer
- `nbytes`: Size of output buffer in bytes
- `basep`: Pointer to location where telldir position is stored
# Safety
- Requires valid open directory descriptor
- Buffer must be valid for writes of `nbytes` bytes
- basep must point to valid memory for `libc::off_t`
# Returns
- Positive: Number of bytes read
- 0: End of directory
- Negative: Error code (check errno)
This function is only available on macOS/FreeBSD
*/
pub unsafe
/*
// Works same as above but I prefer to not rely on hardcoded syscall numbers! Old implementation, kept for posterity.
pub unsafe fn getdirentries64<T>(
fd: libc::c_int,
buffer_ptr: *mut T,
nbytes: libc::size_t,
basep: *mut libc::off_t,
) -> i32
where
T: crate::fs::ValueType,
{
const SYS_GETDIRENTRIES64: libc::c_int = 344; // Reverse engineered syscall number
//https://phrack.org/issues/66/16
// We verify this works via build script, we check if `getdirentries` returns >0 for tmp directory, if not, syscall is broken.
unsafe { libc::syscall(SYS_GETDIRENTRIES64, fd, buffer_ptr, nbytes, basep) }
}
*/
/// A private trait for types that dereference to a byte slice (`[u8]`) representing file paths.
/// Provides efficient path operations, FFI compatibility, and filesystem interactions.
// Help the branch predictor out.
const
/**
Returns the length of `dirent64` / `dirent` `d_name` without the trailing null byte.
On supported Unix targets this delegates to `dirent_const_time_strlen` for
constant-time length detection; on other targets it falls back to
`libc::strlen` on `d_name`. This will *always* take the most optimal route.
# Safety
- `drnt` must be a valid, non-null pointer to a `dirent` / `dirent64` whose `d_name`
field is properly null-terminated within the record.
- The pointer must remain valid for the duration of the call.
*/
pub unsafe
/*
Const-time `strlen` for `dirent64's d_name` using SWAR bit tricks.
(c) Alexander Curtis .
My Cat Diavolo is cute.
*/
// TODO! this only fails on solaris/illumos when going from root, WHY???? that makes no sense. I had to remove solaris/illumos support for this function. I am being too lazy to debug it
// I never came across the issue simply because I never tried searching from root on my VM, until today.... what a weird bug JFC, I should investigate this if i feel like it.
// REALLY REALLY WEIRD
// nvm FOUND OUT WHY: d_reclen is 32 in /proc for illumos/solaris for small files. WHY? this will never work on these systems due to this reason
// leaving this here as a warning to all, don't assume too much, test!
// such a weird weird anomaly...
//cargo-asm --lib fdf::util::utils::dirent_const_time_strlen (put to inline(never) to display)
/**
Returns the length of a `dirent64' /`dirent` d_name` string in constant time using
SWAR (SIMD within a register) bit tricks (equivalent to `libc::strlen`, does NOT include the null terminator)
This function avoids branching and SIMD instructions, achieving O(1) time
by reading the final 8 bytes of the structure and applying bit-masking
operations to locate the null terminator.
# Safety
The caller must ensure:
`dirent` is a valid, non-null pointer to a `libc::dirent64/libc::dirent`.
# Performance
This is almost always faster(by a significant amount) than strlen for dirents, expect in the case of trivially short names (potentially)
On some systems
# Example
```
#[cfg(any(target_os = "linux", target_os = "android"))]
use libc::{dirent64,readdir64};
#[cfg(not(any(target_os = "linux", target_os = "android")))]
use libc::{readdir as readdir64,dirent as dirent64};
use std::env::temp_dir;
use std::fs;
use std::os::unix::ffi::OsStrExt;
use fdf::util::dirent_const_time_strlen;
let tmp = temp_dir();
let target_path = tmp.join("dirent_const_time_test");
fs::create_dir_all(&target_path).ok();
// Create a test file
let test_file = target_path.join("test_file.txt");
fs::File::create(&test_file).ok();
// Open directory and read entries
let path_cstr = std::ffi::CString::new(target_path.as_os_str().as_bytes()).unwrap();
let dir_fd = unsafe { libc::opendir(path_cstr.as_ptr()) };
if !dir_fd.is_null() {
let mut entry = unsafe { readdir64(dir_fd) };
while !entry.is_null() {
let name_len = unsafe {
dirent_const_time_strlen(entry as *const dirent64)
};
let actual_len = unsafe {
libc::strlen((&raw const (*entry).d_name).cast())
};
assert_eq!(name_len, actual_len, "Const-time strlen matches libc strlen {name_len} {actual_len}");
entry = unsafe { readdir64(dir_fd) };
}
unsafe { libc::closedir(dir_fd) };
}
fs::remove_dir_all(&target_path).ok();
```
Notes: If using this on 32 bit, use `readdir64`/`getdents64`
# References
- [Stanford Bit Twiddling Hacks find 0 byte ](http://www.icodeguru.com/Embedded/Hacker%27s-Delight/043.htm)
- [find crate `dirent.rs`](https://github.com/Soveu/find/blob/master/src/dirent.rs)
- [Wojciech Muła ] (<http://0x80.pl/notesen/2016-11-28-simd-strfind.html#algorithm-1-generic-simd>)
*/
//we're aligned (compiler can't see it though and we're doing fancy operations)
pub const unsafe
/*
assembly output: x86_64 with BMI/other optimisations
movzx eax, word ptr [rdi + 16]
xor ecx, ecx
cmp rax, 24
mov edx, 16777215
cmovne rdx, rcx <--- conditional move, no branch
or rdx, qword ptr [rdi + rax - 8]
movabs rcx, -72340172838076673 // Loading this constant with be amortised due to inlining (havent checked for stack spillage, eh, unavoidable if so anyways.)
add rcx, rdx
andn rcx, rdx, rcx
movabs rdx, -9187201950435737472 // as above.
and rdx, rcx
tzcnt rcx, rdx
shr ecx, 3
lea rax, [rax + rcx - 27]
ret
Without BMI
movzx eax, word ptr [rdi + 16]
xor ecx, ecx
cmp rax, 24
mov edx, 16777215
cmovne rdx, rcx
or rdx, qword ptr [rdi + rax - 8]
movabs rcx, -72340172838076673
add rcx, rdx
not rdx
and rcx, rdx
movabs rdx, -9187201950435737472
and rdx, rcx
rep bsf rcx, rdx <---- rep bsf is encoded to tzcnt on most x86_64 cpu's supporting it
shr ecx, 3
add rax, rcx
add rax, -27
ret
*/
/*
// Works on 32bit too, surprisingly!
// C implementation (so people can understand it better)
https://godbolt.org/z/9YM4xqx5s
#if defined(__linux__) && defined(__LP64__)
uint32_t dirent_const_time(const struct dirent *drnt) {
#define DIRENT_HEADER_START (offsetof(struct dirent, d_name))
#define MIN_DIRENT_SIZE (((DIRENT_HEADER_START) + 7) & ~7)
#define HI_U64 0x8080808080808080ULL
#define LO_U64 0x0101010101010101ULL
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define MASK 0x0000000000FFFFFFULL
#else
#define MASK 0xFFFFFF0000000000ULL
#endif
const uint32_t reclen = drnt->d_reclen;
const uint64_t mask = MASK * (uint64_t)(reclen == MIN_DIRENT_SIZE);
uint64_t last_word = *(uint64_t *)((uint8_t *)(drnt) + (reclen - 8));
last_word |= mask;
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
const uint64_t masked_lasked_word =
(last_word - LO_U64) & ~last_word & HI_U64;
const uint32_t byte_pos = __builtin_ctzll(masked_lasked_word) >> 3;
#else
const uint64_t masked_lasked_word =
((~last_word & ~HI_U64) + LO_U64) & (~last_word & HI_U64);
const uint32_t byte_pos = __builtin_clzll(masked_lasked_word) >> 3;
#endif
return reclen - DIRENT_HEADER_START + byte_pos - 8;
}
#else
#error "dirent_const_time is only supported on linux in this simplified example (and GCC/Clang, you'll need to use different intrinsics for MSVC (irrelevant cos wont work on windows lol)"
#endif
*/
/*
C version assembly
(Only distinction is we don't use LEA because we need to explicitly cast to usize in rust (for indexing))
dirent_const_time:
movzx ecx, WORD PTR [rdi+16]
xor edx, edx
mov eax, 16777215
cmp rcx, 24
cmove rdx, rax
or rdx, QWORD PTR [rdi-8+rcx]
movabs rax, -72340172838076673
add rax, rdx
not rdx
and rax, rdx
movabs rdx, -9187201950435737472
and rax, rdx
rep bsf eax, eax
shr rax, 3
lea rax, [rcx-27+rax]
ret
*/