eldenring 0.14.0

Structures, bindings, and utilities for From Software's title Elden Ring
Documentation
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
use std::{
    fmt::Display,
    io::{Cursor, Read, Seek, SeekFrom},
    ptr::NonNull,
};

use vtable_rs::VPtr;

use crate::{
    DLVector,
    dlio::DLIOResult,
    dlkr::{DLAllocator, DLPlainLightMutex},
    dltx::DLString,
    dlut::DLDateTime,
};
use shared::OwnedPtr;

use super::{DLFileSeekDirection, OpenFileMode};

#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DLFileDeviceDriveType {
    Unknown = 0x0,
    CdRom = 0x1,
    Default = 0x2,
}

#[repr(C)]
pub struct DLFileDeviceBase {
    pub vftable: VPtr<dyn DLFileDeviceVmt, Self>,
    unk8: bool,
    // _pad9: [u8; 3],
    ref_count: u32,
    pub mutex: DLPlainLightMutex,
}

/// Represents a source of files.
#[vtable_rs::vtable]
pub trait DLFileDeviceVmt {
    fn destructor(&mut self);

    /// Returns pointer to DLFileOperator
    fn get_file_operator(
        &mut self,
        path_dlstring: &DLString,
        path_u16: *const u16,
        operator_container: &mut DLFileOperatorContainer,
        allocator: &mut DLAllocator,
        is_temp_file: bool,
    ) -> *const DLFileOperatorBase;

    fn file_enumerator(&self) -> *const u8;

    fn get_drive_type(&self, _path: *const u16) -> DLFileDeviceDriveType {
        DLFileDeviceDriveType::Default
    }

    /// Set true on DLEncryptedBinderLightFileDevice.
    /// Will use additional processing logic in DLEncryptedBinderLightUtility by creating
    /// a DLEncryptedBinderLightObject and passing FileOperator to second vftable entry of it.
    fn is_encrypted(&self) -> bool {
        false
    }
}

#[repr(C)]
pub struct DLFileEnumeratorSPIBase {
    pub vftable: VPtr<dyn DLFileEnumeratorSPIVmt, Self>,
}

/// Used to locate files from a given device.
#[vtable_rs::vtable]
pub trait DLFileEnumeratorSPIVmt {
    fn destructor(&mut self);

    /// Starts a search using the given search parameter. Writes a handle to search_handle that
    /// can be passed to the rest of the methods. Also writes the first found path to the
    /// found parameter. No results have been found if the found output parameter is empty.
    fn start_search(&mut self, search: &[u16], search_handle: &mut u64, found: &mut DLString);

    /// Stops a search using the search_handle.
    fn close_search(&self, search_handle: &u64);

    /// Attempts to find the next file that matches the search specified when creating the
    /// search_handle. If found is empty after calling no further results have been found.
    fn search_next(&mut self, search_handle: &mut u64, found: &mut DLString);
}

/// Represents a remote file abstracting away the storage.
#[vtable_rs::vtable]
pub trait DLFileOperatorVmt {
    fn destructor(&mut self);

    /// Copies the data from the source DLFileOperator into itself.
    fn copy_from(&mut self, source: &DLFileOperatorBase) -> bool;

    /// Sets the path for the file operator.
    /// Additionally changes the ioState.
    /// See AdapterFileOperator::set_path for implementation details.
    fn set_path(&mut self, path: &DLString, param_3: bool, param_4: bool) -> bool;

    /// Duplicate of set_path, believed to be for other DLString variants.
    fn set_path_other_1(&mut self, path: &DLString, param_3: bool, param_4: bool) -> bool;

    /// Duplicate of set_path, believed to be for other DLString variants.
    fn set_path_other_2(&mut self, path: &DLString, param_3: bool, param_4: bool) -> bool;

    /// Seems to be a function to reset ioState or toggle specific bits on it.
    /// Same happens in all set_path variants.
    /// See AdapterFileOperator::set_path for implementation details.
    fn set_state(&mut self, param_2: bool, param_3: bool) -> bool;

    /// Clears file info like path, or calls to close.
    fn clear_file_info(&mut self) -> bool;

    /// Returns a pointer to the virtual disk operator.
    fn get_virtual_disk_operator(&self) -> *const DLFileOperatorBase;

    /// Binds the file operator to a device image.
    fn bind_device_image(
        &mut self,
        image_spi: &DLFileDeviceImageSPIBase,
    ) -> *const DLFileDeviceImageSPIBase;

    /// Checks that path exists and is a file that can be read.
    fn is_readable(&mut self) -> bool;

    /// Checks if the file is writable.
    fn is_writable(&mut self) -> bool;

    /// Returns last access time in FS's proprietary format.
    fn last_access_time(&self, ptr: *const DLDateTime) -> *const DLDateTime;

    /// Returns last modify time in FS's proprietary format.
    fn last_modify_time(&self, ptr: *const DLDateTime) -> *const DLDateTime;

    /// Returns the size of the file in bytes.
    fn file_size(&mut self) -> usize;

    /// Returns the amount of bytes left to read.
    fn get_read_size(&mut self) -> usize;

    fn get_write_size(&self) -> usize;

    /// Truncates the file to the current position.
    fn set_eof(&mut self);

    /// Checks if the end of the file has been reached.
    /// by checking
    fn is_eof(&self) -> bool;

    fn is_directory(&self) -> bool;

    fn is_open(&self) -> bool;

    fn open(&mut self, open_mode: OpenFileMode) -> bool;

    /// Closes the file and releases os file handle or closes underlying readers depending on the implementation.
    /// Returns true if the file was closed successfully.
    fn close(&mut self) -> bool;

    fn set_read_only(&mut self, is_open: bool) -> bool;

    fn seek(&mut self, is_stream: bool, offset: i64, seek_mode: DLFileSeekDirection) -> bool;

    fn cursor_position(&mut self) -> usize;

    /// # Safety
    ///
    /// Caller must ensure that `output` is a pointer to valid memory.
    /// Returns amount of bytes read.
    /// It can be less than length if the file is smaller or, value is bigger than u32::MAX because of WinAPI limitations.
    unsafe fn read(&mut self, output: *mut u8, length: usize) -> i32;

    fn write(&mut self, input: *const u8, length: usize) -> usize;

    fn get_async_block_size(&self) -> usize;

    fn get_async_buffer_alignment_size(&self) -> usize;

    /// # Safety
    ///
    /// Caller must ensure that `output` is a pointer to valid memory.
    unsafe fn start_async_read(&mut self, output: *mut u8, length: usize) -> bool;

    fn start_async_write(&mut self, input: *const u8, length: usize) -> bool;

    fn query_async_status(
        &mut self,
        bytes_remaining: &mut usize,
        bytes_transferred: Option<&mut usize>,
    ) -> bool;

    fn get_open_mode(&self) -> OpenFileMode;

    /// Can delete both files and directories.
    fn delete(&mut self) -> bool;

    /// Called by DLFileOutputStream::Close as part of flush > truncate > close chain.
    /// Not implemented in all file operators.
    fn flush(&mut self);

    fn populate_file_info(&mut self) -> bool;

    fn unk2(&mut self) -> bool;

    fn rename_w(&mut self, path: *const u16) -> bool;

    fn rename(&mut self, path: *const u8) -> bool;

    fn create_directory(&mut self) -> bool;
}

#[repr(C)]
#[derive(Default, Clone, Copy)]
pub struct DLFileOperatorIOState(pub u32);

impl DLFileOperatorIOState {
    pub fn is_open(&self) -> bool {
        self.0 & 0x1 != 0
    }
    pub fn unk1(&self) -> bool {
        self.0 & 0x2 != 0
    }
    pub fn unk2(&self) -> bool {
        self.0 & 0x4 != 0
    }
}

impl Display for DLFileOperatorIOState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "DLFileOperatorIOState {{ is_open: {}, unk1: {}, unk2: {} }}",
            self.is_open(),
            self.unk1(),
            self.unk2()
        )
    }
}

#[repr(C)]
pub struct DLFileOperatorBase<T: DLFileOperatorVmt = AdapterFileOperator<Cursor<Vec<u8>>>> {
    pub vftable: VPtr<dyn DLFileOperatorVmt, T>,
    /// Allocator passed to constructor, used for all memory operations
    pub allocator: &'static DLAllocator,
    /// Result of latest operation involving this file operator
    pub result: DLIOResult,
    // _pad14: u32,
    /// File operator container, that owns this file operator.
    pub owning_operator_container: NonNull<DLFileOperatorContainer>,
    /// Bitfield that tracks the state of the file operator.
    /// bit 0: 0x1 - file is open
    /// bit 1 - Unk, changed by vftable.set_path
    /// bit 2: Unk, changed by vftable.set_path
    pub io_state: DLFileOperatorIOState,
    // _pad24: u32,
    /// File device that created this file operator.
    pub owning_file_device: NonNull<DLFileDeviceBase>,
    /// Virtual or real path, this operator is bound to.
    pub path: DLString,
}

impl<T> DLFileOperatorBase<T>
where
    T: DLFileOperatorVmt,
{
    pub fn new(
        vftable: VPtr<dyn DLFileOperatorVmt, T>,
        allocator: &'static DLAllocator,
        path: &DLString,
        operator_container: &DLFileOperatorContainer,
        file_device: &DLFileDeviceBase,
    ) -> Self {
        Self {
            vftable,
            allocator,
            result: DLIOResult::Success,
            owning_operator_container: NonNull::from(operator_container),
            io_state: DLFileOperatorIOState::default(),
            owning_file_device: NonNull::from(file_device),
            path: DLString::transcode_from(path, allocator).expect("Failed to copy DLString"),
        }
    }
}

#[vtable_rs::vtable]
pub trait DLFileDeviceImageSPIVmt {
    fn destructor(&mut self);
}

#[repr(C)]
pub struct DLFileDeviceImageSPIBase {
    pub vftable: VPtr<dyn DLFileDeviceImageSPIVmt, Self>,
}

#[repr(C)]
pub struct BndEntry {
    pub name: DLString,
    pub device: NonNull<DLFileDeviceBase>,
    pub file_size: u64,
}

#[repr(C)]
pub struct DLFileOperatorContainer {
    allocator: &'static DLAllocator,
    read_file_operator: OwnedPtr<DLFileOperatorBase>,
    write_file_operator: OwnedPtr<DLFileOperatorBase>,
    flags: u32,
}

#[repr(C)]
pub struct DLFileDeviceManager {
    pub devices: DLVector<NonNull<DLFileDeviceBase>>,
    pub service_providers: DLVector<NonNull<DLFileDeviceImageSPIBase>>,
    pub msvc_file_device: OwnedPtr<DLFileDeviceBase>,
    pub virtual_roots: DLVector<[DLString; 2]>,
    pub bnd3_files: DLVector<BndEntry>,
    pub bnd4_files: DLVector<BndEntry>,
    pub bnd3_service_provider: OwnedPtr<DLFileDeviceImageSPIBase>,
    pub bnd4_service_provider: OwnedPtr<DLFileDeviceImageSPIBase>,
    pub mutex: DLPlainLightMutex,
}

impl DLFileDeviceVmt for DLFileDeviceBase {
    extern "C" fn destructor(&mut self) {
        (self.vftable.destructor)(self);
    }

    extern "C" fn get_file_operator(
        &mut self,
        name_dlstring: &DLString,
        name_u16: *const u16,
        operator_container: &mut DLFileOperatorContainer,
        allocator: &mut DLAllocator,
        is_temp_file: bool,
    ) -> *const DLFileOperatorBase {
        (self.vftable.get_file_operator)(
            self,
            name_dlstring,
            name_u16,
            operator_container,
            allocator,
            is_temp_file,
        )
    }

    extern "C" fn file_enumerator(&self) -> *const u8 {
        (self.vftable.file_enumerator)(self)
    }

    extern "C" fn get_drive_type(&self, path: *const u16) -> DLFileDeviceDriveType {
        (self.vftable.get_drive_type)(self, path)
    }

    extern "C" fn is_encrypted(&self) -> bool {
        (self.vftable.is_encrypted)(self)
    }
}

#[repr(C)]
pub struct AdapterFileOperator<R>
where
    R: Read + Seek + 'static,
{
    pub base: DLFileOperatorBase,
    buffer: R,
}

impl<R> AdapterFileOperator<R>
where
    R: Read + Seek + 'static,
{
    pub fn new(
        allocator: &'static DLAllocator,
        path: &DLString,
        operator_container: &DLFileOperatorContainer,
        file_device: &DLFileDeviceBase,
        buffer: R,
    ) -> Self {
        Self {
            base: DLFileOperatorBase::new(
                Default::default(),
                allocator,
                path,
                operator_container,
                file_device,
            ),
            buffer,
        }
    }
}

impl<R> Display for AdapterFileOperator<R>
where
    R: Read + Seek + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AdapterFileOperator({})", self.base.path)
    }
}

impl<R> DLFileOperatorVmt for AdapterFileOperator<R>
where
    R: Read + Seek + 'static,
{
    extern "C" fn destructor(&mut self) {
        unsafe {
            std::ptr::drop_in_place(self);
        }
    }

    extern "C" fn copy_from(&mut self, _source: &DLFileOperatorBase) -> bool {
        unimplemented!()
    }

    extern "C" fn set_path(&mut self, path: &DLString, param_3: bool, param_4: bool) -> bool {
        self.base.io_state.0 &= 0xfffffff9;
        self.base.io_state.0 |= (((param_4 as u32 & 1) * 2) | (param_3 as u32 & 1)) * 2;

        self.base.path =
            DLString::transcode_from(path, self.base.allocator).expect("Failed to copy DLString");

        true
    }

    extern "C" fn set_path_other_1(
        &mut self,
        _path: &DLString,
        _param_3: bool,
        _param_4: bool,
    ) -> bool {
        unimplemented!()
    }

    extern "C" fn set_path_other_2(
        &mut self,
        _path: &DLString,
        _param_3: bool,
        _param_4: bool,
    ) -> bool {
        unimplemented!()
    }

    extern "C" fn set_state(&mut self, param_2: bool, param_3: bool) -> bool {
        self.base.io_state.0 &= 0xfffffff9;
        self.base.io_state.0 |= (((param_3 as u32 & 1) * 2) | (param_2 as u32 & 1)) * 2;

        true
    }

    extern "C" fn clear_file_info(&mut self) -> bool {
        unimplemented!()
    }

    extern "C" fn get_virtual_disk_operator(&self) -> *const DLFileOperatorBase {
        unimplemented!()
    }

    extern "C" fn bind_device_image(
        &mut self,
        _image_spi: &DLFileDeviceImageSPIBase,
    ) -> *const DLFileDeviceImageSPIBase {
        unimplemented!()
    }

    extern "C" fn is_readable(&mut self) -> bool {
        unimplemented!()
    }
    extern "C" fn is_writable(&mut self) -> bool {
        unimplemented!()
    }

    extern "C" fn last_access_time(&self, _ptr: *const DLDateTime) -> *const DLDateTime {
        unimplemented!()
    }

    extern "C" fn last_modify_time(&self, _ptr: *const DLDateTime) -> *const DLDateTime {
        unimplemented!()
    }

    extern "C" fn file_size(&mut self) -> usize {
        let current = self.buffer.stream_position().unwrap();
        let end = self.buffer.seek(SeekFrom::End(0)).unwrap() as usize;
        let _ = self.buffer.seek(SeekFrom::Start(current));
        end
    }

    extern "C" fn get_read_size(&mut self) -> usize {
        unimplemented!()
    }

    extern "C" fn get_write_size(&self) -> usize {
        unimplemented!()
    }

    extern "C" fn set_eof(&mut self) {
        unimplemented!()
    }

    extern "C" fn is_eof(&self) -> bool {
        unimplemented!()
    }

    extern "C" fn is_directory(&self) -> bool {
        unimplemented!()
    }

    extern "C" fn is_open(&self) -> bool {
        true
    }

    extern "C" fn open(&mut self, _open_mode: OpenFileMode) -> bool {
        true
    }

    extern "C" fn close(&mut self) -> bool {
        true
    }

    extern "C" fn set_read_only(&mut self, _is_open: bool) -> bool {
        unimplemented!()
    }

    extern "C" fn seek(
        &mut self,
        _is_stream: bool,
        offset: i64,
        seek_mode: DLFileSeekDirection,
    ) -> bool {
        let seek_from = match seek_mode {
            DLFileSeekDirection::Head => SeekFrom::Start(offset as u64),
            DLFileSeekDirection::Current => SeekFrom::Current(offset),
            DLFileSeekDirection::Tail => SeekFrom::End(offset),
        };
        self.buffer.seek(seek_from).is_ok()
    }

    extern "C" fn cursor_position(&mut self) -> usize {
        self.buffer.stream_position().unwrap_or(0) as usize
    }

    unsafe extern "C" fn read(&mut self, output: *mut u8, length: usize) -> i32 {
        let mut buffer = vec![0x0u8; length];
        self.buffer.read_exact(&mut buffer).unwrap();

        unsafe { std::ptr::copy_nonoverlapping(buffer.as_ptr(), output, length) };
        self.base.result = DLIOResult::Success;
        length as i32
    }

    extern "C" fn write(&mut self, _input: *const u8, _length: usize) -> usize {
        unimplemented!()
    }

    extern "C" fn get_async_block_size(&self) -> usize {
        unimplemented!()
    }
    extern "C" fn get_async_buffer_alignment_size(&self) -> usize {
        unimplemented!()
    }

    unsafe extern "C" fn start_async_read(&mut self, _output: *mut u8, _length: usize) -> bool {
        unimplemented!()
    }
    extern "C" fn start_async_write(&mut self, _input: *const u8, _length: usize) -> bool {
        unimplemented!()
    }
    extern "C" fn query_async_status(
        &mut self,
        _bytes_remaining: &mut usize,
        _bytes_transferred: Option<&mut usize>,
    ) -> bool {
        unimplemented!()
    }
    extern "C" fn get_open_mode(&self) -> OpenFileMode {
        unimplemented!()
    }

    extern "C" fn delete(&mut self) -> bool {
        unimplemented!()
    }

    extern "C" fn flush(&mut self) {
        unimplemented!()
    }

    extern "C" fn populate_file_info(&mut self) -> bool {
        unimplemented!()
    }

    extern "C" fn unk2(&mut self) -> bool {
        unimplemented!()
    }

    extern "C" fn rename_w(&mut self, _path: *const u16) -> bool {
        unimplemented!()
    }

    extern "C" fn rename(&mut self, _path: *const u8) -> bool {
        unimplemented!()
    }

    extern "C" fn create_directory(&mut self) -> bool {
        unimplemented!()
    }
}