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
use std::fmt;
use std::sync::atomic::AtomicU32;

use skyline::hooks::{getRegionAddress, Region};
use skyline::nn;

pub static mut LOADED_TABLES_ADRP_OFFSET: usize = 0x324c3a0;
pub static mut RES_SERVICE_ADRP_OFFSET: usize = 0xaf0b04;

static LOADED_TABLES_ADRP_SEARCH_CODE: &[u8] = &[
    0xf3, 0x03, 0x00, 0xaa, 0x1f, 0x01, 0x09, 0x6b, 0xe0, 0x04, 0x00, 0x54,
];

static RES_SERVICE_ADRP_SEARCH_CODE: &[u8] = &[
    0x04, 0x01, 0x49, 0xfa, 0x21, 0x05, 0x00, 0x54, 0x5f, 0x00, 0x00, 0xf9, 0x7f, 0x00, 0x00, 0xf9,
];

pub fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

fn offset_from_adrp(adrp_offset: usize) -> usize {
    unsafe {
        let adrp = *(offset_to_addr(adrp_offset) as *const u32);
        let immhi = (adrp & 0b0_00_00000_1111111111111111111_00000) >> 3;
        let immlo = (adrp & 0b0_11_00000_0000000000000000000_00000) >> 29;
        let imm = ((immhi | immlo) << 12) as i32 as usize;
        let base = adrp_offset & 0xFFFFFFFFFFFFF000;
        base + imm
    }
}

fn offset_from_ldr(ldr_offset: usize) -> usize {
    unsafe {
        let ldr = *(offset_to_addr(ldr_offset) as *const u32);
        let size = (ldr & 0b11_000_0_00_00_000000000000_00000_00000) >> 30;
        let imm = (ldr & 0b00_000_0_00_00_111111111111_00000_00000) >> 10;
        (imm as usize) << size
    }
}

lazy_static::lazy_static! {
    static ref LOADED_TABLES_RES_SERVICE_OFFSETS : (usize, usize) = {
        unsafe {
            let text_ptr = getRegionAddress(Region::Text) as *const u8;
            let text_size = (getRegionAddress(Region::Rodata) as usize) - (text_ptr as usize);
            let text = std::slice::from_raw_parts(text_ptr, text_size);

            if let Some(offset) = find_subsequence(text, LOADED_TABLES_ADRP_SEARCH_CODE) {
                LOADED_TABLES_ADRP_OFFSET = offset + 12
            } else {
                println!("Error: no offset found for 'loaded_tables_adrp'. Defaulting to 8.0.0 offset. This likely won't work.");
            }
            if let Some(offset) = find_subsequence(text, RES_SERVICE_ADRP_SEARCH_CODE) {
                RES_SERVICE_ADRP_OFFSET = offset + 16
            } else {
                println!("Error: no offset found for 'res_service_adrp'. Defaulting to 9.0.0 offset. This likely won't work.");
            }

            let adrp_offset = offset_from_adrp(LOADED_TABLES_ADRP_OFFSET);
            let ldr_offset = offset_from_ldr(LOADED_TABLES_ADRP_OFFSET + 4);
            let loaded_tables_offset = adrp_offset + ldr_offset;

            let adrp_offset = offset_from_adrp(RES_SERVICE_ADRP_OFFSET);
            let ldr_offset = offset_from_ldr(RES_SERVICE_ADRP_OFFSET + 4);
            let res_service_offset = adrp_offset + ldr_offset;

            (loaded_tables_offset, res_service_offset)
            //return (LOADED_TABLES_OFFSET, RES_SERVICE_OFFSET)
        }
    };
}

// 9.0.1 offsets
pub static mut LOADED_TABLES_OFFSET: usize = 0x50567a0;
pub static mut RES_SERVICE_OFFSET: usize = 0x50567a8;

pub fn offset_to_addr(offset: usize) -> *const () {
    unsafe { (getRegionAddress(Region::Text) as *const u8).offset(offset as isize) as _ }
}

#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq)]
#[allow(dead_code)]
pub enum FileState {
    Unused = 0,
    Unloaded = 1,
    Unk2 = 2,
    Loaded = 3,
}

impl fmt::Display for FileState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[repr(C)]
#[repr(packed)]
pub struct Table1Entry {
    pub table2_index: u32,
    pub in_table_2: u32,
}

impl Table1Entry {
    pub fn get_t2_entry(&self) -> Result<&Table2Entry, LoadError> {
        LoadedTables::get_instance()
            .table_2()
            .get(self.table2_index as usize)
            .ok_or(LoadError::NoTable2)
    }
}

impl fmt::Display for Table1Entry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        unsafe {
            write!(
                f,
                "Table2 index: {} (In Table2: {})",
                self.table2_index,
                self.in_table_2 != 0
            )
        }
    }
}

#[repr(C)]
#[derive(Debug)]
pub struct Table2Entry {
    pub data: *const u8,
    pub ref_count: AtomicU32,
    pub is_used: bool,
    pub state: FileState,
    pub file_flags2: bool,
    pub flags: u8,
    pub version: u32,
    pub unk: u8,
}

impl fmt::Display for Table2Entry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "State: {}, Flags: {}, RefCount: {:x?}, Data loaded: {}, Version: {:#x}, Unk: {}",
            self.state,
            self.flags,
            self.ref_count,
            !self.data.is_null(),
            self.version,
            self.unk
        )
    }
}

#[repr(C)]
pub struct LoadedTables {
    pub mutex: *mut nn::os::MutexType,
    pub table1: *mut Table1Entry,
    pub table2: *mut Table2Entry,
    pub table1_len: u32,
    pub table2_len: u32,
    pub table1_count: u32,
    pub table2_count: u32,
    pub table1_list: CppVector<u32>,
    pub loaded_directory_table: *const (),
    pub loaded_directory_table_size: u32,
    pub unk2: u32,
    pub unk3: CppVector<u32>,
    pub unk4: u8,
    pub unk5: [u8; 7],
    pub addr: *const (),
    pub loaded_data: &'static mut LoadedData,
    pub version: u32,
}

#[repr(C)]
pub struct LoadedData {
    arc: &'static mut LoadedArc,
    search: &'static mut LoadedSearch,
}

#[repr(C)]
pub struct LoadedArc {
    pub magic: u64,
    pub music_data_offset: u64,
    pub file_data_offset: u64,
    pub file_data_offset_2: u64,
    pub fs_offset: u64,
    pub fs_search_offset: u64,
    pub unk_offset: u64,
    pub loaded_fs: *const (),
    pub loaded_fs_2: *const (),
    pub region_entry: *const (),
    pub file_path_buckets: *const (),
    pub file_path_to_index_hash_group: *const (),
    pub file_info_path: *const FileInfoPath,
    pub file_info_idx: *const FileInfoIndex,
    pub dir_hash_group: *const (),
    pub dir_list: *const (),
    pub dir_offset: *const (),
    pub dir_child_hash_group: *const (),
    // FileInfoV2
    pub file_info: *const FileInfo,
    pub file_info_sub_index: *const FileInfoSubIndex,
    pub sub_files: *const SubFile,
}

#[repr(C)]
pub struct CppVector<T> {
    start: *const T,
    end: *const T,
    eos: *const T,
}

#[repr(C)]
pub struct LoadedSearch {
    pub header: *const (),
    pub body: *const FsSearchBody,
    pub file_path_to_idx: *const HashIndexGroup,
    pub idx_to_group: *const HashGroup,
    pub path_to_idx: *const HashIndexGroup,
    pub idx_to_path_group_idx: *const (),
    pub path_group: *const HashGroup,
}

#[repr(C)]
pub struct FsSearchBody {
    pub file_path_length: u32,
    pub idx_length: u32,
    pub path_group_length: u32,
}

impl LoadedArc {
    pub fn get_subfile_by_t1_index(&self, t1_index: u32) -> &mut SubFile {
        let mut file_info = self.lookup_file_information_by_t1_index(t1_index);
        let file_index = self.lookup_fileinfoindex_by_t1_index(t1_index);

        // Redirect
        if (file_info.flags & 0x00000010) == 0x10 {
            // Try to change its shared status, infinite loadings so far
            // file_info.flags ^= 0x10;

            // let loaded_tables = LoadedTables::get_instance();
            // unsafe { nn::os::LockMutex(loaded_tables.mutex); }

            // let count: [u8; 4] = unsafe { transmute((loaded_tables.table2_len -1).to_le()) };
            // self.lookup_fileinfopath_by_t1_index(t1_index).path.index.0[0] = count[0];
            // self.lookup_fileinfopath_by_t1_index(t1_index).path.index.0[1] = count[1];
            // self.lookup_fileinfopath_by_t1_index(t1_index).path.index.0[2] = count[2];
            // loaded_tables.get_t1_mut(t1_index).unwrap().table2_index = loaded_tables.table2_len - 1;

            // unsafe { nn::os::UnlockMutex(loaded_tables.mutex); }

            // println!("Table2_len: {:#x}", loaded_tables.table2_len);
            // println!("Flags after: {:#x}, PathIndex: {:#x}", file_info.flags, self.lookup_fileinfopath_by_t1_index(t1_index).path.index.as_u32());

            //let file_index = self.lookup_fileinfoindex_by_t1_index(t1_index);
            file_info = self.lookup_file_information_by_t1_index(file_index.file_info_index);
        }

        let mut sub_index = self.lookup_fileinfosubindex_by_index(file_info.sub_index_index);

        // let region_index;

        // match &crate::config::CONFIG.misc.region[..] {
        //     "jp_ja" => region_index = 0,
        //     "us_en" => region_index = 1,
        //     "us_fr" => region_index = 2,
        //     "us_es" => region_index = 3,
        //     "eu_en" => region_index = 4,
        //     "eu_fr" => region_index = 5,
        //     "eu_es" => region_index = 6,
        //     "eu_de" => region_index = 7,
        //     "eu_nl" => region_index = 8,
        //     "eu_it" => region_index = 9,
        //     "eu_ru" => region_index = 10,
        //     "kr_ko" => region_index = 11,
        //     "zh_cn" => region_index = 12,
        //     "zh_tw" => region_index = 13,
        //     _ => region_index = 1,
        // }

        // Regional
        if (file_info.flags & 0x00008000) == 0x8000 {
            sub_index = self.lookup_fileinfosubindex_by_index(
                file_info.sub_index_index + 1 + ResServiceState::get_instance().regular_region_idx,
            );
        }

        let sub_file =
            unsafe { self.sub_files.offset(sub_index.sub_file_index as isize) as *mut SubFile };

        // Compressed flag
        // unsafe { (*sub_file).flags &= !3; }

        unsafe { &mut *sub_file }
    }

    pub fn lookup_fileinfopath_by_t1_index(&self, t1_index: u32) -> &mut FileInfoPath {
        let file_info_path_table = self.file_info_path;
        let file_info =
            unsafe { file_info_path_table.offset(t1_index as isize) as *mut FileInfoPath };
        unsafe { &mut *file_info }
    }

    pub fn lookup_fileinfoindex_by_t1_index(&self, t1_index: u32) -> &mut FileInfoIndex {
        let file_info_path = self.lookup_fileinfopath_by_t1_index(t1_index);
        let file_info_idx = unsafe {
            self.file_info_idx
                .offset(file_info_path.path.index.as_u32() as isize)
                as *mut FileInfoIndex
        };
        unsafe { &mut *file_info_idx }
    }

    pub fn lookup_file_information_by_t1_index(&self, t1_index: u32) -> &mut FileInfo {
        let file_info_idx = self.lookup_fileinfoindex_by_t1_index(t1_index);
        let file_info_table = self.file_info as *mut FileInfo;
        let file_info =
            unsafe { file_info_table.offset((*file_info_idx).file_info_index as isize) };
        unsafe { &mut (*file_info) }
    }

    pub fn lookup_fileinfosubindex_by_index(&self, sub_index_index: u32) -> &mut FileInfoSubIndex {
        let file_info_sub_index_table = self.file_info_sub_index as *mut FileInfoSubIndex;
        let file_info_sub_index =
            unsafe { &mut *file_info_sub_index_table.offset(sub_index_index as isize) };
        file_info_sub_index
    }
}

#[repr(C)]
pub struct FileInfo {
    pub path_index: u32,
    pub index_index: u32,
    pub sub_index_index: u32,
    pub flags: u32,
}

#[repr(C)]
#[derive(Debug, Clone)]
pub struct SubFile {
    pub offset: u32,
    pub compressed_size: u32,
    pub decompressed_size: u32,
    pub flags: u32,
}

#[repr(C)]
pub struct FileInfoPath {
    pub path: HashIndexGroup,
    pub extension: HashIndexGroup,
    pub parent: HashIndexGroup,
    pub file_name: HashIndexGroup,
}

#[repr(packed)]
pub struct FileInfoIndex {
    pub dir_offset_index: u32,
    pub file_info_index: u32,
}

#[repr(packed)]
pub struct FileInfoSubIndex {
    pub folder_offset_index: u32,
    pub sub_file_index: u32,
    pub file_info_index_and_flag: u32,
}

#[repr(packed)]
#[derive(Copy, Clone)]
pub struct HashIndexGroup {
    pub hash40: Hash40,
    pub index: U24,
}

#[repr(C)]
pub struct HashGroup {
    pub path: HashIndexGroup,
    pub parent: HashIndexGroup,
    pub file_name: HashIndexGroup,
    pub extension: HashIndexGroup,
}

impl fmt::Debug for HashIndexGroup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{:x}", self.hash40.as_u64())
    }
}

#[repr(packed)]
#[derive(Copy, Clone)]
pub struct Hash40 {
    pub crc32: u32,
    pub len: u8,
}

#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct U24(pub [u8; 3]);

impl U24 {
    pub fn as_u32(&self) -> u32 {
        u32::from_le_bytes([self.0[0], self.0[1], self.0[2], 0])
    }
}

impl fmt::Debug for U24 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_u32())
    }
}

impl fmt::Debug for Hash40 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{:x}", self.as_u64())
    }
}

impl Hash40 {
    pub fn as_u64(&self) -> u64 {
        (self.crc32 as u64) + ((self.len as u64) << 32)
    }
}

impl LoadedTables {
    pub fn get_arc(&self) -> &LoadedArc {
        self.loaded_data.arc
    }

    #[allow(dead_code)]
    pub fn get_search(&self) -> &LoadedSearch {
        self.loaded_data.search
    }

    #[allow(dead_code)]
    pub fn get_arc_mut(&mut self) -> &mut LoadedArc {
        &mut self.loaded_data.arc
    }

    #[allow(dead_code)]
    pub fn get_search_mut(&mut self) -> &LoadedSearch {
        &mut self.loaded_data.search
    }

    pub fn get_instance() -> &'static mut Self {
        unsafe {
            let instance_ptr: *mut &'static mut Self =
                std::mem::transmute(offset_to_addr(LOADED_TABLES_RES_SERVICE_OFFSETS.0));
            *instance_ptr
        }
    }

    pub fn get_hash_from_t1_index(&self, t1_index: u32) -> Hash40 {
        let arc = self.get_arc();
        let path_table = arc.file_info_path;
        let file_info = unsafe { &*path_table.offset(t1_index as isize) };
        file_info.path.hash40
    }

    pub fn table_1(&self) -> &[Table1Entry] {
        unsafe { std::slice::from_raw_parts(self.table1, self.table1_len as usize) }
    }

    pub fn table_1_mut(&mut self) -> &mut [Table1Entry] {
        unsafe { std::slice::from_raw_parts_mut(self.table1, self.table1_len as usize) }
    }

    pub fn table_2(&self) -> &[Table2Entry] {
        unsafe { std::slice::from_raw_parts(self.table2, self.table2_len as usize) }
    }

    pub fn table_2_mut(&mut self) -> &mut [Table2Entry] {
        unsafe { std::slice::from_raw_parts_mut(self.table2, self.table2_len as usize) }
    }

    pub fn get_t1_mut(&mut self, t1_index: u32) -> Result<&mut Table1Entry, LoadError> {
        self.table_1_mut()
            .get_mut(t1_index as usize)
            .ok_or(LoadError::NoTable1)
    }

    pub fn get_t2(&self, t1_index: u32) -> Result<&Table2Entry, LoadError> {
        let t1 = self
            .table_1()
            .get(t1_index as usize)
            .ok_or(LoadError::NoTable1)?;
        let t2_index = t1.table2_index as usize;
        self.table_2().get(t2_index).ok_or(LoadError::NoTable2)
    }

    pub fn get_t2_mut(&mut self, t1_index: u32) -> Result<&mut Table2Entry, LoadError> {
        let t1 = self
            .table_1()
            .get(t1_index as usize)
            .ok_or(LoadError::NoTable1)?;
        let t2_index = t1.table2_index as usize;
        self.table_2_mut()
            .get_mut(t2_index)
            .ok_or(LoadError::NoTable2)
    }
}

#[derive(Copy, Clone, Debug)]
pub enum LoadError {
    NoTable1,
    NoTable2,
}

#[repr(C)]
#[allow(dead_code)]
pub struct FileNX {
    vtable: *const (),
    unk1: *const (),
    unk2: u32,
    pub is_open: u32,
    pub file_handle: *mut nn::fs::FileHandle,
    unk3: u32,
    pub position: u64,
    pub filename_fixedstring: [u8; 516],
    unk4: u32,
}

#[repr(C)]
#[allow(dead_code)]
pub struct ResServiceState {
    pub mutex: *mut nn::os::MutexType,
    pub res_update_event: *mut nn::os::EventType,
    unk1: *const (),
    pub io_swap_event: *mut nn::os::EventType,
    unk2: *const (),
    pub semaphore1: *const (),
    pub semaphore2: *const (),
    pub res_update_thread: *mut nn::os::ThreadType,
    pub res_loading_thread: *mut nn::os::ThreadType,
    pub res_inflate_thread: *mut nn::os::ThreadType,
    unk4: *const (),
    unk5: [CppVector<CppVector<u32>>; 4],
    unk6: *const (),
    unk7: *const (),
    unk8: *const (),
    pub loaded_tables: *mut LoadedTables,
    pub unk_region_idx: u32,
    pub regular_region_idx: u32,
    unk9: u32,
    pub state: i16,
    pub is_loader_thread_running: bool,
    unk10: u8,
    pub data_arc_string: [u8; 256],
    unk11: *const (),
    pub data_arc_filenx: *mut FileNX,
    pub buffer_size: usize,
    pub buffer_array: [*const skyline::libc::c_void; 2],
    pub buffer_array_idx: u32,
    unk12: *const (),
    pub data_ptr: *const skyline::libc::c_void,
    pub offset_into_read: u64,
    //Still need to add some
}

impl ResServiceState {
    pub fn get_instance() -> &'static mut Self {
        unsafe {
            let instance_ptr: *mut &'static mut Self =
                std::mem::transmute(offset_to_addr(LOADED_TABLES_RES_SERVICE_OFFSETS.1));
            *instance_ptr
        }
    }
}