pl_u.cpp 15 KB

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