Debian Codegraph @

Source/Core/DiscIO/WiiEncryptionCache.cpp

raw symbols SCIP
1 // Copyright 2020 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DiscIO/WiiEncryptionCache.h"
5
6 #include <array>
7 #include <cstring>
8 #include <limits>
9 #include <memory>
10
11 #include "Common/Align.h"
12 #include "Common/CommonTypes.h"
13 #include "DiscIO/Blob.h"
14 #include "DiscIO/VolumeWii.h"
15
16 namespace DiscIO
17 {
18 WiiEncryptionCache::WiiEncryptionCache(BlobReader* blob) : m_blob(blob)
19 {
20 }
21
22 WiiEncryptionCache::~WiiEncryptionCache() = default;
23
24 const std::array<u8, VolumeWii::GROUP_TOTAL_SIZE>*
25 WiiEncryptionCache::EncryptGroup(u64 offset, u64 partition_data_offset,
26 u64 partition_data_decrypted_size, const Key& key,
27 const HashExceptionCallback& hash_exception_callback)
28 {
29 // Only allocate memory if this function actually ends up getting called
30 if (!m_cache)
31 {
32 m_cache = std::make_unique<std::array<u8, VolumeWii::GROUP_TOTAL_SIZE>>();
33 m_cached_offset = std::numeric_limits<u64>::max();
34 }
35
36 ASSERT(offset % VolumeWii::GROUP_TOTAL_SIZE == 0);
37 const u64 group_offset_in_partition =
38 offset / VolumeWii::GROUP_TOTAL_SIZE * VolumeWii::GROUP_DATA_SIZE;
39 const u64 group_offset_on_disc = partition_data_offset + offset;
40
41 if (m_cached_offset != group_offset_on_disc)
42 {
43 std::function<void(VolumeWii::HashBlock * hash_blocks)> hash_exception_callback_2;
44
45 if (hash_exception_callback)
46 {
47 hash_exception_callback_2 =
48 [offset, &hash_exception_callback](
49 VolumeWii::HashBlock hash_blocks[VolumeWii::BLOCKS_PER_GROUP]) {
50 return hash_exception_callback(hash_blocks, offset);
51 };
52 }
53
54 if (!VolumeWii::EncryptGroup(group_offset_in_partition, partition_data_offset,
55 partition_data_decrypted_size, key, m_blob, m_cache.get(),
56 hash_exception_callback_2))
57 {
58 m_cached_offset = std::numeric_limits<u64>::max(); // Invalidate the cache
59 return nullptr;
60 }
61
62 m_cached_offset = group_offset_on_disc;
63 }
64
65 return m_cache.get();
66 }
67
68 bool WiiEncryptionCache::EncryptGroups(u64 offset, u64 size, u8* out_ptr, u64 partition_data_offset,
69 u64 partition_data_decrypted_size, const Key& key,
70 const HashExceptionCallback& hash_exception_callback)
71 {
72 while (size > 0)
73 {
74 const std::array<u8, VolumeWii::GROUP_TOTAL_SIZE>* group =
75 EncryptGroup(Common::AlignDown(offset, VolumeWii::GROUP_TOTAL_SIZE), partition_data_offset,
76 partition_data_decrypted_size, key, hash_exception_callback);
77
78 if (!group)
79 return false;
80
81 const u64 offset_in_group = offset % VolumeWii::GROUP_TOTAL_SIZE;
82 const u64 bytes_to_read = std::min(VolumeWii::GROUP_TOTAL_SIZE - offset_in_group, size);
83 std::memcpy(out_ptr, group->data() + offset_in_group, bytes_to_read);
84
85 offset += bytes_to_read;
86 size -= bytes_to_read;
87 out_ptr += bytes_to_read;
88 }
89
90 return true;
91 }
92
93 } // namespace DiscIO