pl_u.cpp 12 KB

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