pl_u.cpp 13 KB

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