pl_u.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cstring>
  6. #include <vector>
  7. #include "common/assert.h"
  8. #include "common/common_types.h"
  9. #include "common/logging/log.h"
  10. #include "common/swap.h"
  11. #include "core/core.h"
  12. #include "core/file_sys/content_archive.h"
  13. #include "core/file_sys/nca_metadata.h"
  14. #include "core/file_sys/registered_cache.h"
  15. #include "core/file_sys/romfs.h"
  16. #include "core/file_sys/system_archive/system_archive.h"
  17. #include "core/hle/ipc_helpers.h"
  18. #include "core/hle/kernel/k_shared_memory.h"
  19. #include "core/hle/kernel/kernel.h"
  20. #include "core/hle/kernel/physical_memory.h"
  21. #include "core/hle/service/filesystem/filesystem.h"
  22. #include "core/hle/service/ns/pl_u.h"
  23. namespace Service::NS {
  24. struct FontRegion {
  25. u32 offset;
  26. u32 size;
  27. };
  28. // The below data is specific to shared font data dumped from Switch on f/w 2.2
  29. // Virtual address and offsets/sizes likely will vary by dump
  30. [[maybe_unused]] constexpr VAddr SHARED_FONT_MEM_VADDR{0x00000009d3016000ULL};
  31. constexpr u32 EXPECTED_RESULT{0x7f9a0218}; // What we expect the decrypted bfttf first 4 bytes to be
  32. constexpr u32 EXPECTED_MAGIC{0x36f81a1e}; // What we expect the encrypted bfttf first 4 bytes to be
  33. constexpr u64 SHARED_FONT_MEM_SIZE{0x1100000};
  34. constexpr FontRegion EMPTY_REGION{0, 0};
  35. enum class LoadState : u32 {
  36. Loading = 0,
  37. Done = 1,
  38. };
  39. static void DecryptSharedFont(const std::vector<u32>& input, Kernel::PhysicalMemory& output,
  40. std::size_t& offset) {
  41. ASSERT_MSG(offset + (input.size() * sizeof(u32)) < SHARED_FONT_MEM_SIZE,
  42. "Shared fonts exceeds 17mb!");
  43. ASSERT_MSG(input[0] == EXPECTED_MAGIC, "Failed to derive key, unexpected magic number");
  44. const u32 KEY = input[0] ^ EXPECTED_RESULT; // Derive key using an inverse xor
  45. std::vector<u32> transformed_font(input.size());
  46. // TODO(ogniK): Figure out a better way to do this
  47. std::transform(input.begin(), input.end(), transformed_font.begin(),
  48. [&KEY](u32 font_data) { return Common::swap32(font_data ^ KEY); });
  49. transformed_font[1] = Common::swap32(transformed_font[1]) ^ KEY; // "re-encrypt" the size
  50. std::memcpy(output.data() + offset, transformed_font.data(),
  51. transformed_font.size() * sizeof(u32));
  52. offset += transformed_font.size() * sizeof(u32);
  53. }
  54. void DecryptSharedFontToTTF(const std::vector<u32>& input, std::vector<u8>& output) {
  55. ASSERT_MSG(input[0] == EXPECTED_MAGIC, "Failed to derive key, unexpected magic number");
  56. if (input.size() < 2) {
  57. LOG_ERROR(Service_NS, "Input font is empty");
  58. return;
  59. }
  60. const u32 KEY = input[0] ^ EXPECTED_RESULT; // Derive key using an inverse xor
  61. std::vector<u32> transformed_font(input.size());
  62. // TODO(ogniK): Figure out a better way to do this
  63. std::transform(input.begin(), input.end(), transformed_font.begin(),
  64. [&KEY](u32 font_data) { return Common::swap32(font_data ^ KEY); });
  65. std::memcpy(output.data(), transformed_font.data() + 2,
  66. (transformed_font.size() - 2) * sizeof(u32));
  67. }
  68. void EncryptSharedFont(const std::vector<u32>& input, std::vector<u8>& output,
  69. std::size_t& offset) {
  70. ASSERT_MSG(offset + (input.size() * sizeof(u32)) < SHARED_FONT_MEM_SIZE,
  71. "Shared fonts exceeds 17mb!");
  72. const auto key = Common::swap32(EXPECTED_RESULT ^ EXPECTED_MAGIC);
  73. std::vector<u32> transformed_font(input.size() + 2);
  74. transformed_font[0] = Common::swap32(EXPECTED_MAGIC);
  75. transformed_font[1] = Common::swap32(static_cast<u32>(input.size() * sizeof(u32))) ^ key;
  76. std::transform(input.begin(), input.end(), transformed_font.begin() + 2,
  77. [key](u32 in) { return in ^ key; });
  78. std::memcpy(output.data() + offset, transformed_font.data(),
  79. transformed_font.size() * sizeof(u32));
  80. offset += transformed_font.size() * sizeof(u32);
  81. }
  82. // Helper function to make BuildSharedFontsRawRegions a bit nicer
  83. static u32 GetU32Swapped(const u8* data) {
  84. u32 value;
  85. std::memcpy(&value, data, sizeof(value));
  86. return Common::swap32(value);
  87. }
  88. struct PL_U::Impl {
  89. const FontRegion& GetSharedFontRegion(std::size_t index) const {
  90. if (index >= shared_font_regions.size() || shared_font_regions.empty()) {
  91. // No font fallback
  92. return EMPTY_REGION;
  93. }
  94. return shared_font_regions.at(index);
  95. }
  96. void BuildSharedFontsRawRegions(const Kernel::PhysicalMemory& input) {
  97. // As we can derive the xor key we can just populate the offsets
  98. // based on the shared memory dump
  99. unsigned cur_offset = 0;
  100. for (std::size_t i = 0; i < SHARED_FONTS.size(); i++) {
  101. // Out of shared fonts/invalid font
  102. if (GetU32Swapped(input.data() + cur_offset) != EXPECTED_RESULT) {
  103. break;
  104. }
  105. // Derive key withing inverse xor
  106. const u32 KEY = GetU32Swapped(input.data() + cur_offset) ^ EXPECTED_MAGIC;
  107. const u32 SIZE = GetU32Swapped(input.data() + cur_offset + 4) ^ KEY;
  108. shared_font_regions.push_back(FontRegion{cur_offset + 8, SIZE});
  109. cur_offset += SIZE + 8;
  110. }
  111. }
  112. /// Backing memory for the shared font data
  113. std::shared_ptr<Kernel::PhysicalMemory> shared_font;
  114. // Automatically populated based on shared_fonts dump or system archives.
  115. std::vector<FontRegion> shared_font_regions;
  116. };
  117. PL_U::PL_U(Core::System& system_)
  118. : ServiceFramework{system_, "pl:u"}, impl{std::make_unique<Impl>()} {
  119. // clang-format off
  120. static const FunctionInfo functions[] = {
  121. {0, &PL_U::RequestLoad, "RequestLoad"},
  122. {1, &PL_U::GetLoadState, "GetLoadState"},
  123. {2, &PL_U::GetSize, "GetSize"},
  124. {3, &PL_U::GetSharedMemoryAddressOffset, "GetSharedMemoryAddressOffset"},
  125. {4, &PL_U::GetSharedMemoryNativeHandle, "GetSharedMemoryNativeHandle"},
  126. {5, &PL_U::GetSharedFontInOrderOfPriority, "GetSharedFontInOrderOfPriority"},
  127. {6, nullptr, "GetSharedFontInOrderOfPriorityForSystem"},
  128. {100, nullptr, "RequestApplicationFunctionAuthorization"},
  129. {101, nullptr, "RequestApplicationFunctionAuthorizationByProcessId"},
  130. {102, nullptr, "RequestApplicationFunctionAuthorizationByApplicationId"},
  131. {103, nullptr, "RefreshApplicationFunctionBlackListDebugRecord"},
  132. {104, nullptr, "RequestApplicationFunctionAuthorizationByProgramId"},
  133. {105, nullptr, "GetFunctionBlackListSystemVersionToAuthorize"},
  134. {106, nullptr, "GetFunctionBlackListVersion"},
  135. {1000, nullptr, "LoadNgWordDataForPlatformRegionChina"},
  136. {1001, nullptr, "GetNgWordDataSizeForPlatformRegionChina"},
  137. };
  138. // clang-format on
  139. RegisterHandlers(functions);
  140. auto& fsc = system.GetFileSystemController();
  141. // Attempt to load shared font data from disk
  142. const auto* nand = fsc.GetSystemNANDContents();
  143. std::size_t offset = 0;
  144. // Rebuild shared fonts from data ncas or synthesize
  145. impl->shared_font = std::make_shared<Kernel::PhysicalMemory>(SHARED_FONT_MEM_SIZE);
  146. for (auto font : SHARED_FONTS) {
  147. FileSys::VirtualFile romfs;
  148. const auto nca =
  149. nand->GetEntry(static_cast<u64>(font.first), FileSys::ContentRecordType::Data);
  150. if (nca) {
  151. romfs = nca->GetRomFS();
  152. }
  153. if (!romfs) {
  154. romfs = FileSys::SystemArchive::SynthesizeSystemArchive(static_cast<u64>(font.first));
  155. }
  156. if (!romfs) {
  157. LOG_ERROR(Service_NS, "Failed to find or synthesize {:016X}! Skipping", font.first);
  158. continue;
  159. }
  160. const auto extracted_romfs = FileSys::ExtractRomFS(romfs);
  161. if (!extracted_romfs) {
  162. LOG_ERROR(Service_NS, "Failed to extract RomFS for {:016X}! Skipping", font.first);
  163. continue;
  164. }
  165. const auto font_fp = extracted_romfs->GetFile(font.second);
  166. if (!font_fp) {
  167. LOG_ERROR(Service_NS, "{:016X} has no file \"{}\"! Skipping", font.first, font.second);
  168. continue;
  169. }
  170. std::vector<u32> font_data_u32(font_fp->GetSize() / sizeof(u32));
  171. font_fp->ReadBytes<u32>(font_data_u32.data(), font_fp->GetSize());
  172. // We need to be BigEndian as u32s for the xor encryption
  173. std::transform(font_data_u32.begin(), font_data_u32.end(), font_data_u32.begin(),
  174. Common::swap32);
  175. // Font offset and size do not account for the header
  176. const FontRegion region{static_cast<u32>(offset + 8),
  177. static_cast<u32>((font_data_u32.size() * sizeof(u32)) - 8)};
  178. DecryptSharedFont(font_data_u32, *impl->shared_font, offset);
  179. impl->shared_font_regions.push_back(region);
  180. }
  181. }
  182. PL_U::~PL_U() = default;
  183. void PL_U::RequestLoad(Kernel::HLERequestContext& ctx) {
  184. IPC::RequestParser rp{ctx};
  185. const u32 shared_font_type{rp.Pop<u32>()};
  186. // Games don't call this so all fonts should be loaded
  187. LOG_DEBUG(Service_NS, "called, shared_font_type={}", shared_font_type);
  188. IPC::ResponseBuilder rb{ctx, 2};
  189. rb.Push(ResultSuccess);
  190. }
  191. void PL_U::GetLoadState(Kernel::HLERequestContext& ctx) {
  192. IPC::RequestParser rp{ctx};
  193. const u32 font_id{rp.Pop<u32>()};
  194. LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
  195. IPC::ResponseBuilder rb{ctx, 3};
  196. rb.Push(ResultSuccess);
  197. rb.Push<u32>(static_cast<u32>(LoadState::Done));
  198. }
  199. void PL_U::GetSize(Kernel::HLERequestContext& ctx) {
  200. IPC::RequestParser rp{ctx};
  201. const u32 font_id{rp.Pop<u32>()};
  202. LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
  203. IPC::ResponseBuilder rb{ctx, 3};
  204. rb.Push(ResultSuccess);
  205. rb.Push<u32>(impl->GetSharedFontRegion(font_id).size);
  206. }
  207. void PL_U::GetSharedMemoryAddressOffset(Kernel::HLERequestContext& ctx) {
  208. IPC::RequestParser rp{ctx};
  209. const u32 font_id{rp.Pop<u32>()};
  210. LOG_DEBUG(Service_NS, "called, font_id={}", font_id);
  211. IPC::ResponseBuilder rb{ctx, 3};
  212. rb.Push(ResultSuccess);
  213. rb.Push<u32>(impl->GetSharedFontRegion(font_id).offset);
  214. }
  215. void PL_U::GetSharedMemoryNativeHandle(Kernel::HLERequestContext& ctx) {
  216. // Map backing memory for the font data
  217. LOG_DEBUG(Service_NS, "called");
  218. // Create shared font memory object
  219. auto& kernel = system.Kernel();
  220. std::memcpy(kernel.GetFontSharedMem().GetPointer(), impl->shared_font->data(),
  221. impl->shared_font->size());
  222. IPC::ResponseBuilder rb{ctx, 2, 1};
  223. rb.Push(ResultSuccess);
  224. rb.PushCopyObjects(&kernel.GetFontSharedMem());
  225. }
  226. void PL_U::GetSharedFontInOrderOfPriority(Kernel::HLERequestContext& ctx) {
  227. IPC::RequestParser rp{ctx};
  228. const u64 language_code{rp.Pop<u64>()}; // TODO(ogniK): Find out what this is used for
  229. LOG_DEBUG(Service_NS, "called, language_code={:X}", language_code);
  230. IPC::ResponseBuilder rb{ctx, 4};
  231. std::vector<u32> font_codes;
  232. std::vector<u32> font_offsets;
  233. std::vector<u32> font_sizes;
  234. // TODO(ogniK): Have actual priority order
  235. for (std::size_t i = 0; i < impl->shared_font_regions.size(); i++) {
  236. font_codes.push_back(static_cast<u32>(i));
  237. auto region = impl->GetSharedFontRegion(i);
  238. font_offsets.push_back(region.offset);
  239. font_sizes.push_back(region.size);
  240. }
  241. // Resize buffers if game requests smaller size output.
  242. font_codes.resize(
  243. std::min<std::size_t>(font_codes.size(), ctx.GetWriteBufferSize(0) / sizeof(u32)));
  244. font_offsets.resize(
  245. std::min<std::size_t>(font_offsets.size(), ctx.GetWriteBufferSize(1) / sizeof(u32)));
  246. font_sizes.resize(
  247. std::min<std::size_t>(font_sizes.size(), ctx.GetWriteBufferSize(2) / sizeof(u32)));
  248. ctx.WriteBuffer(font_codes, 0);
  249. ctx.WriteBuffer(font_offsets, 1);
  250. ctx.WriteBuffer(font_sizes, 2);
  251. rb.Push(ResultSuccess);
  252. rb.Push<u8>(static_cast<u8>(LoadState::Done)); // Fonts Loaded
  253. rb.Push<u32>(static_cast<u32>(font_codes.size()));
  254. }
  255. } // namespace Service::NS