pl_u.cpp 12 KB

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