id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,823
|
erpt_srv_keys.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_keys.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "erpt_srv_keys.hpp"
namespace ams::erpt::srv {
namespace {
constexpr const u8 PublicKeyModulusProduction[] = {
0x00,
0xAB, 0xB6, 0x6C, 0x43, 0x86, 0xDF, 0x52, 0x5F, 0xB9, 0xD3, 0x61, 0xEB, 0xFB, 0x16, 0x2B, 0x44,
0xE1, 0x1F, 0xDD, 0x81, 0xFA, 0x20, 0x48, 0x7B, 0xDB, 0x17, 0x9F, 0x9A, 0x92, 0x1E, 0x0A, 0x80,
0xD1, 0x1A, 0x4F, 0xD7, 0x49, 0xFE, 0xBA, 0x65, 0xE4, 0x61, 0x08, 0x26, 0x43, 0x7B, 0x4A, 0x16,
0x59, 0x60, 0xD1, 0xE0, 0x42, 0x0A, 0x26, 0x54, 0xC4, 0xC7, 0x2A, 0xE3, 0x17, 0x1F, 0x8E, 0x35,
0x79, 0xC0, 0x1B, 0xA1, 0xF8, 0x6F, 0x5C, 0xDC, 0x05, 0x2D, 0x90, 0x75, 0xD5, 0x98, 0x7E, 0x5A,
0x07, 0x3F, 0x4E, 0x78, 0xF1, 0x69, 0x2F, 0xE9, 0x2E, 0x50, 0x01, 0x9F, 0xCE, 0x35, 0xC8, 0x4D,
0x65, 0x23, 0xA8, 0x9F, 0xC3, 0x3C, 0x4A, 0xF2, 0x29, 0x4D, 0x10, 0x03, 0x1C, 0xB4, 0x0E, 0x64,
0xB6, 0xDD, 0xB2, 0x74, 0xE3, 0x32, 0x84, 0x25, 0x99, 0xEA, 0xE1, 0x6C, 0x78, 0x24, 0xF2, 0xB0,
0xD2, 0x2C, 0xA5, 0x1A, 0x70, 0xA6, 0x49, 0x08, 0x73, 0x8A, 0x74, 0x3A, 0x12, 0x0E, 0x1B, 0x68,
0xD1, 0x6A, 0x6C, 0x3F, 0x2C, 0x2C, 0x53, 0xD5, 0xCE, 0x5A, 0x07, 0xA2, 0xB9, 0x2E, 0x0A, 0x77,
0x51, 0x4B, 0xD2, 0x8E, 0x4F, 0xA3, 0xA8, 0x56, 0x99, 0x6F, 0x63, 0xBC, 0x23, 0x04, 0x6E, 0x71,
0x57, 0x7C, 0xFD, 0x84, 0xA7, 0xF8, 0x8D, 0x7F, 0xD6, 0xA0, 0x6E, 0x92, 0xBC, 0xCC, 0x28, 0x82,
0x60, 0xE9, 0x78, 0xC1, 0x31, 0x82, 0x4F, 0xF8, 0xC5, 0xDB, 0xB6, 0x6B, 0xF9, 0x62, 0x95, 0xD3,
0xC8, 0x63, 0x59, 0x53, 0x3F, 0x82, 0xEB, 0x06, 0xA7, 0xB8, 0x55, 0xEC, 0x9E, 0x33, 0x04, 0xCF,
0x5E, 0x42, 0x32, 0x09, 0x26, 0xFF, 0xB4, 0x5E, 0xBD, 0xD7, 0xA8, 0x6B, 0x2C, 0xF5, 0x68, 0x86,
0xCD, 0x8A, 0x13, 0xF3, 0x1C, 0x5F, 0xE6, 0x4F, 0xFC, 0xD1, 0x07, 0x28, 0x5C, 0x2D, 0xA7, 0xF7
};
constexpr const u8 PublicKeyModulusDevelopment[] = {
0x00,
0xAE, 0x7D, 0x6C, 0xD0, 0xC3, 0x13, 0x61, 0x01, 0x9D, 0x1B, 0x55, 0xA0, 0xE5, 0xF4, 0x3D, 0x56,
0x7D, 0xCA, 0x0E, 0x49, 0xFB, 0x82, 0x08, 0x06, 0x33, 0xB6, 0x37, 0xB3, 0x4A, 0x3F, 0x57, 0x39,
0x05, 0x84, 0x18, 0x3D, 0x82, 0xD8, 0x8F, 0xBC, 0xF3, 0xE1, 0x66, 0xEE, 0xD2, 0x80, 0x43, 0xF8,
0xA7, 0xB7, 0x5E, 0x5B, 0x5C, 0xF9, 0x9D, 0x7F, 0xE9, 0x6C, 0x93, 0x8A, 0x65, 0xBB, 0xD1, 0xDD,
0x56, 0xFF, 0x7C, 0x9D, 0x24, 0x66, 0x09, 0x84, 0x21, 0x2C, 0x7F, 0x0A, 0xB8, 0x31, 0x42, 0x29,
0xE6, 0xD3, 0x20, 0x76, 0xA1, 0x1F, 0x7E, 0x59, 0x5B, 0x7C, 0xF6, 0xC6, 0x02, 0xDB, 0xC9, 0x1B,
0xB9, 0x24, 0x99, 0xAD, 0x0F, 0x7B, 0x0D, 0x8E, 0x7E, 0x01, 0xFE, 0x95, 0xCE, 0x9B, 0xB5, 0x09,
0xC5, 0xF5, 0xA5, 0x6A, 0x82, 0xF6, 0x57, 0xF8, 0x06, 0x72, 0xAE, 0x73, 0x71, 0xD1, 0x09, 0x2B,
0xE2, 0x84, 0x0D, 0x66, 0x39, 0xB6, 0x21, 0x8B, 0x35, 0xE4, 0xDF, 0x90, 0x36, 0xE1, 0x3F, 0xC0,
0x9F, 0xF8, 0x85, 0x03, 0xD6, 0xCA, 0xBB, 0x1A, 0x62, 0x2D, 0xE5, 0x03, 0xF6, 0x47, 0x00, 0x6E,
0x98, 0x5A, 0x1C, 0x51, 0x94, 0x47, 0xF6, 0x83, 0x0C, 0x25, 0xBD, 0xBE, 0xBD, 0x6A, 0x35, 0xC0,
0xAB, 0x65, 0xF8, 0x01, 0xF4, 0xC3, 0x2A, 0xA3, 0xBC, 0xD7, 0xD9, 0xF7, 0x2A, 0x98, 0x27, 0xE1,
0x3F, 0x9A, 0xCF, 0xDF, 0xB1, 0x30, 0x82, 0xA4, 0xAA, 0x78, 0xCA, 0xC8, 0xB8, 0x34, 0xFA, 0xA7,
0x75, 0x23, 0xC9, 0x9C, 0x11, 0x68, 0x7E, 0x0F, 0x80, 0x8F, 0x90, 0xA6, 0xDE, 0x2B, 0x47, 0x5B,
0x94, 0x6F, 0xB9, 0x67, 0x4C, 0xC1, 0xAE, 0x50, 0x8F, 0xD8, 0xE3, 0xD1, 0xF2, 0x92, 0x54, 0x4C,
0x25, 0x02, 0x5B, 0x31, 0x65, 0x5E, 0x41, 0x81, 0x34, 0xF4, 0xF1, 0x34, 0xE7, 0x64, 0x7A, 0xC1
};
constexpr const u8 PublicKeyExponent[] = {
0x01, 0x00, 0x01
};
bool IsProductionModeImpl() {
bool is_prod = true;
if (settings::fwdbg::GetSettingsItemValue(std::addressof(is_prod), sizeof(is_prod), "erpt", "production_mode") != sizeof(is_prod)) {
return true;
}
return is_prod;
}
bool IsProductionMode() {
AMS_FUNCTION_LOCAL_STATIC(bool, s_is_prod_mode, IsProductionModeImpl());
return s_is_prod_mode;
}
}
const u8 *GetPublicKeyModulus() {
return IsProductionMode() ? PublicKeyModulusProduction : PublicKeyModulusDevelopment;
}
size_t GetPublicKeyModulusSize() {
return IsProductionMode() ? sizeof(PublicKeyModulusProduction) : sizeof(PublicKeyModulusDevelopment);
}
const u8 *GetPublicKeyExponent() {
return PublicKeyExponent;
}
size_t GetPublicKeyExponentSize() {
return sizeof(PublicKeyExponent);
}
}
| 5,402
|
C++
|
.cpp
| 85
| 54.458824
| 144
| 0.622101
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,824
|
erpt_srv_forced_shutdown.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_forced_shutdown.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "erpt_srv_forced_shutdown.hpp"
#include "erpt_srv_context.hpp"
#include "erpt_srv_context_record.hpp"
#include "erpt_srv_reporter.hpp"
#include "erpt_srv_stream.hpp"
namespace ams::erpt::srv {
namespace {
constexpr u32 ForcedShutdownContextBufferSize = 1_KB;
constexpr u32 ForcedShutdownContextVersion = 1;
struct ForcedShutdownContextHeader {
u32 version;
u32 num_contexts;
};
static_assert(sizeof(ForcedShutdownContextHeader) == 8);
struct ForcedShutdownContextEntry {
u32 version;
CategoryId category;
u32 field_count;
u32 array_buffer_size;
};
static_assert(sizeof(ForcedShutdownContextEntry) == 16);
os::Event g_forced_shutdown_update_event(os::EventClearMode_ManualClear);
constinit ContextEntry g_forced_shutdown_contexts[] = {
{ .category = CategoryId_RunningApplicationInfo, },
{ .category = CategoryId_RunningAppletInfo, },
{ .category = CategoryId_FocusedAppletHistoryInfo, },
};
bool IsForceShutdownDetected() {
fs::DirectoryEntryType entry_type;
return R_SUCCEEDED(fs::GetEntryType(std::addressof(entry_type), ForcedShutdownContextFileName));
}
Result CreateForcedShutdownContext() {
/* Create the context. */
{
/* Create the stream. */
Stream stream;
R_TRY(stream.OpenStream(ForcedShutdownContextFileName, StreamMode_Write, 0));
/* Write a context header. */
const ForcedShutdownContextHeader header = { .version = ForcedShutdownContextVersion, .num_contexts = 0, };
R_TRY(stream.WriteStream(reinterpret_cast<const u8 *>(std::addressof(header)), sizeof(header)));
}
/* Commit the context. */
R_TRY(Stream::CommitStream());
R_SUCCEED();
}
Result CreateReportForForcedShutdown() {
/* Create a new context record. */
/* NOTE: Nintendo does not check that this allocation succeeds. */
auto record = std::make_unique<ContextRecord>(CategoryId_ErrorInfo);
/* Create error code for the report. */
char error_code_str[err::ErrorCode::StringLengthMax];
err::GetErrorCodeString(error_code_str, sizeof(error_code_str), err::ConvertResultToErrorCode(err::ResultForcedShutdownDetected()));
/* Add error code to the context. */
R_TRY(record->Add(FieldId_ErrorCode, error_code_str, std::strlen(error_code_str)));
/* Create report. */
R_TRY(Reporter::CreateReport(ReportType_Invisible, ResultSuccess(), std::move(record), nullptr, nullptr, 0, erpt::srv::MakeNoCreateReportOptionFlags()));
R_SUCCEED();
}
Result LoadForcedShutdownContext() {
/* Create the stream to read the context. */
Stream stream;
R_TRY(stream.OpenStream(ForcedShutdownContextFileName, StreamMode_Read, ForcedShutdownContextBufferSize));
/* Read the header. */
u32 read_size;
ForcedShutdownContextHeader header;
R_TRY(stream.ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(header)), sizeof(header)));
/* Validate the header. */
R_SUCCEED_IF(read_size != sizeof(header));
R_SUCCEED_IF(ForcedShutdownContextVersion);
R_SUCCEED_IF(header.num_contexts == 0);
/* Read out the contexts. */
for (u32 i = 0; i < header.num_contexts; ++i) {
/* Read the context entry header. */
ForcedShutdownContextEntry entry_header;
R_TRY(stream.ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(entry_header)), sizeof(entry_header)));
if (read_size != sizeof(entry_header)) {
break;
}
if (entry_header.field_count == 0) {
continue;
}
/* Read the saved data into a context entry. */
ContextEntry ctx = {
.version = entry_header.version,
.field_count = entry_header.field_count,
.category = entry_header.category,
};
/* Check that the field count is valid. */
AMS_ABORT_UNLESS(entry_header.field_count <= util::size(ctx.fields));
/* Read the fields. */
R_TRY(stream.ReadStream(std::addressof(read_size), reinterpret_cast<u8 *>(std::addressof(ctx.fields)), entry_header.field_count * sizeof(ctx.fields[0])));
if (read_size != entry_header.field_count * sizeof(ctx.fields[0])) {
break;
}
/* Allocate an array buffer. */
u8 *array_buffer = static_cast<u8 *>(Allocate(entry_header.array_buffer_size));
if (array_buffer == nullptr) {
break;
}
ON_SCOPE_EXIT { Deallocate(array_buffer); };
/* Read the array buffer data. */
R_TRY(stream.ReadStream(std::addressof(read_size), array_buffer, entry_header.array_buffer_size));
if (read_size != entry_header.array_buffer_size) {
break;
}
/* Create a record for the context. */
auto record = std::make_unique<ContextRecord>();
if (record == nullptr) {
break;
}
/* Initialize the record. */
R_TRY(record->Initialize(std::addressof(ctx), array_buffer, entry_header.array_buffer_size));
/* Submit the record. */
R_TRY(Context::SubmitContextRecord(std::move(record)));
}
R_SUCCEED();
}
u32 GetForcedShutdownContextCount() {
u32 count = 0;
for (const auto &ctx : g_forced_shutdown_contexts) {
if (ctx.field_count != 0) {
++count;
}
}
return count;
}
Result SaveForcedShutdownContextImpl() {
/* Save context to file. */
{
/* Create the stream to write the context. */
Stream stream;
R_TRY(stream.OpenStream(ForcedShutdownContextFileName, StreamMode_Write, ForcedShutdownContextBufferSize));
/* Write a context header. */
const ForcedShutdownContextHeader header = { .version = ForcedShutdownContextVersion, .num_contexts = GetForcedShutdownContextCount(), };
R_TRY(stream.WriteStream(reinterpret_cast<const u8 *>(std::addressof(header)), sizeof(header)));
/* Write each context. */
for (const auto &ctx : g_forced_shutdown_contexts) {
/* If the context has no fields, continue. */
if (ctx.field_count == 0) {
continue;
}
/* Write a context entry header. */
const ForcedShutdownContextEntry entry_header = {
.version = ctx.version,
.category = ctx.category,
.field_count = ctx.field_count,
.array_buffer_size = ctx.array_buffer_size,
};
R_TRY(stream.WriteStream(reinterpret_cast<const u8 *>(std::addressof(entry_header)), sizeof(entry_header)));
/* Write all fields. */
for (u32 i = 0; i < ctx.field_count; ++i) {
R_TRY(stream.WriteStream(reinterpret_cast<const u8 *>(ctx.fields + i), sizeof(ctx.fields[0])));
}
/* Write the array buffer. */
R_TRY(stream.WriteStream(ctx.array_buffer, ctx.array_buffer_size));
}
}
/* Commit the context. */
R_TRY(Stream::CommitStream());
R_SUCCEED();
}
}
os::Event *GetForcedShutdownUpdateEvent() {
return std::addressof(g_forced_shutdown_update_event);
}
void InitializeForcedShutdownDetection() {
/* Check if the forced shutdown context exists; if it doesn't, we should create an empty one. */
if (!IsForceShutdownDetected()) {
/* NOTE: Nintendo does not check result here. */
CreateForcedShutdownContext();
return;
}
/* Load the forced shutdown context. */
/* NOTE: Nintendo does not check that this succeeds. */
LoadForcedShutdownContext();
/* Create report for the forced shutdown. */
/* NOTE: Nintendo does not check that this succeeds. */
CreateReportForForcedShutdown();
/* Clear the forced shutdown categories. */
/* NOTE: Nintendo does not check that this succeeds. */
Context::ClearContext(CategoryId_RunningApplicationInfo);
Context::ClearContext(CategoryId_RunningAppletInfo);
Context::ClearContext(CategoryId_FocusedAppletHistoryInfo);
/* Save the forced shutdown context. */
/* NOTE: Nintendo does not check that this succeeds. */
SaveForcedShutdownContext();
}
void FinalizeForcedShutdownDetection() {
/* Try to delete the context. */
const Result result = Stream::DeleteStream(ForcedShutdownContextFileName);
if (!fs::ResultPathNotFound::Includes(result)) {
/* We must have succeeded, if the file existed. */
R_ABORT_UNLESS(result);
/* Commit the deletion. */
R_ABORT_UNLESS(Stream::CommitStream());
}
}
void SaveForcedShutdownContext() {
/* NOTE: Nintendo does not check that saving the report succeeds. */
SaveForcedShutdownContextImpl();
}
void SubmitContextForForcedShutdownDetection(const ContextEntry *entry, const u8 *data, u32 data_size) {
/* If the context entry matches one of our tracked categories, update our stored category. */
for (auto &ctx : g_forced_shutdown_contexts) {
/* Check for a match. */
if (ctx.category != entry->category) {
continue;
}
/* If we have an existing array buffer, free it. */
if (ctx.array_buffer != nullptr) {
Deallocate(ctx.array_buffer);
ctx.array_buffer = nullptr;
ctx.array_buffer_size = 0;
ctx.array_free_count = 0;
}
/* Copy in the context. */
ctx = *entry;
/* Add the submitted data. */
if (data != nullptr && data_size > 0) {
/* Allocate new array buffer. */
ctx.array_buffer = static_cast<u8 *>(Allocate(data_size));
if (ctx.array_buffer == nullptr) {
/* We failed to allocate; this is okay, but clear our field count. */
ctx.field_count = 0;
break;
}
/* Copy in the data. */
std::memcpy(ctx.array_buffer, data, data_size);
/* Set buffer extents. */
ctx.array_buffer_size = data_size;
ctx.array_free_count = 0;
} else {
ctx.array_buffer = nullptr;
ctx.array_buffer_size = 0;
ctx.array_free_count = 0;
}
/* Signal, to notify that we had an update. */
g_forced_shutdown_update_event.Signal();
/* We're done processing, since we found a match. */
break;
}
}
Result InvalidateForcedShutdownDetection() {
/* Delete the forced shutdown context. */
R_TRY(Stream::DeleteStream(ForcedShutdownContextFileName));
/* Commit the deletion. */
R_TRY(Stream::CommitStream());
R_SUCCEED();
}
}
| 12,924
|
C++
|
.cpp
| 266
| 35.545113
| 170
| 0.567299
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,825
|
erpt_srv_context_record.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/erpt/srv/erpt_srv_context_record.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "erpt_srv_context_record.hpp"
namespace ams::erpt::srv {
constinit u32 ContextRecord::s_record_count = 0;
namespace {
bool IsArrayFieldType(FieldType type) {
return type == FieldType_String ||
type == FieldType_U8Array ||
type == FieldType_U32Array ||
type == FieldType_U64Array ||
type == FieldType_I32Array ||
type == FieldType_I64Array;
}
}
ContextRecord::ContextRecord() {
m_ctx = {};
}
ContextRecord::ContextRecord(CategoryId category, u32 array_buf_size) {
m_ctx = {
.category = category,
.array_buffer = static_cast<u8 *>(Allocate(array_buf_size)),
};
if (m_ctx.array_buffer != nullptr) {
m_ctx.array_buffer_size = array_buf_size;
m_ctx.array_free_count = array_buf_size;
}
}
ContextRecord::~ContextRecord() {
if (m_ctx.array_buffer != nullptr) {
Deallocate(m_ctx.array_buffer);
}
AMS_ABORT_UNLESS(s_record_count >= m_ctx.field_count);
s_record_count -= m_ctx.field_count;
}
Result ContextRecord::Initialize(const ContextEntry *ctx_ptr, const u8 *data, u32 data_size) {
R_UNLESS(data_size <= ArrayBufferSizeMax, erpt::ResultInvalidArgument());
m_ctx.version = ctx_ptr->version;
m_ctx.field_count = ctx_ptr->field_count;
m_ctx.category = ctx_ptr->category;
m_ctx.array_buffer = nullptr;
m_ctx.array_buffer_size = data_size;
m_ctx.array_free_count = 0;
auto guard = SCOPE_GUARD { m_ctx.field_count = 0; };
R_UNLESS(m_ctx.field_count <= FieldsPerContext, erpt::ResultInvalidArgument());
R_UNLESS(FindCategoryIndex(m_ctx.category).has_value(), erpt::ResultInvalidArgument());
for (u32 i = 0; i < m_ctx.field_count; i++) {
m_ctx.fields[i] = ctx_ptr->fields[i];
R_UNLESS(FindFieldIndex(m_ctx.fields[i].id).has_value(), erpt::ResultInvalidArgument());
R_UNLESS(0 <= m_ctx.fields[i].type && m_ctx.fields[i].type < FieldType_Count, erpt::ResultInvalidArgument());
R_UNLESS(m_ctx.fields[i].type == ConvertFieldToType(m_ctx.fields[i].id), erpt::ResultFieldTypeMismatch());
R_UNLESS(m_ctx.category == ConvertFieldToCategory(m_ctx.fields[i].id), erpt::ResultFieldCategoryMismatch());
if (IsArrayFieldType(m_ctx.fields[i].type)) {
const u32 start_idx = m_ctx.fields[i].value_array.start_idx;
const u32 size = m_ctx.fields[i].value_array.size;
const u32 end_idx = start_idx + size;
R_UNLESS(start_idx <= data_size, erpt::ResultInvalidArgument());
R_UNLESS(size <= data_size, erpt::ResultInvalidArgument());
R_UNLESS(end_idx <= data_size, erpt::ResultInvalidArgument());
R_UNLESS(size <= ArrayFieldSizeMax, erpt::ResultInvalidArgument());
}
}
if (data_size > 0) {
/* If array buffer isn't nullptr, we'll leak memory here, so verify that it is. */
AMS_ABORT_UNLESS(m_ctx.array_buffer == nullptr);
m_ctx.array_buffer = static_cast<u8 *>(AllocateWithAlign(data_size, alignof(u64)));
R_UNLESS(m_ctx.array_buffer != nullptr, erpt::ResultOutOfMemory());
std::memcpy(m_ctx.array_buffer, data, data_size);
}
guard.Cancel();
s_record_count += m_ctx.field_count;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, bool value_bool) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = FieldType_Bool;
field.value_bool = value_bool;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, u32 value_u32) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = FieldType_NumericU32;
field.value_u32 = value_u32;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, u64 value_u64) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = FieldType_NumericU64;
field.value_u64 = value_u64;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, s32 value_i32) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = FieldType_NumericI32;
field.value_i32 = value_i32;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, s64 value_i64) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = FieldType_NumericI64;
field.value_i64 = value_i64;
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, const void *arr, u32 size, FieldType type) {
R_UNLESS(m_ctx.field_count < FieldsPerContext, erpt::ResultOutOfFieldSpace());
R_UNLESS(size <= m_ctx.array_free_count, erpt::ResultOutOfArraySpace());
const u32 start_idx = m_ctx.array_buffer_size - m_ctx.array_free_count;
m_ctx.array_free_count -= size;
s_record_count++;
auto &field = m_ctx.fields[m_ctx.field_count++];
field.id = field_id;
field.type = type;
field.value_array = {
.start_idx = start_idx,
.size = size,
};
std::memcpy(m_ctx.array_buffer + start_idx, arr, size);
R_SUCCEED();
}
Result ContextRecord::Add(FieldId field_id, const char *str, u32 str_size) {
R_RETURN(this->Add(field_id, str, str_size, FieldType_String));
}
Result ContextRecord::Add(FieldId field_id, const u8 *data, u32 size) {
R_RETURN(this->Add(field_id, data, size, FieldType_U8Array));
}
}
| 7,280
|
C++
|
.cpp
| 155
| 37.954839
| 126
| 0.608659
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,826
|
osdbg_thread.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/osdbg/osdbg_thread.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#if defined(ATMOSPHERE_OS_HORIZON)
#include "impl/osdbg_thread_info.os.horizon.hpp"
#else
#include "impl/osdbg_thread_info.generic.hpp"
#endif
namespace ams::osdbg {
Result InitializeThreadInfo(ThreadInfo *thread_info, os::NativeHandle debug_handle, const osdbg::DebugInfoCreateProcess *create_process, const osdbg::DebugInfoCreateThread *create_thread) {
/* Set basic fields. */
thread_info->_thread_type = nullptr;
thread_info->_thread_type_type = ThreadTypeType_Unknown;
thread_info->_debug_handle = debug_handle;
#if defined(ATMOSPHERE_OS_HORIZON)
thread_info->_debug_info_create_process = *create_process;
thread_info->_debug_info_create_thread = *create_thread;
#else
AMS_UNUSED(create_process, create_thread);
#endif
/* Update the current info. */
R_RETURN(impl::ThreadInfoImpl::FillWithCurrentInfo(thread_info));
}
Result UpdateThreadInfo(ThreadInfo *thread_info) {
/* Update the current info. */
R_RETURN(impl::ThreadInfoImpl::FillWithCurrentInfo(thread_info));
}
Result GetThreadName(char *dst, const ThreadInfo *thread_info) {
#if defined(ATMOSPHERE_OS_HORIZON)
/* Read the name. */
if (const auto name_pointer = GetThreadNamePointer(thread_info); name_pointer != 0) {
R_RETURN(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(dst), thread_info->_debug_handle, name_pointer, os::ThreadNameLengthMax));
} else {
/* Special-case libnx threads. */
if (thread_info->_thread_type_type == ThreadTypeType_Libnx) {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "libnx Thread_0x%010" PRIx64 "", reinterpret_cast<uintptr_t>(thread_info->_thread_type));
} else {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_0x%010" PRIx64 "", reinterpret_cast<uintptr_t>(thread_info->_thread_type));
}
R_SUCCEED();
}
#else
util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_0x%010" PRIx64 "", static_cast<u64>(reinterpret_cast<uintptr_t>(thread_info->_thread_type)));
R_SUCCEED();
#endif
}
}
| 2,923
|
C++
|
.cpp
| 60
| 42.016667
| 193
| 0.672504
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,827
|
osdbg_thread_info.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/osdbg/impl/osdbg_thread_info.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "osdbg_thread_info.os.horizon.hpp"
#include "osdbg_thread_type.os.horizon.hpp"
#include "osdbg_thread_local_region.os.horizon.hpp"
#include "../../os/impl/os_thread_manager_impl.os.horizon.hpp"
namespace ams::osdbg::impl {
namespace {
s32 ConvertToUserPriority(s32 horizon_priority) {
return horizon_priority - os::impl::UserThreadPriorityOffset;
}
s32 GetCurrentThreadPriorityImpl(const ThreadInfo *info) {
u64 dummy;
u32 horizon_priority;
if (R_FAILED(svc::GetDebugThreadParam(std::addressof(dummy), std::addressof(horizon_priority), info->_debug_handle, info->_debug_info_create_thread.thread_id, svc::DebugThreadParam_Priority))) {
return info->_base_priority;
}
return ConvertToUserPriority(static_cast<s32>(horizon_priority));
}
void FillWithCurrentInfoImpl(ThreadInfo *info, const auto &thread_type_impl) {
/* Set fields. */
info->_base_priority = thread_type_impl._base_priority;
info->_current_priority = GetCurrentThreadPriorityImpl(info);
info->_stack_size = thread_type_impl._stack_size;
info->_stack = thread_type_impl._stack;
info->_argument = thread_type_impl._argument;
info->_function = thread_type_impl._thread_function;
info->_name_pointer = thread_type_impl._name_pointer;
}
}
Result ThreadInfoHorizonImpl::FillWithCurrentInfo(ThreadInfo *info) {
/* Detect lp64. */
const bool is_lp64 = IsLp64(info);
/* Ensure that we have a thread type. */
if (info->_thread_type == nullptr) {
/* Ensure we exit with correct thread type. */
auto thread_guard = SCOPE_GUARD { info->_thread_type = nullptr; };
/* Set the target thread type. */
GetTargetThreadType(info);
/* If it's still nullptr, we failed to get the thread type. */
R_UNLESS(info->_thread_type != nullptr, osdbg::ResultCannotGetThreadInfo());
/* Check that the thread type is valid. */
R_UNLESS(info->_thread_type_type != ThreadTypeType_Unknown, osdbg::ResultUnsupportedThreadVersion());
/* We successfully got the thread type. */
thread_guard.Cancel();
}
/* Read and process the thread type. */
ThreadTypeCommon thread_type;
switch (info->_thread_type_type) {
case ThreadTypeType_Nintendo:
if (is_lp64) {
/* Read in the thread type. */
R_TRY(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(thread_type.lp64)), info->_debug_handle, reinterpret_cast<uintptr_t>(info->_thread_type), sizeof(thread_type.lp64)));
/* Process different versions. */
switch (thread_type.lp64._version) {
case 0x0000:
case 0xFFFF:
FillWithCurrentInfoImpl(info, thread_type.lp64_v0);
break;
case 0x0001:
FillWithCurrentInfoImpl(info, thread_type.lp64);
break;
default:
R_THROW(osdbg::ResultUnsupportedThreadVersion());
}
} else {
/* Read in the thread type. */
R_TRY(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(thread_type.ilp32)), info->_debug_handle, reinterpret_cast<uintptr_t>(info->_thread_type), sizeof(thread_type.ilp32)));
/* Process different versions. */
switch (thread_type.ilp32._version) {
case 0x0000:
case 0xFFFF:
FillWithCurrentInfoImpl(info, thread_type.ilp32_v0);
break;
case 0x0001:
FillWithCurrentInfoImpl(info, thread_type.ilp32);
break;
default:
R_THROW(osdbg::ResultUnsupportedThreadVersion());
}
}
break;
case ThreadTypeType_Stratosphere:
{
/* Read in the thread type. */
R_TRY(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(thread_type.stratosphere)), info->_debug_handle, reinterpret_cast<uintptr_t>(info->_thread_type), sizeof(thread_type.stratosphere)));
/* Set fields. */
const auto &thread_type_impl = thread_type.stratosphere;
/* Check that our thread version is valid. */
R_UNLESS(thread_type_impl.version == 0x0000 || thread_type_impl.version == 0xFFFF, osdbg::ResultUnsupportedThreadVersion());
info->_base_priority = thread_type_impl.base_priority;
info->_current_priority = GetCurrentThreadPriorityImpl(info);
info->_stack_size = thread_type_impl.stack_size;
info->_stack = reinterpret_cast<uintptr_t>(thread_type_impl.stack);
info->_argument = reinterpret_cast<uintptr_t>(thread_type_impl.argument);
info->_function = reinterpret_cast<uintptr_t>(thread_type_impl.function);
info->_name_pointer = reinterpret_cast<uintptr_t>(thread_type_impl.name_pointer);
}
break;
case ThreadTypeType_Libnx:
{
/* Read in the thread type. */
R_TRY(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(thread_type.libnx)), info->_debug_handle, reinterpret_cast<uintptr_t>(info->_thread_type), sizeof(thread_type.libnx)));
/* Set fields. */
const auto &thread_type_impl = thread_type.libnx;
/* NOTE: libnx does not store/track base priority anywhere. */
info->_base_priority = -1;
info->_current_priority = GetCurrentThreadPriorityImpl(info);
if (info->_current_priority != info->_base_priority) {
info->_base_priority = info->_current_priority;
}
info->_stack_size = thread_type_impl.stack_sz;
info->_stack = reinterpret_cast<uintptr_t>(thread_type_impl.stack_mirror);
/* Parse thread entry args. */
{
LibnxThreadEntryArgs thread_entry_args;
if (R_SUCCEEDED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(thread_entry_args)), info->_debug_handle, info->_stack + info->_stack_size, sizeof(LibnxThreadEntryArgs)))) {
info->_argument = thread_entry_args.arg;
info->_function = thread_entry_args.entry;
} else {
/* Failed to read the argument/function. */
info->_argument = 0;
info->_function = 0;
}
}
/* Libnx threads don't have names. */
info->_name_pointer = 0;
}
break;
default:
R_THROW(osdbg::ResultUnsupportedThreadVersion());
}
R_SUCCEED();
}
}
| 8,415
|
C++
|
.cpp
| 149
| 40.543624
| 230
| 0.553101
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,828
|
osdbg_thread_local_region.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/osdbg/impl/osdbg_thread_local_region.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "osdbg_thread_info.os.horizon.hpp"
#include "osdbg_thread_type.os.horizon.hpp"
#include "osdbg_thread_local_region.os.horizon.hpp"
namespace ams::osdbg::impl {
namespace {
Result GetThreadTypePointerFromThreadLocalRegion(uintptr_t *out, ThreadInfo *info) {
/* Detect lp64. */
const bool is_lp64 = IsLp64(info);
/* Get the thread local region. */
const auto *tlr_address = GetTargetThreadLocalRegion(info);
/* Read the thread local region. */
ThreadLocalRegionCommon tlr;
R_TRY(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(tlr)), info->_debug_handle, reinterpret_cast<uintptr_t>(tlr_address), sizeof(tlr)));
/* Detect libnx vs nintendo via magic number. */
if (tlr.libnx.thread_vars.magic == LibnxThreadVars::Magic) {
info->_thread_type_type = ThreadTypeType_Libnx;
*out = reinterpret_cast<uintptr_t>(tlr.libnx.thread_vars.thread_ptr);
} else {
info->_thread_type_type = ThreadTypeType_Nintendo;
*out = is_lp64 ? tlr.lp64.p_thread_type : tlr.ilp32.p_thread_type;
}
R_SUCCEED();
}
Result GetThreadArgumentAndStackPointer(u64 *out_arg, u64 *out_sp, ThreadInfo *info) {
/* Read the thread context. */
svc::ThreadContext thread_context;
R_TRY(svc::GetDebugThreadContext(std::addressof(thread_context), info->_debug_handle, info->_debug_info_create_thread.thread_id, svc::ThreadContextFlag_General | svc::ThreadContextFlag_Control));
/* Argument is in r0. */
*out_arg = thread_context.r[0];
/* Stack pointer varies by architecture. */
if (Is64BitArch(info)) {
*out_sp = thread_context.sp;
} else {
*out_sp = thread_context.r[13];
}
R_SUCCEED();
}
void DetectStratosphereThread(ThreadInfo *info) {
/* Stratosphere threads are initially misdetected as libnx threads. */
if (info->_thread_type_type != ThreadTypeType_Libnx || info->_thread_type == nullptr) {
return;
}
/* Convert to a parent pointer. */
os::ThreadType *stratosphere_ptr = util::GetParentPointer<&os::ThreadType::thread_impl_storage>(std::addressof(info->_thread_type->libnx));
/* Read the magic. */
u16 magic;
if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(magic)), info->_debug_handle, reinterpret_cast<uintptr_t>(std::addressof(stratosphere_ptr->magic)), sizeof(magic)))) {
return;
}
/* Check the magic. */
if (magic == os::ThreadType::Magic) {
info->_thread_type_type = ThreadTypeType_Stratosphere;
info->_thread_type = reinterpret_cast<ThreadTypeCommon *>(stratosphere_ptr);
}
}
}
void GetTargetThreadType(ThreadInfo *info) {
/* Ensure we exit with correct state. */
auto type_guard = SCOPE_GUARD {
info->_thread_type = nullptr;
info->_thread_type_type = ThreadTypeType_Unknown;
};
/* Read the thread type pointer. */
uintptr_t tlr_thread_type;
if (R_FAILED(GetThreadTypePointerFromThreadLocalRegion(std::addressof(tlr_thread_type), info))) {
return;
}
/* Handle the case where we have a thread type. */
if (tlr_thread_type != 0) {
info->_thread_type = reinterpret_cast<ThreadTypeCommon *>(tlr_thread_type);
DetectStratosphereThread(info);
type_guard.Cancel();
return;
}
/* Otherwise, the thread is just created, and we should read its context. */
u64 arg, sp;
if (R_FAILED(GetThreadArgumentAndStackPointer(std::addressof(arg), std::addressof(sp), info))) {
return;
}
/* We may have been bamboozled into thinking a nintendo thread was a libnx thread, so check that. */
/* Nintendo threads have argument=ThreadType, libnx threads have argument=ThreadEntryArgs. */
if (info->_thread_type_type == ThreadTypeType_Nintendo && sp == arg) {
/* It's a libnx thread, so we should parse the entry args. */
info->_thread_type_type = ThreadTypeType_Libnx;
/* Read the entry args. */
LibnxThreadEntryArgs entry_args;
if (R_FAILED(svc::ReadDebugProcessMemory(reinterpret_cast<uintptr_t>(std::addressof(entry_args)), info->_debug_handle, arg, sizeof(entry_args)))) {
return;
}
info->_thread_type = reinterpret_cast<ThreadTypeCommon *>(entry_args.t);
} else {
info->_thread_type_type = ThreadTypeType_Nintendo;
info->_thread_type = reinterpret_cast<ThreadTypeCommon *>(arg);
}
/* If we got the thread type, we don't need to reset our state. */
if (info->_thread_type != nullptr) {
type_guard.Cancel();
DetectStratosphereThread(info);
}
}
}
| 5,918
|
C++
|
.cpp
| 117
| 40.25641
| 214
| 0.615478
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,829
|
htcfs_client.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_client.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_client.hpp"
namespace ams::htcfs {
namespace {
constinit util::TypedStorage<Client> g_client_storage = {};
[[maybe_unused]] constinit bool g_initialized = false;
}
void InitializeClient(htclow::HtclowManager *manager) {
AMS_ASSERT(!g_initialized);
util::ConstructAt(g_client_storage, manager);
}
void FinalizeClient() {
AMS_ASSERT(g_initialized);
util::DestroyAt(g_client_storage);
}
Client &GetClient() {
AMS_ASSERT(g_initialized);
return GetReference(g_client_storage);
}
}
| 1,262
|
C++
|
.cpp
| 35
| 31.6
| 76
| 0.708059
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,830
|
htcfs_file_system_service_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_file_system_service_object.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_file_system_service_object.hpp"
#include "htcfs_file_service_object.hpp"
#include "htcfs_directory_service_object.hpp"
#include "htcfs_client.hpp"
namespace ams::htcfs {
namespace {
struct DirectoryServiceObjectAllocatorTag;
struct FileServiceObjectAllocatorTag;
using DirectoryServiceObjectAllocator = ams::sf::ExpHeapStaticAllocator<4_KB, DirectoryServiceObjectAllocatorTag>;
using FileServiceObjectAllocator = ams::sf::ExpHeapStaticAllocator<4_KB, FileServiceObjectAllocatorTag>;
using DirectoryServiceObjectFactory = ams::sf::ObjectFactory<typename DirectoryServiceObjectAllocator::Policy>;
using FileServiceObjectFactory = ams::sf::ObjectFactory<typename FileServiceObjectAllocator::Policy>;
class StaticAllocatorInitializer {
public:
StaticAllocatorInitializer() {
DirectoryServiceObjectAllocator::Initialize(lmem::CreateOption_ThreadSafe);
FileServiceObjectAllocator::Initialize(lmem::CreateOption_ThreadSafe);
}
} g_static_allocator_initializer;
constexpr bool IsValidPath(const tma::Path &path) {
const auto len = util::Strnlen(path.str, fs::EntryNameLengthMax + 1);
return 0 < len && len < static_cast<int>(fs::EntryNameLengthMax + 1);
}
Result ConvertOpenMode(fs::OpenMode *out, u32 open_mode) {
switch (open_mode) {
case 1:
*out = fs::OpenMode_Read;
break;
case 2:
*out = static_cast<fs::OpenMode>(fs::OpenMode_Write | fs::OpenMode_AllowAppend);
break;
case 3:
*out = static_cast<fs::OpenMode>(fs::OpenMode_ReadWrite | fs::OpenMode_AllowAppend);
break;
default:
R_THROW(htcfs::ResultInvalidArgument());
}
R_SUCCEED();
}
}
Result FileSystemServiceObject::OpenFile(sf::Out<sf::SharedPointer<tma::IFileAccessor>> out, const tma::Path &path, u32 open_mode, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Convert the open mode. */
fs::OpenMode fs_open_mode;
R_TRY(ConvertOpenMode(std::addressof(fs_open_mode), open_mode));
/* Open the file. */
s32 handle = -1;
R_TRY(htcfs::GetClient().OpenFile(std::addressof(handle), path.str, fs_open_mode, case_sensitive));
/* Set the output file. */
*out = FileServiceObjectFactory::CreateSharedEmplaced<tma::IFileAccessor, FileServiceObject>(handle);
R_SUCCEED();
}
Result FileSystemServiceObject::FileExists(sf::Out<bool> out, const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get whether the file exists. */
R_RETURN(htcfs::GetClient().FileExists(out.GetPointer(), path.str, case_sensitive));
}
Result FileSystemServiceObject::DeleteFile(const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Delete the file. */
R_RETURN(htcfs::GetClient().DeleteFile(path.str, case_sensitive));
}
Result FileSystemServiceObject::RenameFile(const tma::Path &old_path, const tma::Path &new_path, bool case_sensitive) {
/* Check that the paths are valid. */
R_UNLESS(IsValidPath(old_path), htcfs::ResultInvalidArgument());
R_UNLESS(IsValidPath(new_path), htcfs::ResultInvalidArgument());
/* Rename the file. */
R_RETURN(htcfs::GetClient().RenameFile(old_path.str, new_path.str, case_sensitive));
}
Result FileSystemServiceObject::GetIOType(sf::Out<s32> out, const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get the entry type. */
static_assert(sizeof(s32) == sizeof(fs::DirectoryEntryType));
R_RETURN(htcfs::GetClient().GetEntryType(reinterpret_cast<fs::DirectoryEntryType *>(out.GetPointer()), path.str, case_sensitive));
}
Result FileSystemServiceObject::OpenDirectory(sf::Out<sf::SharedPointer<tma::IDirectoryAccessor>> out, const tma::Path &path, s32 open_mode, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Open the directory. */
s32 handle = -1;
R_TRY(htcfs::GetClient().OpenDirectory(std::addressof(handle), path.str, static_cast<fs::OpenDirectoryMode>(open_mode), case_sensitive));
/* Set the output directory. */
*out = DirectoryServiceObjectFactory::CreateSharedEmplaced<tma::IDirectoryAccessor, DirectoryServiceObject>(handle);
R_SUCCEED();
}
Result FileSystemServiceObject::DirectoryExists(sf::Out<bool> out, const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get whether the file exists. */
R_RETURN(htcfs::GetClient().DirectoryExists(out.GetPointer(), path.str, case_sensitive));
}
Result FileSystemServiceObject::CreateDirectory(const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Create the directory. */
R_RETURN(htcfs::GetClient().CreateDirectory(path.str, case_sensitive));
}
Result FileSystemServiceObject::DeleteDirectory(const tma::Path &path, bool recursively, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Delete the directory. */
R_RETURN(htcfs::GetClient().DeleteDirectory(path.str, recursively, case_sensitive));
}
Result FileSystemServiceObject::RenameDirectory(const tma::Path &old_path, const tma::Path &new_path, bool case_sensitive) {
/* Check that the paths are valid. */
R_UNLESS(IsValidPath(old_path), htcfs::ResultInvalidArgument());
R_UNLESS(IsValidPath(new_path), htcfs::ResultInvalidArgument());
/* Rename the file. */
R_RETURN(htcfs::GetClient().RenameDirectory(old_path.str, new_path.str, case_sensitive));
}
Result FileSystemServiceObject::CreateFile(const tma::Path &path, s64 size, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Create the file. */
R_RETURN(htcfs::GetClient().CreateFile(path.str, size, case_sensitive));
}
Result FileSystemServiceObject::GetFileTimeStamp(sf::Out<u64> out_create, sf::Out<u64> out_access, sf::Out<u64> out_modify, const tma::Path &path, bool case_sensitive) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get the timestamp. */
R_RETURN(htcfs::GetClient().GetFileTimeStamp(out_create.GetPointer(), out_access.GetPointer(), out_modify.GetPointer(), path.str, case_sensitive));
}
Result FileSystemServiceObject::GetCaseSensitivePath(const tma::Path &path, const sf::OutBuffer &out) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get the case sensitive path. */
R_RETURN(htcfs::GetClient().GetCaseSensitivePath(reinterpret_cast<char *>(out.GetPointer()), out.GetSize(), path.str));
}
Result FileSystemServiceObject::GetDiskFreeSpaceExW(sf::Out<s64> out_free, sf::Out<s64> out_total, sf::Out<s64> out_total_free, const tma::Path &path) {
/* Check that the path is valid. */
R_UNLESS(IsValidPath(path), htcfs::ResultInvalidArgument());
/* Get the timestamp. */
R_RETURN(htcfs::GetClient().GetDiskFreeSpace(out_free.GetPointer(), out_total.GetPointer(), out_total_free.GetPointer(), path.str));
}
}
| 8,947
|
C++
|
.cpp
| 155
| 49.116129
| 173
| 0.672152
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,831
|
htcfs_hipc_server.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_hipc_server.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_client.hpp"
#include "htcfs_file_system_service_object.hpp"
namespace ams::htcfs {
namespace {
static constexpr inline size_t NumServers = 1;
static constexpr inline size_t MaxSessions = 30;
static constexpr inline sm::ServiceName ServiceName = sm::ServiceName::Encode("file_io");
struct ServerOptions {
static constexpr size_t PointerBufferSize = 0x1000;
static constexpr size_t MaxDomains = 0x10;
static constexpr size_t MaxDomainObjects = 0x100;
static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false;
};
using ServerManager = sf::hipc::ServerManager<NumServers, ServerOptions, MaxSessions>;
/* Service object. */
ServerManager g_server_manager;
/* Service object. */
constinit sf::UnmanagedServiceObject<tma::IFileManager, FileSystemServiceObject> g_htcfs_service_object;
constinit sf::UnmanagedServiceObject<tma::IDeprecatedFileManager, FileSystemServiceObject> g_htcfs_deprecated_service_object;
}
void Initialize(htclow::HtclowManager *htclow_manager) {
/* Initialize the htcfs client library. */
htcfs::InitializeClient(htclow_manager);
}
void RegisterHipcServer() {
/* Register the service. */
if (hos::GetVersion() >= hos::Version_6_0_0) {
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_htcfs_service_object.GetShared(), ServiceName, MaxSessions));
} else {
R_ABORT_UNLESS(g_server_manager.RegisterObjectForServer(g_htcfs_deprecated_service_object.GetShared(), ServiceName, MaxSessions));
}
}
void LoopHipcServer() {
/* Loop, servicing services. */
g_server_manager.LoopProcess();
}
}
| 2,558
|
C++
|
.cpp
| 54
| 40.925926
| 142
| 0.693018
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,832
|
htcfs_directory_service_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_directory_service_object.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_directory_service_object.hpp"
#include "htcfs_client.hpp"
namespace ams::htcfs {
DirectoryServiceObject::DirectoryServiceObject(s32 handle) : m_handle(handle) { /* ... */ }
DirectoryServiceObject::~DirectoryServiceObject() {
htcfs::GetClient().CloseDirectory(m_handle);
}
Result DirectoryServiceObject::GetEntryCount(ams::sf::Out<s64> out) {
R_RETURN(htcfs::GetClient().GetEntryCount(out.GetPointer(), m_handle));
}
Result DirectoryServiceObject::Read(ams::sf::Out<s64> out, const ams::sf::OutMapAliasArray<fs::DirectoryEntry> &out_entries) {
if (out_entries.GetSize() * sizeof(fs::DirectoryEntry) >= ClientImpl::MaxPacketBodySize) {
R_RETURN(htcfs::GetClient().ReadDirectoryLarge(out.GetPointer(), out_entries.GetPointer(), out_entries.GetSize(), m_handle));
} else {
R_RETURN(htcfs::GetClient().ReadDirectory(out.GetPointer(), out_entries.GetPointer(), out_entries.GetSize(), m_handle));
}
}
Result DirectoryServiceObject::SetPriorityForDirectory(s32 priority) {
R_RETURN(htcfs::GetClient().SetPriorityForDirectory(priority, m_handle));
}
Result DirectoryServiceObject::GetPriorityForDirectory(ams::sf::Out<s32> out) {
R_RETURN(htcfs::GetClient().GetPriorityForDirectory(out.GetPointer(), m_handle));
}
}
| 2,019
|
C++
|
.cpp
| 40
| 45.8
| 137
| 0.724365
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,833
|
htcfs_file_service_object.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_file_service_object.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_file_service_object.hpp"
#include "htcfs_client.hpp"
namespace ams::htcfs {
FileServiceObject::FileServiceObject(s32 handle) : m_handle(handle) { /* ... */ }
FileServiceObject::~FileServiceObject() {
htcfs::GetClient().CloseFile(m_handle);
}
Result FileServiceObject::ReadFile(ams::sf::Out<s64> out, s64 offset, const ams::sf::OutNonSecureBuffer &buffer, ams::fs::ReadOption option) {
/* Validate offset. */
R_UNLESS(offset >= 0, htcfs::ResultInvalidArgument());
if (buffer.GetSize() >= ClientImpl::MaxPacketBodySize) {
R_RETURN(htcfs::GetClient().ReadFileLarge(out.GetPointer(), buffer.GetPointer(), m_handle, offset, buffer.GetSize(), option));
} else {
R_RETURN(htcfs::GetClient().ReadFile(out.GetPointer(), buffer.GetPointer(), m_handle, offset, buffer.GetSize(), option));
}
}
Result FileServiceObject::WriteFile(s64 offset, const ams::sf::InNonSecureBuffer &buffer, ams::fs::WriteOption option) {
/* Validate offset. */
R_UNLESS(offset >= 0, htcfs::ResultInvalidArgument());
if (buffer.GetSize() >= ClientImpl::MaxPacketBodySize) {
R_RETURN(htcfs::GetClient().WriteFileLarge(buffer.GetPointer(), m_handle, offset, buffer.GetSize(), option));
} else {
R_RETURN(htcfs::GetClient().WriteFile(buffer.GetPointer(), m_handle, offset, buffer.GetSize(), option));
}
}
Result FileServiceObject::GetFileSize(ams::sf::Out<s64> out) {
R_RETURN(htcfs::GetClient().GetFileSize(out.GetPointer(), m_handle));
}
Result FileServiceObject::SetFileSize(s64 size) {
/* Validate size. */
R_UNLESS(size >= 0, htcfs::ResultInvalidArgument());
R_RETURN(htcfs::GetClient().SetFileSize(size, m_handle));
}
Result FileServiceObject::FlushFile() {
R_RETURN(htcfs::GetClient().FlushFile(m_handle));
}
Result FileServiceObject::SetPriorityForFile(s32 priority) {
R_RETURN(htcfs::GetClient().SetPriorityForFile(priority, m_handle));
}
Result FileServiceObject::GetPriorityForFile(ams::sf::Out<s32> out) {
R_RETURN(htcfs::GetClient().GetPriorityForFile(out.GetPointer(), m_handle));
}
}
| 2,913
|
C++
|
.cpp
| 59
| 43.491525
| 146
| 0.68838
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,834
|
htcfs_client_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_client_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_client_impl.hpp"
#include "htcfs_result.hpp"
namespace ams::htcfs {
namespace {
/* TODO: Move to a header? */
constexpr u16 RpcChannelId = 0;
constexpr u16 DataChannelId = 1;
alignas(os::ThreadStackAlignment) constinit u8 g_monitor_thread_stack[os::MemoryPageSize];
constexpr size_t FileDataCacheSize = 32_KB;
constinit u8 g_cache[FileDataCacheSize];
ALWAYS_INLINE Result ConvertNativeResult(s64 value) {
return result::impl::MakeResult(value);
}
}
ClientImpl::ClientImpl(htclow::HtclowManager *manager)
: m_htclow_manager(manager),
m_cache_manager(g_cache, sizeof(g_cache)),
m_header_factory(),
m_mutex(),
m_module(htclow::ModuleId::Htcfs),
m_rpc_channel(manager),
m_data_channel(manager),
m_connected(false),
m_event(os::EventClearMode_ManualClear)
{
/* Start our thread. */
this->Start();
}
void ClientImpl::Start() {
/* Create our thread. */
os::CreateThread(std::addressof(m_monitor_thread), ThreadEntry, this, g_monitor_thread_stack, sizeof(g_monitor_thread_stack), AMS_GET_SYSTEM_THREAD_PRIORITY(htc, HtcfsMonitor));
/* Set thread name pointer. */
os::SetThreadNamePointer(std::addressof(m_monitor_thread), AMS_GET_SYSTEM_THREAD_NAME(htc, HtcfsMonitor));
/* Start our thread. */
os::StartThread(std::addressof(m_monitor_thread));
}
void ClientImpl::Cancel() {
/* Signal our event. */
m_event.Signal();
}
void ClientImpl::Wait() {
/* Wait for and destroy our thread. */
os::WaitThread(std::addressof(m_monitor_thread));
os::DestroyThread(std::addressof(m_monitor_thread));
}
void ClientImpl::ThreadBody() {
/* Loop forever, until we're cancelled. */
while (!m_event.TryWait()) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Open our channel. */
R_ABORT_UNLESS(m_rpc_channel.Open(std::addressof(m_module), RpcChannelId));
/* Ensure that we clean up our channel when we're done. */
ON_SCOPE_EXIT {
m_rpc_channel.Close();
m_cache_manager.Invalidate();
};
/* Set our channel config and buffers. */
m_rpc_channel.SetConfig(htclow::DefaultChannelConfig);
m_rpc_channel.SetReceiveBuffer(m_receive_buffer, sizeof(m_receive_buffer));
m_rpc_channel.SetSendBuffer(m_send_buffer, sizeof(m_send_buffer));
/* Wait for our channel state to be connectable. */
if (this->WaitAny(htclow::ChannelState_Connectable, m_event.GetBase()) != 0) {
return;
}
/* Ensure that when we're done, we reset our connected status. */
ON_SCOPE_EXIT { m_connected = false; };
/* Try to connect. */
const Result conn_result = m_rpc_channel.Connect();
if (R_FAILED(conn_result)) {
/* DEBUG */
R_ABORT_UNLESS(conn_result);
continue;
}
/* Ensure that we manage our connection correctly. */
auto conn_guard = SCOPE_GUARD { m_rpc_channel.Shutdown(); };
/* Try to set up the protocol. */
const Result setup_result = this->SetUpProtocol();
if (R_FAILED(setup_result)) {
R_ABORT_UNLESS(setup_result);
continue;
}
/* We're properly connected now. */
m_connected = true;
conn_guard.Cancel();
/* Tear down the protocol when we're done processing. */
ON_SCOPE_EXIT { this->TearDownProtocol(); };
/* Wait to become disconnected. */
if (this->WaitAny(htclow::ChannelState_Disconnected, m_event.GetBase()) != 0) {
break;
}
}
}
int ClientImpl::WaitAny(htclow::ChannelState state, os::EventType *event) {
/* Wait. */
int idx = 0;
while (m_rpc_channel.GetChannelState() != state) {
/* Get the channel state event. */
os::EventType *channel_state_event = m_rpc_channel.GetChannelStateEvent();
/* Perform wait with lock temporarily not held. */
{
m_mutex.Unlock();
idx = os::WaitAny(channel_state_event, event);
m_mutex.Lock();
}
/* If we're cancel-signalled, we're done. */
if (idx != 0) {
break;
}
/* Clear the channel state event. */
os::ClearEvent(channel_state_event);
}
return idx;
}
Result ClientImpl::SetUpProtocol() {
/* Get the maximum supported protocol on the host side. */
s16 max_host_protocol;
R_TRY(this->GetMaxProtocolVersion(std::addressof(max_host_protocol)));
/* Verify that the host protocol is >= 0. */
R_UNLESS(max_host_protocol >= 0, htcfs::ResultUnsupportedProtocolVersion());
/* Inform the host what protocol we're using. */
const auto use_version = std::min(MaxProtocolVersion, max_host_protocol);
R_TRY(this->SetProtocolVersion(use_version));
/* Set the version in our header factory. */
m_header_factory.SetVersion(use_version);
R_SUCCEED();
}
void ClientImpl::TearDownProtocol() {
/* Set the header factory version to zero. */
m_header_factory.SetVersion(0);
}
Result ClientImpl::CheckResponseHeaderWithoutVersion(const Header &response, PacketType packet_type) {
/* Check the protocol. */
R_UNLESS(response.protocol == HtcfsProtocol, htcfs::ResultUnexpectedResponseProtocolId());
/* Check the packet category. */
R_UNLESS(response.packet_category == PacketCategory::Response, htcfs::ResultUnexpectedResponsePacketCategory());
/* Check the type. */
R_UNLESS(response.packet_type == packet_type, htcfs::ResultUnexpectedResponsePacketType());
R_SUCCEED();
}
Result ClientImpl::CheckResponseHeader(const Header &response, PacketType packet_type) {
/* Perform base checks. */
R_TRY(this->CheckResponseHeaderWithoutVersion(response, packet_type));
/* Check the version. */
R_UNLESS(response.version == m_header_factory.GetVersion(), htcfs::ResultUnexpectedResponseProtocolVersion());
R_SUCCEED();
}
Result ClientImpl::CheckResponseHeader(const Header &response, PacketType packet_type, s64 body_size) {
/* Perform base checks. */
R_TRY(this->CheckResponseHeader(response, packet_type));
/* Check the body size. */
R_UNLESS(response.body_size == body_size, htcfs::ResultUnexpectedResponseBodySize());
R_SUCCEED();
}
Result ClientImpl::GetMaxProtocolVersion(s16 *out) {
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetMaxProtocolVersionHeader(std::addressof(request));
/* Send the request to the host. */
R_TRY(this->SendToRpcChannel(std::addressof(request), sizeof(request)));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeaderWithoutVersion(response, request.packet_type));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Set the maximum protocol version. */
*out = response.params[1];
R_SUCCEED();
}
Result ClientImpl::SetProtocolVersion(s16 version) {
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeSetProtocolVersionHeader(std::addressof(request), version);
/* Send the request to the host. */
R_TRY(this->SendToRpcChannel(std::addressof(request), sizeof(request)));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeaderWithoutVersion(response, request.packet_type));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
R_SUCCEED();
}
Result ClientImpl::SendToRpcChannel(const void *src, s64 size) {
R_RETURN(this->SendToHtclow(src, size, std::addressof(m_rpc_channel)));
}
Result ClientImpl::ReceiveFromRpcChannel(void *dst, s64 size) {
R_RETURN(this->ReceiveFromHtclow(dst, size, std::addressof(m_rpc_channel)));
}
Result ClientImpl::ReceiveFromDataChannel(s64 size) {
R_RETURN(m_data_channel.WaitReceive(size));
}
Result ClientImpl::SendToDataChannel() {
R_RETURN(m_data_channel.Flush());
}
Result ClientImpl::SendToHtclow(const void *src, s64 size, htclow::Channel *channel) {
/* Check size. */
R_UNLESS(size >= 0, htcfs::ResultInvalidArgument());
/* Iteratively send. */
s64 sent;
for (s64 total = 0; total < size; total += sent) {
/* Send the current batch of data. */
R_TRY(channel->Send(std::addressof(sent), static_cast<const u8 *>(src) + total, size - total));
/* Check that we sent the right amount. */
R_UNLESS(sent == size - total, htcfs::ResultHtclowChannelClosed());
}
/* Flush. */
R_TRY(channel->Flush());
R_SUCCEED();
}
Result ClientImpl::ReceiveFromHtclow(void *dst, s64 size, htclow::Channel *channel) {
/* Check size. */
R_UNLESS(size >= 0, htcfs::ResultInvalidArgument());
/* Iteratively receive. */
s64 received;
for (s64 total = 0; total < size; total += received) {
/* Receive the current batch of data. */
R_TRY(channel->Receive(std::addressof(received), static_cast<u8 *>(dst) + total, size - total, htclow::ReceiveOption_ReceiveAllData));
/* Check that we received the right amount. */
R_UNLESS(received == size - total, htcfs::ResultHtclowChannelClosed());
}
/* Flush. */
R_TRY(channel->Flush());
R_SUCCEED();
}
Result ClientImpl::InitializeRpcChannel() {
/* Check that we're not cancelled. */
R_UNLESS(!m_event.TryWait(), htcfs::ResultConnectionFailure());
/* Check that we're connected. */
R_UNLESS(m_connected, htcfs::ResultConnectionFailure());
R_SUCCEED();
}
void ClientImpl::InitializeDataChannelForReceive(void *dst, size_t size) {
/* Open the data channel. */
R_ABORT_UNLESS(m_data_channel.Open(std::addressof(m_module), DataChannelId));
/* Set our config. */
constexpr htclow::ChannelConfig BulkReceiveConfig = {
.flow_control_enabled = false,
.handshake_enabled = false,
.max_packet_size = 0x3E000,
};
m_data_channel.SetConfig(BulkReceiveConfig);
/* Set receive buffer. */
m_data_channel.SetReceiveBuffer(dst, size);
/* Connect. */
R_ABORT_UNLESS(m_data_channel.Connect());
}
void ClientImpl::InitializeDataChannelForSend(const void *src, size_t size) {
/* Open the data channel. */
R_ABORT_UNLESS(m_data_channel.Open(std::addressof(m_module), DataChannelId));
/* Check that the size is valid. */
AMS_ASSERT(util::IsIntValueRepresentable<s64>(size));
/* Set our config. */
constexpr htclow::ChannelConfig BulkSendConfig = {
.flow_control_enabled = false,
.handshake_enabled = false,
.max_packet_size = 0xE020,
};
m_data_channel.SetConfig(BulkSendConfig);
/* Set our send buffer. */
m_data_channel.SetSendBufferWithData(src, size);
/* Connect. */
R_ABORT_UNLESS(m_data_channel.Connect());
}
void ClientImpl::FinalizeDataChannel() {
/* Close our data channel. */
m_data_channel.Close();
}
Result ClientImpl::SendRequest(const Header &request, const void *arg1, size_t arg1_size, const void *arg2, size_t arg2_size) {
/* Try to perform an optimized send. */
if (sizeof(request) + arg1_size + arg2_size < sizeof(m_packet_buffer)) {
/* Setup our packet buffer. */
std::memcpy(m_packet_buffer, std::addressof(request), sizeof(request));
if (arg1_size > 0) {
std::memcpy(m_packet_buffer + sizeof(request), arg1, arg1_size);
}
if (arg2_size > 0) {
std::memcpy(m_packet_buffer + sizeof(request) + arg1_size, arg2, arg2_size);
}
/* Send the request. */
R_TRY(this->SendToRpcChannel(m_packet_buffer, sizeof(request) + arg1_size + arg2_size));
} else {
/* We can't perform a single optimized send, so perform three separate sends. */
R_TRY(this->SendToRpcChannel(std::addressof(request), sizeof(request)));
if (arg1_size > 0) {
R_TRY(this->SendToRpcChannel(arg1, arg1_size));
}
if (arg2_size > 0) {
R_TRY(this->SendToRpcChannel(arg2, arg2_size));
}
}
R_SUCCEED();
}
Result ClientImpl::OpenFile(s32 *out_handle, const char *path, fs::OpenMode mode, bool case_sensitive) {
/* Invalidate the cache manager. */
m_cache_manager.Invalidate();
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeOpenFileHeader(std::addressof(request), path_len, mode, case_sensitive, FileDataCacheSize);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check the response body size. */
R_UNLESS(response.body_size >= 0, htcfs::ResultUnexpectedResponseBodySize());
R_UNLESS(static_cast<size_t>(response.body_size) <= MaxPacketBodySize, htcfs::ResultUnexpectedResponseBodySize());
/* Receive the response body. */
if (response.body_size > 0) {
R_TRY(this->ReceiveFromRpcChannel(m_packet_buffer, response.body_size));
}
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set our output handle. */
*out_handle = response.params[2];
/* If we have data to cache, cache it. */
if (response.params[3]) {
m_cache_manager.Record(response.params[4], m_packet_buffer, response.params[2], response.body_size);
}
R_SUCCEED();
}
Result ClientImpl::FileExists(bool *out, const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeFileExistsHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output. */
*out = response.params[2] != 0;
R_SUCCEED();
}
Result ClientImpl::DeleteFile(const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeDeleteFileHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::RenameFile(const char *old_path, const char *new_path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto old_path_len = std::strlen(new_path);
const auto new_path_len = std::strlen(old_path);
m_header_factory.MakeRenameFileHeader(std::addressof(request), old_path_len, new_path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, old_path, old_path_len, new_path, new_path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::GetEntryType(fs::DirectoryEntryType *out, const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeGetEntryTypeHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output. */
*out = static_cast<fs::DirectoryEntryType>(response.params[2]);
R_SUCCEED();
}
Result ClientImpl::OpenDirectory(s32 *out_handle, const char *path, fs::OpenDirectoryMode mode, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeOpenDirectoryHeader(std::addressof(request), path_len, mode, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output handle. */
*out_handle = static_cast<s32>(response.params[2]);
R_SUCCEED();
}
Result ClientImpl::DirectoryExists(bool *out, const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeDirectoryExistsHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output. */
*out = response.params[2] != 0;
R_SUCCEED();
}
Result ClientImpl::CreateDirectory(const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeCreateDirectoryHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::DeleteDirectory(const char *path, bool recursively, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeDeleteDirectoryHeader(std::addressof(request), path_len, recursively, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::RenameDirectory(const char *old_path, const char *new_path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto old_path_len = std::strlen(new_path);
const auto new_path_len = std::strlen(old_path);
m_header_factory.MakeRenameDirectoryHeader(std::addressof(request), old_path_len, new_path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, old_path, old_path_len, new_path, new_path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::CreateFile(const char *path, s64 size, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeCreateFileHeader(std::addressof(request), path_len, size, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::GetFileTimeStamp(u64 *out_create, u64 *out_access, u64 *out_modify, const char *path, bool case_sensitive) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeGetFileTimeStampHeader(std::addressof(request), path_len, case_sensitive);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set output. */
*out_create = static_cast<u64>(response.params[2]);
*out_access = static_cast<u64>(response.params[3]);
*out_modify = static_cast<u64>(response.params[4]);
R_SUCCEED();
}
Result ClientImpl::GetCaseSensitivePath(char *dst, size_t dst_size, const char *path) {
/* Sanity check the output buffer. */
R_UNLESS(util::IsIntValueRepresentable<s64>(dst_size), htcfs::ResultInvalidArgument());
R_UNLESS(dst_size > 0, htcfs::ResultInvalidArgument());
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeGetCaseSensitivePathHeader(std::addressof(request), path_len);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check our operation's result. */
const auto native_result = ConvertNativeResult(response.params[1]);
if (R_FAILED(native_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(native_result);
}
/* Check the body size. */
R_UNLESS(response.body_size < static_cast<s64>(dst_size), htcfs::ResultUnexpectedResponseBodySize());
/* Receive the response body. */
R_TRY(this->ReceiveFromRpcChannel(dst, response.body_size));
/* Null-terminate the output path. */
dst[response.body_size] = '\x00';
R_SUCCEED();
}
Result ClientImpl::GetDiskFreeSpace(s64 *out_free, s64 *out_total, s64 *out_total_free, const char *path) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
const auto path_len = std::strlen(path);
m_header_factory.MakeGetDiskFreeSpaceHeader(std::addressof(request), path_len);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, path, path_len));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set output. */
*out_free = response.params[2];
*out_total = response.params[3];
*out_total_free = response.params[4];
R_SUCCEED();
}
Result ClientImpl::CloseDirectory(s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeCloseDirectoryHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::GetEntryCount(s64 *out, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetEntryCountHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output count. */
*out = response.params[2];
R_SUCCEED();
}
Result ClientImpl::ReadDirectory(s64 *out, fs::DirectoryEntry *out_entries, size_t max_out_entries, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeReadDirectoryHeader(std::addressof(request), handle, max_out_entries);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Check that the response body size is expected. */
R_UNLESS(static_cast<size_t>(response.body_size) == max_out_entries * sizeof(*out_entries), htcfs::ResultUnexpectedResponseBody());
/* Check that the number of entries read is allowable. */
R_UNLESS(static_cast<size_t>(response.params[2]) <= max_out_entries, htcfs::ResultUnexpectedResponseBody());
/* Receive the entries. */
*out = response.params[2];
R_RETURN(this->ReceiveFromRpcChannel(out_entries, response.body_size));
}
Result ClientImpl::ReadDirectoryLarge(s64 *out, fs::DirectoryEntry *out_entries, size_t max_out_entries, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Setup data channel. */
const bool use_data_channel = max_out_entries > 0;
if (use_data_channel) {
this->InitializeDataChannelForReceive(out_entries, max_out_entries * sizeof(*out_entries));
}
ON_SCOPE_EXIT { if (use_data_channel) { this->FinalizeDataChannel(); } };
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeReadDirectoryLargeHeader(std::addressof(request), handle, max_out_entries, DataChannelId);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check our operation's result. */
const auto native_result = ConvertNativeResult(response.params[1]);
if (R_FAILED(native_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(native_result);
}
/* Check that the number of entries read is allowable. */
R_UNLESS(static_cast<size_t>(response.params[2]) <= max_out_entries, htcfs::ResultUnexpectedResponseBody());
/* Read the entries, if there are any. */
if (response.params[2] > 0) {
R_TRY(this->ReceiveFromDataChannel(response.params[2] * sizeof(*out_entries)));
}
/* Set the number of output entries. */
*out = response.params[2];
R_SUCCEED();
}
Result ClientImpl::GetPriorityForDirectory(s32 *out, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetPriorityForDirectoryHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Set the output. */
*out = static_cast<s32>(response.params[1]);
R_SUCCEED();
}
Result ClientImpl::SetPriorityForDirectory(s32 priority, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeSetPriorityForDirectoryHeader(std::addressof(request), handle, priority);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
R_SUCCEED();
}
Result ClientImpl::CloseFile(s32 handle) {
/* Invalidate the cache. */
m_cache_manager.Invalidate(handle);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeCloseFileHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::ReadFile(s64 *out, void *buffer, s32 handle, s64 offset, s64 buffer_size, fs::ReadOption option) {
AMS_UNUSED(option);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Try to read from our cache. */
if (util::IsIntValueRepresentable<size_t>(offset) && util::IsIntValueRepresentable<size_t>(buffer_size)) {
size_t read_size;
if (m_cache_manager.ReadFile(std::addressof(read_size), buffer, handle, static_cast<size_t>(offset), static_cast<size_t>(buffer_size))) {
AMS_ASSERT(util::IsIntValueRepresentable<s64>(read_size));
*out = static_cast<s64>(read_size);
R_SUCCEED();
}
}
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeReadFileHeader(std::addressof(request), handle, offset, buffer_size);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check our operation's result. */
const auto native_result = ConvertNativeResult(response.params[1]);
if (R_FAILED(native_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(native_result);
}
/* Check the body size. */
R_UNLESS(response.body_size <= buffer_size, htcfs::ResultUnexpectedResponseBodySize());
/* Receive the file data. */
R_TRY(this->ReceiveFromRpcChannel(buffer, response.body_size));
/* Set the output size. */
*out = response.body_size;
R_SUCCEED();
}
Result ClientImpl::ReadFileLarge(s64 *out, void *buffer, s32 handle, s64 offset, s64 buffer_size, fs::ReadOption option) {
AMS_UNUSED(option);
/* Check our buffer size. */
R_UNLESS(util::IsIntValueRepresentable<size_t>(buffer_size), htcfs::ResultInvalidArgument());
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Setup data channel. */
this->InitializeDataChannelForReceive(buffer, buffer_size);
ON_SCOPE_EXIT { this->FinalizeDataChannel(); };
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeReadFileLargeHeader(std::addressof(request), handle, offset, buffer_size, DataChannelId);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check our operation's result. */
const auto native_result = ConvertNativeResult(response.params[1]);
if (R_FAILED(native_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(native_result);
}
/* Check that the size read is allowable. */
R_UNLESS(response.params[2] <= buffer_size, htcfs::ResultUnexpectedResponseBodySize());
/* Read the entries, if there are any. */
R_TRY(this->ReceiveFromDataChannel(response.params[2]));
/* Set the number of output entries. */
*out = response.params[2];
R_SUCCEED();
}
Result ClientImpl::WriteFile(const void *buffer, s32 handle, s64 offset, s64 buffer_size, fs::WriteOption option) {
/* Invalidate the cache. */
m_cache_manager.Invalidate(handle);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeWriteFileHeader(std::addressof(request), buffer_size, handle, option._value, offset);
/* Send the request to the host. */
R_TRY(this->SendRequest(request, buffer, buffer_size));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::WriteFileLarge(const void *buffer, s32 handle, s64 offset, s64 buffer_size, fs::WriteOption option) {
/* Invalidate the cache. */
m_cache_manager.Invalidate(handle);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeWriteFileLargeHeader(std::addressof(request), handle, option._value, offset, buffer_size, DataChannelId);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Verify that the host reports ready to receive our data. */
if (static_cast<HtcfsResult>(response.params[0]) != HtcfsResult::Ready) {
R_RETURN(ConvertHtcfsResult(response.params[0]));
}
/* Verify that our send will be valid. */
AMS_ASSERT(util::IsIntValueRepresentable<size_t>(buffer_size));
/* Perform the send. */
{
/* Initialize data channel for our write. */
this->InitializeDataChannelForSend(buffer, buffer_size);
/* Ensure that we clean up our data channel. */
ON_SCOPE_EXIT { this->FinalizeDataChannel(); };
/* Send to our data channel. */
R_TRY(this->SendToDataChannel());
}
/* Receive the large-write response. */
Header write_resp;
R_TRY(this->ReceiveFromRpcChannel(std::addressof(write_resp), sizeof(write_resp)));
/* Check the write-response header. */
R_TRY(this->CheckResponseHeader(write_resp, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(write_resp.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(write_resp.params[1]));
R_SUCCEED();
}
Result ClientImpl::GetFileSize(s64 *out, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Check if we have the file size cached. */
R_SUCCEED_IF(m_cache_manager.GetFileSize(out, handle));
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetFileSizeHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
/* Set the output. */
*out = response.params[2];
R_SUCCEED();
}
Result ClientImpl::SetFileSize(s64 size, s32 handle) {
/* Invalidate the cache. */
m_cache_manager.Invalidate(handle);
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeSetFileSizeHeader(std::addressof(request), handle, size);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::FlushFile(s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeFlushFileHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Check our operation's result. */
R_TRY(ConvertNativeResult(response.params[1]));
R_SUCCEED();
}
Result ClientImpl::GetPriorityForFile(s32 *out, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetPriorityForFileHeader(std::addressof(request), handle);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
/* Set the output. */
*out = static_cast<s32>(response.params[1]);
R_SUCCEED();
}
Result ClientImpl::SetPriorityForFile(s32 priority, s32 handle) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeSetPriorityForFileHeader(std::addressof(request), handle, priority);
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type, 0));
/* Check that we succeeded. */
R_TRY(ConvertHtcfsResult(response.params[0]));
R_SUCCEED();
}
Result ClientImpl::GetWorkingDirectory(char *dst, size_t dst_size) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetWorkingDirectoryHeader(std::addressof(request));
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check that the body size is valid. */
R_UNLESS(response.body_size < static_cast<s64>(dst_size), htcfs::ResultUnexpectedResponseBodySize());
/* Receive the response body. */
R_TRY(this->ReceiveFromRpcChannel(dst, response.body_size));
/* Null-terminate the response body. */
dst[response.body_size] = '\x00';
R_SUCCEED();
}
Result ClientImpl::GetWorkingDirectorySize(s32 *out) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Initialize our rpc channel. */
R_TRY(this->InitializeRpcChannel());
/* Create space for request and response. */
Header request, response;
/* Create header for the request. */
m_header_factory.MakeGetWorkingDirectorySizeHeader(std::addressof(request));
/* Send the request to the host. */
R_TRY(this->SendRequest(request));
/* Receive response from the host. */
R_TRY(this->ReceiveFromRpcChannel(std::addressof(response), sizeof(response)));
/* Check the response header. */
R_TRY(this->CheckResponseHeader(response, request.packet_type));
/* Check that we succeeded. */
const auto htcfs_result = ConvertHtcfsResult(response.params[0]);
if (R_FAILED(htcfs_result)) {
R_UNLESS(response.body_size == 0, htcfs::ResultUnexpectedResponseBodySize());
R_RETURN(htcfs_result);
}
/* Check that the size is representable. */
R_UNLESS(util::IsIntValueRepresentable<s32>(response.params[1]), htcfs::ResultInvalidSize());
/* Set the output size. */
*out = static_cast<s32>(response.params[1]);
R_SUCCEED();
}
}
| 57,605
|
C++
|
.cpp
| 1,165
| 40.053219
| 185
| 0.625402
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,835
|
htcfs_working_directory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/htcfs/htcfs_working_directory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "htcfs_client.hpp"
namespace ams::htcfs {
Result GetWorkingDirectory(char *dst, size_t dst_size) {
R_RETURN(htcfs::GetClient().GetWorkingDirectory(dst, dst_size));
}
Result GetWorkingDirectorySize(s32 *out) {
R_RETURN(htcfs::GetClient().GetWorkingDirectorySize(out));
}
}
| 980
|
C++
|
.cpp
| 25
| 36.2
| 76
| 0.741325
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,836
|
ncm_integrated_content_meta_database_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_integrated_content_meta_database_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
Result IntegratedContentMetaDatabaseImpl::Set(const ContentMetaKey &key, const sf::InBuffer &value) {
AMS_UNUSED(key, value);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentMetaDatabaseImpl::Get(sf::Out<u64> out_size, const ContentMetaKey &key, const sf::OutBuffer &out_value) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->Get(out_size, key, out_value));
}));
}
Result IntegratedContentMetaDatabaseImpl::Remove(const ContentMetaKey &key) {
AMS_UNUSED(key);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentMetaDatabaseImpl::GetContentIdByType(sf::Out<ContentId> out_content_id, const ContentMetaKey &key, ContentType type) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetContentIdByType(out_content_id, key, type));
}));
}
Result IntegratedContentMetaDatabaseImpl::ListContentInfo(sf::Out<s32> out_entries_written, const sf::OutArray<ContentInfo> &out_info, const ContentMetaKey &key, s32 offset) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), key));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentMetaNotFound());
/* If it does, list the content infos. */
R_RETURN(data.interface->ListContentInfo(out_entries_written, out_info, key, offset));
}));
}
Result IntegratedContentMetaDatabaseImpl::List(sf::Out<s32> out_entries_total, sf::Out<s32> out_entries_written, const sf::OutArray<ContentMetaKey> &out_info, ContentMetaType meta_type, ApplicationId application_id, u64 min, u64 max, ContentInstallType install_type) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* List on all databases. */
s32 entries_total = 0;
s32 entries_written = 0;
R_TRY(m_list.ForAll([&](const auto &data) {
/* List on the current database. */
s32 cur_total;
s32 cur_written;
R_TRY(data.interface->List(std::addressof(cur_total), std::addressof(cur_written), sf::OutArray<ContentMetaKey>{out_info.GetPointer() + entries_written, out_info.GetSize() - entries_written}, meta_type, application_id, min, max, install_type));
/* Add to the totals. */
entries_total += cur_total;
entries_written += cur_written;
R_SUCCEED();
}));
/* Set output. */
*out_entries_total = entries_total;
*out_entries_written = entries_written;
R_SUCCEED();
}
Result IntegratedContentMetaDatabaseImpl::GetLatestContentMetaKey(sf::Out<ContentMetaKey> out_key, u64 id) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetLatestContentMetaKey(out_key, id));
}));
}
Result IntegratedContentMetaDatabaseImpl::ListApplication(sf::Out<s32> out_entries_total, sf::Out<s32> out_entries_written, const sf::OutArray<ApplicationContentMetaKey> &out_keys, ContentMetaType meta_type) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* List on all databases. */
s32 entries_total = 0;
s32 entries_written = 0;
R_TRY(m_list.ForAll([&](const auto &data) {
/* List on the current database. */
s32 cur_total;
s32 cur_written;
R_TRY(data.interface->ListApplication(std::addressof(cur_total), std::addressof(cur_written), sf::OutArray<ApplicationContentMetaKey>{out_keys.GetPointer() + entries_written, out_keys.GetSize() - entries_written}, meta_type));
/* Add to the totals. */
entries_total += cur_total;
entries_written += cur_written;
R_SUCCEED();
}));
/* Set output. */
*out_entries_total = entries_total;
*out_entries_written = entries_written;
R_SUCCEED();
}
Result IntegratedContentMetaDatabaseImpl::Has(sf::Out<bool> out, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* If we don't locate the content meta, set the output to false. */
*out = false;
ON_RESULT_INCLUDED(ncm::ResultContentMetaNotFound) { *out = false; };
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
R_TRY(data.interface->Has(out, key));
/* If it doesn't, continue on. */
R_UNLESS(*out, ncm::ResultContentMetaNotFound());
/* If it does, we're done looking. */
R_SUCCEED();
}));
}
Result IntegratedContentMetaDatabaseImpl::HasAll(sf::Out<bool> out, const sf::InArray<ContentMetaKey> &keys) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
*out = false;
/* Check if keys are present. */
for (size_t i = 0; i < keys.GetSize(); i++) {
/* Check if we have the current key. */
bool has;
R_TRY(this->Has(std::addressof(has), keys[i]));
/* If we don't, then we can early return because we don't have all. */
R_SUCCEED_IF(!has);
}
*out = true;
R_SUCCEED();
}
Result IntegratedContentMetaDatabaseImpl::GetSize(sf::Out<u64> out_size, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetSize(out_size, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetRequiredSystemVersion(sf::Out<u32> out_version, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetRequiredSystemVersion(out_version, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetPatchContentMetaId(sf::Out<u64> out_patch_id, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetPatchContentMetaId(out_patch_id, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::DisableForcibly() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
m_disabled = true;
R_SUCCEED();
}
Result IntegratedContentMetaDatabaseImpl::LookupOrphanContent(const sf::OutArray<bool> &out_orphaned, const sf::InArray<ContentId> &content_ids) {
AMS_UNUSED(out_orphaned, content_ids);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentMetaDatabaseImpl::Commit() {
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentMetaDatabaseImpl::HasContent(sf::Out<bool> out, const ContentMetaKey &key, const ContentId &content_id) {
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
/* NOTE: Nintendo bug: Nintendo calls this->Has(), which is likely a copy paste error from ::HasAll... */
bool has;
R_TRY(data.interface->Has(std::addressof(has), key));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentMetaNotFound());
/* If it does, list the content infos. */
R_RETURN(data.interface->HasContent(out, key, content_id));
}));
}
Result IntegratedContentMetaDatabaseImpl::ListContentMetaInfo(sf::Out<s32> out_entries_written, const sf::OutArray<ContentMetaInfo> &out_meta_info, const ContentMetaKey &key, s32 offset) {
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), key));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentMetaNotFound());
/* If it does, list the content infos. */
R_RETURN(data.interface->ListContentMetaInfo(out_entries_written, out_meta_info, key, offset));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetAttributes(sf::Out<u8> out_attributes, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetAttributes(out_attributes, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetRequiredApplicationVersion(sf::Out<u32> out_version, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetRequiredApplicationVersion(out_version, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetContentIdByTypeAndIdOffset(sf::Out<ContentId> out_content_id, const ContentMetaKey &key, ContentType type, u8 id_offset) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetContentIdByTypeAndIdOffset(out_content_id, key, type, id_offset));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetCount(sf::Out<u32> out_count) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* List on all databases. */
u32 total = 0;
R_TRY(m_list.ForAll([&](const auto &data) {
/* List on the current database. */
u32 cur;
R_TRY(data.interface->GetCount(std::addressof(cur)));
/* Add to the totals. */
total += cur;
R_SUCCEED();
}));
/* Set output. */
*out_count = total;
R_SUCCEED();
}
Result IntegratedContentMetaDatabaseImpl::GetOwnerApplicationId(sf::Out<ApplicationId> out_id, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetOwnerApplicationId(out_id, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetContentAccessibilities(sf::Out<u8> out_accessibilities, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetContentAccessibilities(out_accessibilities, key));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetContentInfoByType(sf::Out<ContentInfo> out_content_info, const ContentMetaKey &key, ContentType type) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetContentInfoByType(out_content_info, key, type));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetContentInfoByTypeAndIdOffset(sf::Out<ContentInfo> out_content_info, const ContentMetaKey &key, ContentType type, u8 id_offset) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetContentInfoByTypeAndIdOffset(out_content_info, key, type, id_offset));
}));
}
Result IntegratedContentMetaDatabaseImpl::GetPlatform(sf::Out<ncm::ContentMetaPlatform> out, const ContentMetaKey &key) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentMetaNotFound());
/* Check each interface in turn. */
R_RETURN(m_list.TryEach([&](const auto &data) {
/* Try the current interface. */
R_RETURN(data.interface->GetPlatform(out, key));
}));
}
}
| 17,983
|
C++
|
.cpp
| 364
| 40.162088
| 272
| 0.617229
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,837
|
ncm_placeholder_accessor.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_placeholder_accessor.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_placeholder_accessor.hpp"
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
constexpr inline const char * const BasePlaceHolderDirectory = "/placehld";
constexpr inline const char * const PlaceHolderExtension = ".nca";
constexpr inline size_t PlaceHolderExtensionLength = 4;
constexpr inline size_t PlaceHolderFileNameLengthWithoutExtension = 2 * sizeof(PlaceHolderId);
constexpr inline size_t PlaceHolderFileNameLength = PlaceHolderFileNameLengthWithoutExtension + PlaceHolderExtensionLength;
void MakeBasePlaceHolderDirectoryPath(PathString *out, const char *root_path) {
out->AssignFormat("%s%s", root_path, BasePlaceHolderDirectory);
}
void MakePlaceHolderFilePath(PathString *out, PlaceHolderId id, MakePlaceHolderPathFunction func, const char *root_path) {
PathString path;
MakeBasePlaceHolderDirectoryPath(std::addressof(path), root_path);
func(out, id, path);
}
}
void PlaceHolderAccessor::MakePath(PathString *out_placeholder_path, PlaceHolderId placeholder_id) const {
MakePlaceHolderFilePath(out_placeholder_path, placeholder_id, m_make_placeholder_path_func, *m_root_path);
}
void PlaceHolderAccessor::MakeBaseDirectoryPath(PathString *out, const char *root_path) {
MakeBasePlaceHolderDirectoryPath(out, root_path);
}
Result PlaceHolderAccessor::EnsurePlaceHolderDirectory(PlaceHolderId placeholder_id) {
PathString path;
this->MakePath(std::addressof(path), placeholder_id);
R_RETURN(fs::EnsureParentDirectory(path));
}
Result PlaceHolderAccessor::GetPlaceHolderIdFromFileName(PlaceHolderId *out, const char *name) {
/* Ensure placeholder name is valid. */
R_UNLESS(strnlen(name, PlaceHolderFileNameLength) == PlaceHolderFileNameLength, ncm::ResultInvalidPlaceHolderFile());
R_UNLESS(strncmp(name + PlaceHolderFileNameLengthWithoutExtension, PlaceHolderExtension, PlaceHolderExtensionLength) == 0, ncm::ResultInvalidPlaceHolderFile());
/* Convert each character pair to a byte until we reach the end. */
PlaceHolderId placeholder_id = {};
for (size_t i = 0; i < sizeof(placeholder_id); i++) {
char tmp[3];
util::Strlcpy(tmp, name + i * 2, sizeof(tmp));
char *err = nullptr;
reinterpret_cast<u8 *>(std::addressof(placeholder_id))[i] = static_cast<u8>(std::strtoul(tmp, std::addressof(err), 16));
R_UNLESS(*err == '\x00', ncm::ResultInvalidPlaceHolderFile());
}
*out = placeholder_id;
R_SUCCEED();
}
Result PlaceHolderAccessor::Open(fs::FileHandle *out_handle, PlaceHolderId placeholder_id) {
/* Try to load from the cache. */
R_SUCCEED_IF(this->LoadFromCache(out_handle, placeholder_id));
/* Make the path of the placeholder. */
PathString placeholder_path;
this->MakePath(std::addressof(placeholder_path), placeholder_id);
/* Open the placeholder file. */
R_RETURN(fs::OpenFile(out_handle, placeholder_path, fs::OpenMode_Write));
}
bool PlaceHolderAccessor::LoadFromCache(fs::FileHandle *out_handle, PlaceHolderId placeholder_id) {
std::scoped_lock lk(m_cache_mutex);
/* Attempt to find an entry in the cache. */
CacheEntry *entry = this->FindInCache(placeholder_id);
if (!entry) {
return false;
}
/* No cached entry found. */
entry->id = InvalidPlaceHolderId;
*out_handle = entry->handle;
return true;
}
void PlaceHolderAccessor::StoreToCache(PlaceHolderId placeholder_id, fs::FileHandle handle) {
std::scoped_lock lk(m_cache_mutex);
/* Store placeholder id and file handle to a free entry. */
CacheEntry *entry = this->GetFreeEntry();
entry->id = placeholder_id;
entry->handle = handle;
entry->counter = m_cur_counter++;
}
void PlaceHolderAccessor::Invalidate(CacheEntry *entry) {
/* Flush and close the cached entry's file. */
if (entry != nullptr) {
fs::FlushFile(entry->handle);
fs::CloseFile(entry->handle);
entry->id = InvalidPlaceHolderId;
}
}
PlaceHolderAccessor::CacheEntry *PlaceHolderAccessor::FindInCache(PlaceHolderId placeholder_id) {
/* Ensure placeholder id is valid. */
if (placeholder_id == InvalidPlaceHolderId) {
return nullptr;
}
/* Attempt to find a cache entry with the same placeholder id. */
for (size_t i = 0; i < MaxCacheEntries; i++) {
if (placeholder_id == m_caches[i].id) {
return std::addressof(m_caches[i]);
}
}
return nullptr;
}
PlaceHolderAccessor::CacheEntry *PlaceHolderAccessor::GetFreeEntry() {
/* Try to find an already free entry. */
for (size_t i = 0; i < MaxCacheEntries; i++) {
if (m_caches[i].id == InvalidPlaceHolderId) {
return std::addressof(m_caches[i]);
}
}
/* Get the oldest entry. */
CacheEntry *entry = std::addressof(m_caches[0]);
for (size_t i = 1; i < MaxCacheEntries; i++) {
if (entry->counter < m_caches[i].counter) {
entry = std::addressof(m_caches[i]);
}
}
this->Invalidate(entry);
return entry;
}
void PlaceHolderAccessor::GetPath(PathString *placeholder_path, PlaceHolderId placeholder_id) {
{
std::scoped_lock lock(m_cache_mutex);
this->Invalidate(this->FindInCache(placeholder_id));
}
this->MakePath(placeholder_path, placeholder_id);
}
Result PlaceHolderAccessor::CreatePlaceHolderFile(PlaceHolderId placeholder_id, s64 size) {
/* Ensure the destination directory exists. */
R_TRY(this->EnsurePlaceHolderDirectory(placeholder_id));
/* Get the placeholder path. */
PathString placeholder_path;
this->GetPath(std::addressof(placeholder_path), placeholder_id);
/* Create the placeholder file. */
R_TRY_CATCH(fs::CreateFile(placeholder_path, size, fs::CreateOption_BigFile)) {
R_CONVERT(fs::ResultPathAlreadyExists, ncm::ResultPlaceHolderAlreadyExists())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result PlaceHolderAccessor::DeletePlaceHolderFile(PlaceHolderId placeholder_id) {
/* Get the placeholder path. */
PathString placeholder_path;
this->GetPath(std::addressof(placeholder_path), placeholder_id);
/* Delete the placeholder file. */
R_TRY_CATCH(fs::DeleteFile(placeholder_path)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultPlaceHolderNotFound())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result PlaceHolderAccessor::WritePlaceHolderFile(PlaceHolderId placeholder_id, s64 offset, const void *buffer, size_t size) {
/* Open the placeholder file. */
fs::FileHandle file;
R_TRY_CATCH(this->Open(std::addressof(file), placeholder_id)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultPlaceHolderNotFound())
} R_END_TRY_CATCH;
/* Store opened files to the cache regardless of write failures. */
ON_SCOPE_EXIT { this->StoreToCache(placeholder_id, file); };
/* Write data to the placeholder file. */
R_RETURN(fs::WriteFile(file, offset, buffer, size, m_delay_flush ? fs::WriteOption::Flush : fs::WriteOption::None));
}
Result PlaceHolderAccessor::SetPlaceHolderFileSize(PlaceHolderId placeholder_id, s64 size) {
/* Open the placeholder file. */
fs::FileHandle file;
R_TRY_CATCH(this->Open(std::addressof(file), placeholder_id)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultPlaceHolderNotFound())
} R_END_TRY_CATCH;
/* Close the file on exit. */
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Set the size of the placeholder file. */
R_RETURN(fs::SetFileSize(file, size));
}
Result PlaceHolderAccessor::TryGetPlaceHolderFileSize(bool *found_in_cache, s64 *out_size, PlaceHolderId placeholder_id) {
/* Attempt to find the placeholder in the cache. */
fs::FileHandle handle;
auto found = this->LoadFromCache(std::addressof(handle), placeholder_id);
if (found) {
/* Renew the entry in the cache. */
this->StoreToCache(placeholder_id, handle);
R_TRY(fs::GetFileSize(out_size, handle));
*found_in_cache = true;
} else {
*found_in_cache = false;
}
R_SUCCEED();
}
void PlaceHolderAccessor::InvalidateAll() {
/* Invalidate all cache entries. */
for (auto &entry : m_caches) {
if (entry.id != InvalidPlaceHolderId) {
this->Invalidate(std::addressof(entry));
}
}
}
}
| 9,772
|
C++
|
.cpp
| 202
| 39.767327
| 168
| 0.650425
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,838
|
ncm_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_content_manager_factory.hpp"
#include "ncm_remote_content_manager_impl.hpp"
namespace ams::ncm {
namespace {
constinit sf::SharedPointer<IContentManager> g_content_manager;
#if defined(ATMOSPHERE_OS_HORIZON)
constinit util::TypedStorage<sf::UnmanagedServiceObject<IContentManager, RemoteContentManagerImpl>> g_remote_manager_storage = {};
#endif
}
void Initialize() {
AMS_ASSERT(g_content_manager == nullptr);
#if defined(ATMOSPHERE_OS_HORIZON)
util::ConstructAt(g_remote_manager_storage);
g_content_manager = util::GetReference(g_remote_manager_storage).GetShared();
#else
g_content_manager = CreateDefaultContentManager(ContentManagerConfig{});
#endif
}
void Finalize() {
AMS_ASSERT(g_content_manager != nullptr);
g_content_manager.Reset();
#if defined(ATMOSPHERE_OS_HORIZON)
util::DestroyAt(g_remote_manager_storage);
#endif
}
void InitializeWithObject(sf::SharedPointer<IContentManager> manager_object) {
AMS_ASSERT(g_content_manager == nullptr);
g_content_manager = manager_object;
AMS_ASSERT(g_content_manager != nullptr);
}
/* Service API. */
Result CreateContentStorage(StorageId storage_id) {
R_RETURN(g_content_manager->CreateContentStorage(storage_id));
}
Result CreateContentMetaDatabase(StorageId storage_id) {
R_RETURN(g_content_manager->CreateContentMetaDatabase(storage_id));
}
Result VerifyContentStorage(StorageId storage_id) {
R_RETURN(g_content_manager->VerifyContentStorage(storage_id));
}
Result VerifyContentMetaDatabase(StorageId storage_id) {
R_RETURN(g_content_manager->VerifyContentMetaDatabase(storage_id));
}
Result OpenContentStorage(ContentStorage *out, StorageId storage_id) {
sf::SharedPointer<IContentStorage> content_storage;
R_TRY(g_content_manager->OpenContentStorage(std::addressof(content_storage), storage_id));
*out = ContentStorage(std::move(content_storage));
R_SUCCEED();
}
Result OpenContentMetaDatabase(ContentMetaDatabase *out, StorageId storage_id) {
sf::SharedPointer<IContentMetaDatabase> content_db;
R_TRY(g_content_manager->OpenContentMetaDatabase(std::addressof(content_db), storage_id));
*out = ContentMetaDatabase(std::move(content_db));
R_SUCCEED();
}
Result CleanupContentMetaDatabase(StorageId storage_id) {
R_RETURN(g_content_manager->CleanupContentMetaDatabase(storage_id));
}
Result ActivateContentStorage(StorageId storage_id) {
R_RETURN(g_content_manager->ActivateContentStorage(storage_id));
}
Result InactivateContentStorage(StorageId storage_id) {
R_RETURN(g_content_manager->InactivateContentStorage(storage_id));
}
Result ActivateContentMetaDatabase(StorageId storage_id) {
/* On < 2.0.0, this command doesn't exist, and databases are activated as needed on open. */
R_SUCCEED_IF(hos::GetVersion() < hos::Version_2_0_0);
R_RETURN(g_content_manager->ActivateContentMetaDatabase(storage_id));
}
Result InactivateContentMetaDatabase(StorageId storage_id) {
/* On < 2.0.0, this command doesn't exist. */
R_SUCCEED_IF(hos::GetVersion() < hos::Version_2_0_0);
R_RETURN(g_content_manager->InactivateContentMetaDatabase(storage_id));
}
Result InvalidateRightsIdCache() {
R_RETURN(g_content_manager->InvalidateRightsIdCache());
}
Result ActivateFsContentStorage(fs::ContentStorageId fs_content_storage_id) {
R_RETURN(g_content_manager->ActivateFsContentStorage(fs_content_storage_id));
}
/* Deprecated API. */
Result CloseContentStorageForcibly(StorageId storage_id) {
AMS_ABORT_UNLESS(hos::GetVersion() == hos::Version_1_0_0);
R_RETURN(g_content_manager->CloseContentStorageForcibly(storage_id));
}
Result CloseContentMetaDatabaseForcibly(StorageId storage_id) {
AMS_ABORT_UNLESS(hos::GetVersion() == hos::Version_1_0_0);
R_RETURN(g_content_manager->CloseContentMetaDatabaseForcibly(storage_id));
}
}
| 4,891
|
C++
|
.cpp
| 106
| 39.792453
| 138
| 0.712605
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,839
|
ncm_memory_report.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_memory_report.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
void HeapState::Initialize(lmem::HeapHandle heap_handle) {
std::scoped_lock lk(m_mutex);
m_heap_handle = heap_handle;
}
void HeapState::Allocate(size_t size) {
std::scoped_lock lk(m_mutex);
m_total_alloc_size += size;
m_peak_total_alloc_size = std::max(m_total_alloc_size, m_peak_total_alloc_size);
m_peak_alloc_size = std::max(size, m_peak_alloc_size);
}
void HeapState::Free(size_t size) {
std::scoped_lock lk(m_mutex);
m_total_alloc_size -= size;
}
void HeapState::GetMemoryResourceState(MemoryResourceState *out) {
*out = {};
std::scoped_lock lk(m_mutex);
out->peak_total_alloc_size = m_peak_total_alloc_size;
out->peak_alloc_size = m_peak_alloc_size;
out->total_free_size = lmem::GetExpHeapTotalFreeSize(m_heap_handle);
out->allocatable_size = lmem::GetExpHeapAllocatableSize(m_heap_handle, alignof(s32));
}
HeapState &GetHeapState() {
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(HeapState, s_heap_state);
return s_heap_state;
}
}
| 1,788
|
C++
|
.cpp
| 44
| 35.318182
| 93
| 0.684332
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,840
|
ncm_host_content_storage_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_host_content_storage_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_host_content_storage_impl.hpp"
namespace ams::ncm {
Result HostContentStorageImpl::GeneratePlaceHolderId(sf::Out<PlaceHolderId> out) {
AMS_UNUSED(out);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::CreatePlaceHolder(PlaceHolderId placeholder_id, ContentId content_id, s64 size) {
AMS_UNUSED(placeholder_id, content_id, size);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::DeletePlaceHolder(PlaceHolderId placeholder_id) {
AMS_UNUSED(placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::HasPlaceHolder(sf::Out<bool> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::WritePlaceHolder(PlaceHolderId placeholder_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(placeholder_id, offset, data);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::Register(PlaceHolderId placeholder_id, ContentId content_id) {
AMS_UNUSED(placeholder_id, content_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::Delete(ContentId content_id) {
AMS_UNUSED(content_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::Has(sf::Out<bool> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Attempt to locate the content. */
Path path;
R_TRY_CATCH(m_registered_content->GetPath(std::addressof(path), content_id)) {
/* The content is absent, this is fine. */
R_CATCH(ncm::ResultContentNotFound) {
out.SetValue(false);
R_SUCCEED();
}
} R_END_TRY_CATCH;
out.SetValue(true);
R_SUCCEED();
}
Result HostContentStorageImpl::GetPath(sf::Out<Path> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
R_RETURN(m_registered_content->GetPath(out.GetPointer(), content_id));
}
Result HostContentStorageImpl::GetPlaceHolderPath(sf::Out<Path> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::CleanupAllPlaceHolder() {
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::ListPlaceHolder(sf::Out<s32> out_count, const sf::OutArray<PlaceHolderId> &out_buf) {
AMS_UNUSED(out_count, out_buf);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetContentCount(sf::Out<s32> out_count) {
AMS_UNUSED(out_count);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::ListContentId(sf::Out<s32> out_count, const sf::OutArray<ContentId> &out_buf, s32 offset) {
AMS_UNUSED(out_count, out_buf, offset);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetSizeFromContentId(sf::Out<s64> out_size, ContentId content_id) {
AMS_UNUSED(out_size, content_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result HostContentStorageImpl::DisableForcibly() {
m_disabled = true;
R_SUCCEED();
}
Result HostContentStorageImpl::RevertToPlaceHolder(PlaceHolderId placeholder_id, ContentId old_content_id, ContentId new_content_id) {
AMS_UNUSED(placeholder_id, old_content_id, new_content_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::SetPlaceHolderSize(PlaceHolderId placeholder_id, s64 size) {
AMS_UNUSED(placeholder_id, size);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::ReadContentIdFile(const sf::OutBuffer &buf, ContentId content_id, s64 offset) {
AMS_UNUSED(buf, content_id, offset);
R_THROW(ncm::ResultInvalidOperation());
}
Result HostContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
AMS_UNUSED(out_rights_id, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
AMS_UNUSED(out_rights_id, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetRightsIdFromPlaceHolderId(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, attr);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetRightsIdFromContentIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, ContentId content_id) {
/* Obtain the regular rights id for the content id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromContentIdDeprecated2(std::addressof(rights_id), content_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result HostContentStorageImpl::GetRightsIdFromContentIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id) {
R_RETURN(this->GetRightsIdFromContentId(out_rights_id, content_id, fs::ContentAttributes_None));
}
Result HostContentStorageImpl::GetRightsIdFromContentId(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the content path. */
Path path;
R_TRY(m_registered_content->GetPath(std::addressof(path), content_id));
/* Acquire the rights id for the content. */
RightsId rights_id;
R_TRY_CATCH(GetRightsId(std::addressof(rights_id), path, attr)) {
/* The content is absent, output a blank rights id. */
R_CATCH(fs::ResultTargetNotFound) {
out_rights_id.SetValue({});
R_SUCCEED();
}
} R_END_TRY_CATCH;
/* Output the rights id. */
out_rights_id.SetValue(rights_id);
R_SUCCEED();
}
Result HostContentStorageImpl::WriteContentForDebug(ContentId content_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(content_id, offset, data);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetFreeSpaceSize(sf::Out<s64> out_size) {
out_size.SetValue(0);
R_SUCCEED();
}
Result HostContentStorageImpl::GetTotalSpaceSize(sf::Out<s64> out_size) {
out_size.SetValue(0);
R_SUCCEED();
}
Result HostContentStorageImpl::FlushPlaceHolder() {
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetSizeFromPlaceHolderId(sf::Out<s64> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::RepairInvalidFileAttribute() {
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetRightsIdFromPlaceHolderIdWithCacheDeprecated(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, ContentId cache_content_id) {
AMS_UNUSED(out_rights_id, placeholder_id, cache_content_id);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::GetRightsIdFromPlaceHolderIdWithCache(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, ContentId cache_content_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, cache_content_id, attr);
R_THROW(ncm::ResultNotSupported());
}
Result HostContentStorageImpl::RegisterPath(const ContentId &content_id, const Path &path) {
AMS_ABORT_UNLESS(spl::IsDevelopment());
R_RETURN(m_registered_content->RegisterPath(content_id, path));
}
Result HostContentStorageImpl::ClearRegisteredPath() {
AMS_ABORT_UNLESS(spl::IsDevelopment());
m_registered_content->ClearPaths();
R_SUCCEED();
}
Result HostContentStorageImpl::GetProgramId(sf::Out<ncm::ProgramId> out, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the content path. */
Path path;
R_TRY(m_registered_content->GetPath(std::addressof(path), content_id));
/* Check for correct extension. */
const auto path_len = std::strlen(path.str);
const char *extension = path.str + path_len - 1;
if (*extension == '/') {
--extension;
}
R_UNLESS(path_len >= 4 && std::memcmp(extension - 4, ".ncd", 4) == 0, ncm::ResultInvalidContentMetaDirectory());
/* Obtain the program id for the content. */
ncm::ProgramId program_id;
R_TRY(fs::GetProgramId(std::addressof(program_id), path.str, attr));
out.SetValue(program_id);
R_SUCCEED();
}
}
| 9,769
|
C++
|
.cpp
| 202
| 40.935644
| 198
| 0.686312
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,841
|
ncm_install_task_base.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_install_task_base.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_extended_data_mapper.hpp"
namespace ams::ncm {
namespace {
bool Contains(const StorageContentMetaKey *keys, s32 num_keys, const ContentMetaKey &key, StorageId storage_id) {
for (s32 i = 0; i < num_keys; i++) {
const StorageContentMetaKey &storage_key = keys[i];
/* Check if the key matches the input key and storage id. */
if (storage_key.key == key && storage_key.storage_id == storage_id) {
return true;
}
}
return false;
}
bool Contains(const ContentMetaKey *keys, s32 num_keys, const ContentMetaKey &key) {
for (s32 i = 0; i < num_keys; i++) {
/* Check if the key matches the input key. */
if (keys[i] == key) {
return true;
}
}
return false;
}
bool IsExpectedKey(const ContentMetaKey &expected_key, const ContentMetaKey &actual_key) {
return expected_key.id == actual_key.id &&
expected_key.version == actual_key.version &&
expected_key.type == actual_key.type;
}
}
void InstallTaskBase::Cancel() {
std::scoped_lock lk(m_cancel_mutex);
m_cancel_requested = true;
}
void InstallTaskBase::ResetCancel() {
std::scoped_lock lk(m_cancel_mutex);
m_cancel_requested = false;
}
bool InstallTaskBase::IsCancelRequested() {
std::scoped_lock lk(m_cancel_mutex);
return m_cancel_requested;
}
Result InstallTaskBase::Initialize(StorageId install_storage, InstallTaskDataBase *data, u32 config) {
R_UNLESS(IsInstallableStorage(install_storage), ncm::ResultUnknownStorage());
m_install_storage = install_storage;
m_data = data;
m_config = config;
R_RETURN(data->GetProgress(std::addressof(m_progress)));
}
Result InstallTaskBase::Prepare() {
R_TRY(this->SetLastResultOnFailure(this->PrepareImpl()));
R_SUCCEED();
}
Result InstallTaskBase::GetPreparedPlaceHolderPath(Path *out_path, u64 id, ContentMetaType meta_type, ContentType type) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(this->CountInstallContentMetaData(std::addressof(count)));
/* Iterate over content meta. */
util::optional<PlaceHolderId> placeholder_id;
util::optional<StorageId> storage_id;
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(this->GetInstallContentMetaData(std::addressof(content_meta), i));
const InstallContentMetaReader reader = content_meta.GetReader();
/* Ensure content meta matches the key and meta type. */
const auto key = reader.GetKey();
if (key.id != id || key.type != meta_type) {
continue;
}
/* Attempt to find a content info for the type. */
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const auto content_info = reader.GetContentInfo(j);
if (content_info->GetType() == type) {
placeholder_id = content_info->GetPlaceHolderId();
storage_id = content_info->GetStorageId();
break;
}
}
}
R_UNLESS(placeholder_id, ncm::ResultPlaceHolderNotFound());
R_UNLESS(storage_id, ncm::ResultPlaceHolderNotFound());
/* Open the relevant content storage. */
ContentStorage storage;
R_TRY(OpenContentStorage(std::addressof(storage), *storage_id));
/* Get the path. */
storage.GetPlaceHolderPath(out_path, *placeholder_id);
R_SUCCEED();
}
Result InstallTaskBase::CalculateRequiredSize(s64 *out_size) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
s64 required_size = 0;
/* Iterate over each entry. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
const auto reader = content_meta.GetReader();
/* Sum the sizes from the content infos. */
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const auto *content_info = reader.GetContentInfo(j);
if (content_info->install_state == InstallState::NotPrepared) {
required_size += ncm::CalculateRequiredSize(content_info->GetSize());
}
}
}
*out_size = required_size;
R_SUCCEED();
}
Result InstallTaskBase::PrepareImpl() {
/* Reset the throughput. */
this->ResetThroughputMeasurement();
/* Transition from NotPrepared to DataPrepared. */
if (this->GetProgress().state == InstallProgressState::NotPrepared) {
R_TRY(this->PrepareInstallContentMetaData());
R_TRY(this->PrepareDependency());
R_TRY(this->CheckInstallable());
this->SetProgressState(InstallProgressState::DataPrepared);
}
/* Transition from DataPrepared to Prepared. */
if (this->GetProgress().state == InstallProgressState::DataPrepared) {
R_TRY(this->PreparePlaceHolder());
this->SetProgressState(InstallProgressState::Prepared);
}
/* Signal prepare is completed. */
R_RETURN(this->OnPrepareComplete());
}
Result InstallTaskBase::Cleanup() {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Get the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Cleanup the content meta. */
/* N doesn't check the result of this. */
this->CleanupOne(content_meta);
}
/* Cleanup the data and progress. */
R_TRY(m_data->Cleanup());
this->CleanupProgress();
R_SUCCEED();
}
Result InstallTaskBase::CleanupOne(const InstallContentMeta &content_meta) {
/* Obtain a reader and get the storage id. */
const auto reader = content_meta.GetReader();
const auto storage_id = reader.GetStorageId();
R_SUCCEED_IF(storage_id == StorageId::None);
/* Open the relevant content storage. */
ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), storage_id));
/* Iterate over content infos. */
for (size_t i = 0; i < reader.GetContentCount(); i++) {
auto *content_info = reader.GetContentInfo(i);
/* Delete placeholders for Prepared or Installed content infos. */
if (content_info->install_state == InstallState::Prepared || content_info->install_state == InstallState::Installed) {
content_storage.DeletePlaceHolder(content_info->placeholder_id);
}
}
R_SUCCEED();
}
Result InstallTaskBase::ListContentMetaKey(s32 *out_keys_written, StorageContentMetaKey *out_keys, s32 out_keys_count, s32 offset, ListContentMetaKeyFilter filter) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Offset exceeds keys that can be written. */
if (count <= offset) {
*out_keys_written = 0;
R_SUCCEED();
}
if (filter == ListContentMetaKeyFilter::All) {
const s32 num_keys = std::min(count, offset + out_keys_count);
/* Iterate over content meta. */
for (s32 i = offset; i < num_keys; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Write output StorageContentMetaKey. */
const auto reader = content_meta.GetReader();
out_keys[i - offset] = { reader.GetKey(), reader.GetStorageId() };
}
/* Output the number of keys written. */
*out_keys_written = num_keys - offset;
} else {
s32 keys_written = 0;
s32 cur_offset = 0;
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader and check if the content has been committed. */
const auto reader = content_meta.GetReader();
const bool committed = reader.GetHeader()->committed;
/* Apply filter. */
if ((filter == ListContentMetaKeyFilter::Committed && committed) || (filter == ListContentMetaKeyFilter::NotCommitted && !committed)) {
/* Write output StorageContentMetaKey if at a suitable offset. */
if (cur_offset >= offset) {
out_keys[keys_written++] = { reader.GetKey(), reader.GetStorageId() };
}
/* Increment the current offset. */
cur_offset++;
/* We can't write any more output keys. */
if (keys_written >= out_keys_count) {
break;
}
}
}
/* Output the number of keys written. */
*out_keys_written = keys_written;
}
R_SUCCEED();
}
Result InstallTaskBase::ListApplicationContentMetaKey(s32 *out_keys_written, ApplicationContentMetaKey *out_keys, s32 out_keys_count, s32 offset) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Offset exceeds keys that can be written. */
if (count <= offset) {
*out_keys_written = 0;
R_SUCCEED();
}
/* Iterate over content meta. */
const s32 max = std::min(count, offset + out_keys_count);
s32 keys_written = 0;
for (s32 i = offset; i < max; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const auto reader = content_meta.GetReader();
/* Ensure this key has an application id. */
const auto app_id = reader.GetApplicationId();
if (!app_id) {
continue;
}
/* Write output ApplicationContentMetaKey. */
out_keys[keys_written++] = { reader.GetKey(), *app_id };
}
*out_keys_written = keys_written;
R_SUCCEED();
}
Result InstallTaskBase::Execute() {
R_TRY(this->SetLastResultOnFailure(this->ExecuteImpl()));
R_SUCCEED();
}
Result InstallTaskBase::ExecuteImpl() {
this->StartThroughputMeasurement();
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Write all prepared content infos. */
{
/* If we fail while writing, update (but don't check the result). */
ON_RESULT_FAILURE { m_data->Update(content_meta, i); };
/* Create a writer. */
const auto writer = content_meta.GetWriter();
/* Iterate over content infos. */
for (size_t j = 0; j < writer.GetContentCount(); j++) {
auto *content_info = writer.GetWritableContentInfo(j);
/* Write prepared content infos. */
if (content_info->install_state == InstallState::Prepared) {
R_TRY(this->WritePlaceHolder(writer.GetKey(), content_info));
content_info->install_state = InstallState::Installed;
}
}
}
/* Update our data. */
R_TRY(m_data->Update(content_meta, i));
}
/* Execution has finished, signal this and update the state. */
R_TRY(this->OnExecuteComplete());
this->SetProgressState(InstallProgressState::Downloaded);
R_SUCCEED();
}
Result InstallTaskBase::PrepareAndExecute() {
R_TRY(this->SetLastResultOnFailure(this->PrepareImpl()));
R_TRY(this->SetLastResultOnFailure(this->ExecuteImpl()));
R_SUCCEED();
}
Result InstallTaskBase::VerifyAllNotCommitted(const StorageContentMetaKey *keys, s32 num_keys) {
/* No keys to check. */
R_SUCCEED_IF(keys == nullptr);
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
s32 num_not_committed = 0;
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const auto reader = content_meta.GetReader();
if (Contains(keys, num_keys, reader.GetKey(), reader.GetStorageId())) {
/* Ensure content meta isn't committed. */
R_UNLESS(!reader.GetHeader()->committed, ncm::ResultListPartiallyNotCommitted());
num_not_committed++;
}
}
/* Ensure number of uncommitted keys equals the number of input keys. */
R_UNLESS(num_not_committed == num_keys, ncm::ResultListPartiallyNotCommitted());
R_SUCCEED();
}
Result InstallTaskBase::CommitImpl(const StorageContentMetaKey *keys, s32 num_keys) {
/* Ensure progress state is Downloaded. */
R_UNLESS(this->GetProgress().state == InstallProgressState::Downloaded, ncm::ResultInvalidInstallTaskState());
/* Ensure keys aren't committed. */
R_TRY(this->VerifyAllNotCommitted(keys, num_keys));
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* List of storages to commit. */
StorageList commit_list;
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const auto reader = content_meta.GetReader();
const auto cur_key = reader.GetKey();
const auto storage_id = reader.GetStorageId();
const size_t convert_size = reader.CalculateConvertSize();
/* Skip content meta not contained in input keys. */
if (keys != nullptr && !Contains(keys, num_keys, cur_key, storage_id)) {
continue;
}
/* Skip already committed. This check is primarily for if keys is nullptr. */
if (reader.GetHeader()->committed) {
continue;
}
/* Commit the current meta. */
{
/* Ensure that if something goes wrong during commit, we still try to update. */
ON_RESULT_FAILURE { m_data->Update(content_meta, i); };
/* Open a writer. */
const auto writer = content_meta.GetWriter();
/* Convert to content meta and store to a buffer. */
std::unique_ptr<char[]> content_meta_buffer(new (std::nothrow) char[convert_size]);
R_UNLESS(content_meta_buffer != nullptr, ncm::ResultAllocationFailed());
reader.ConvertToContentMeta(content_meta_buffer.get(), convert_size);
/* Open the content storage for this meta. */
ContentStorage content_storage;
R_TRY(OpenContentStorage(std::addressof(content_storage), storage_id));
/* Open the content meta database for this meta. */
ContentMetaDatabase meta_db;
R_TRY(OpenContentMetaDatabase(std::addressof(meta_db), storage_id));
/* Iterate over content infos. */
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const auto *content_info = reader.GetContentInfo(j);
/* Register non-existing content infos. */
if (content_info->install_state != InstallState::AlreadyExists) {
R_TRY(content_storage.Register(content_info->placeholder_id, content_info->info.content_id));
}
}
/* Store the content meta. */
R_TRY(meta_db.Set(reader.GetKey(), content_meta_buffer.get(), convert_size));
/* Mark as committed. */
writer.GetWritableHeader()->committed = true;
/* Mark storage id to be committed later. */
commit_list.Push(reader.GetStorageId());
}
/* Try to update our data. */
R_TRY(m_data->Update(content_meta, i));
}
/* Commit all applicable content meta databases. */
for (s32 i = 0; i < commit_list.Count(); i++) {
ContentMetaDatabase meta_db;
R_TRY(OpenContentMetaDatabase(std::addressof(meta_db), commit_list[i]));
R_TRY(meta_db.Commit());
}
/* Change progress state to committed if keys are nullptr. */
if (keys == nullptr) {
this->SetProgressState(InstallProgressState::Committed);
}
R_SUCCEED();
}
Result InstallTaskBase::Commit(const StorageContentMetaKey *keys, s32 num_keys) {
ON_RESULT_FAILURE { this->SetProgressState(InstallProgressState::Fatal); };
R_RETURN(this->SetLastResultOnFailure(this->CommitImpl(keys, num_keys)));
}
Result InstallTaskBase::IncludesExFatDriver(bool *out) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Check if the attributes are set for including the exfat driver. */
if (content_meta.GetReader().GetHeader()->attributes & ContentMetaAttribute_IncludesExFatDriver) {
*out = true;
R_SUCCEED();
}
}
*out = false;
R_SUCCEED();
}
Result InstallTaskBase::WritePlaceHolderBuffer(InstallContentInfo *content_info, const void *data, size_t data_size) {
R_UNLESS(!this->IsCancelRequested(), ncm::ResultWritePlaceHolderCancelled());
/* Open the content storage for the content info. */
ContentStorage content_storage;
R_TRY(OpenContentStorage(std::addressof(content_storage), content_info->storage_id));
/* Write data to the placeholder. */
R_TRY(content_storage.WritePlaceHolder(content_info->placeholder_id, content_info->written, data, data_size));
content_info->written += data_size;
/* Update progress/throughput if content info isn't temporary. */
if (!content_info->is_temporary) {
this->IncrementProgress(data_size);
this->UpdateThroughputMeasurement(data_size);
}
/* Update the hash for the new data. */
m_sha256_generator.Update(data, data_size);
R_SUCCEED();
}
Result InstallTaskBase::WritePlaceHolder(const ContentMetaKey &key, InstallContentInfo *content_info) {
if (content_info->is_sha256_calculated) {
/* Update the hash with the buffered data. */
m_sha256_generator.InitializeWithContext(std::addressof(content_info->context));
m_sha256_generator.Update(content_info->buffered_data, content_info->buffered_data_size);
} else {
/* Initialize the generator. */
m_sha256_generator.Initialize();
}
{
ON_SCOPE_EXIT {
/* Update this content info's sha256 data. */
m_sha256_generator.GetContext(std::addressof(content_info->context));
content_info->buffered_data_size = m_sha256_generator.GetBufferedDataSize();
m_sha256_generator.GetBufferedData(content_info->buffered_data, m_sha256_generator.GetBufferedDataSize());
content_info->is_sha256_calculated = true;
};
/* Perform the placeholder write. */
R_TRY(this->OnWritePlaceHolder(key, content_info));
}
/* Compare generated hash to expected hash if verification required. */
if (content_info->verify_digest) {
u8 hash[crypto::Sha256Generator::HashSize];
m_sha256_generator.GetHash(hash, crypto::Sha256Generator::HashSize);
R_UNLESS(std::memcmp(hash, content_info->digest.data, crypto::Sha256Generator::HashSize) == 0, ncm::ResultInvalidContentHash());
}
if (hos::GetVersion() >= hos::Version_2_0_0 && !(m_config & InstallConfig_IgnoreTicket)) {
ncm::RightsId rights_id;
{
/* Open the content storage and obtain the rights id. */
ncm::ContentStorage storage;
R_TRY(OpenContentStorage(std::addressof(storage), content_info->storage_id));
R_TRY(storage.GetRightsId(std::addressof(rights_id), content_info->placeholder_id, content_info->GetContentAttributes()));
}
/* Install a ticket if necessary. */
if (this->IsNecessaryInstallTicket(rights_id.id)) {
R_TRY_CATCH(this->InstallTicket(rights_id.id, content_info->meta_type)) {
R_CATCH(ncm::ResultIgnorableInstallTicketFailure) { /* We can ignore the installation failure. */ }
} R_END_TRY_CATCH;
}
}
R_SUCCEED();
}
bool InstallTaskBase::IsNecessaryInstallTicket(const fs::RightsId &rights_id) {
/* If the title has no rights, there's no ticket to install. */
fs::RightsId empty_rights_id = {};
if (std::memcmp(std::addressof(rights_id), std::addressof(empty_rights_id), sizeof(fs::RightsId)) == 0) {
return false;
}
/* TODO: Support detecting if a title requires rights. */
/* TODO: How should es be handled without undesired effects? */
return false;
}
Result InstallTaskBase::PreparePlaceHolder() {
size_t total_size = 0;
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
for (s32 i = 0; i < count; i++) {
R_UNLESS(!this->IsCancelRequested(), ncm::ResultCreatePlaceHolderCancelled());
AMS_FUNCTION_LOCAL_STATIC_CONSTINIT(os::SdkMutex, s_placeholder_mutex);
std::scoped_lock lk(s_placeholder_mutex);
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Update the data (and check result) when we are done. */
{
ON_RESULT_FAILURE { m_data->Update(content_meta, i); };
/* Automatically choose a suitable storage id. */
auto reader = content_meta.GetReader();
StorageId storage_id = StorageId::None;
if (reader.GetStorageId() != StorageId::None) {
storage_id = reader.GetStorageId();
} else {
StorageId install_storage = this->GetInstallStorage();
R_TRY(ncm::SelectDownloadableStorage(std::addressof(storage_id), install_storage, reader.CalculateContentRequiredSize()));
}
/* Open the relevant content storage. */
ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), storage_id));
/* Update the storage id in the header. */
auto writer = content_meta.GetWriter();
writer.SetStorageId(storage_id);
for (size_t j = 0; j < writer.GetContentCount(); j++) {
R_UNLESS(!this->IsCancelRequested(), ncm::ResultCreatePlaceHolderCancelled());
auto *content_info = writer.GetWritableContentInfo(j);
/* Check if we have the content already exists. */
bool has_content;
R_TRY(content_storage.Has(std::addressof(has_content), content_info->GetId()));
if (has_content) {
/* Add the size of installed content infos to the total size. */
if (content_info->install_state == InstallState::Installed) {
total_size += content_info->GetSize();
}
/* Update the install state. */
content_info->install_state = InstallState::AlreadyExists;
/* Continue. */
continue;
}
if (content_info->install_state == InstallState::NotPrepared) {
/* Generate a placeholder id. */
const PlaceHolderId placeholder_id = content_storage.GeneratePlaceHolderId();
/* Update the placeholder id in the content info. */
content_info->placeholder_id = placeholder_id;
/* Create the placeholder. */
R_TRY(content_storage.CreatePlaceHolder(placeholder_id, content_info->GetId(), content_info->GetSize()));
/* Update the install state. */
content_info->install_state = InstallState::Prepared;
}
/* Update the storage id for the content info. */
content_info->storage_id = storage_id;
/* Add the size of this content info to the total size. */
total_size += content_info->GetSize();
}
}
/* Try to update our data. */
R_TRY(m_data->Update(content_meta, i));
}
this->SetTotalSize(total_size);
R_SUCCEED();
}
Result InstallTaskBase::WriteContentMetaToPlaceHolder(InstallContentInfo *out_install_content_info, ContentStorage *storage, const InstallContentMetaInfo &meta_info, util::optional<bool> is_temporary) {
/* Generate a placeholder id. */
auto placeholder_id = storage->GeneratePlaceHolderId();
/* Create the placeholder. */
R_TRY(storage->CreatePlaceHolder(placeholder_id, meta_info.content_id, meta_info.content_size));
ON_RESULT_FAILURE { storage->DeletePlaceHolder(placeholder_id); };
/* Output install content info. */
*out_install_content_info = this->MakeInstallContentInfoFrom(meta_info, placeholder_id, is_temporary);
/* Write install content info. */
R_TRY(this->WritePlaceHolder(meta_info.key, out_install_content_info));
/* Don't delete the placeholder. Set state to installed. */
out_install_content_info->install_state = InstallState::Installed;
R_SUCCEED();
}
Result InstallTaskBase::PrepareContentMeta(const InstallContentMetaInfo &meta_info, util::optional<ContentMetaKey> expected_key, util::optional<u32> source_version) {
/* Open the BuiltInSystem content storage. */
ContentStorage content_storage;
R_TRY(OpenContentStorage(std::addressof(content_storage), StorageId::BuiltInSystem));
/* Write content meta to a placeholder. */
InstallContentInfo content_info;
R_TRY(this->WriteContentMetaToPlaceHolder(std::addressof(content_info), std::addressof(content_storage), meta_info, util::nullopt));
/* Get the path of the placeholder. */
Path path;
content_storage.GetPlaceHolderPath(std::addressof(path), content_info.GetPlaceHolderId());
/* If we fail, delete the placeholder. */
ON_RESULT_FAILURE { content_storage.DeletePlaceHolder(content_info.GetPlaceHolderId()); };
/* Create a new temporary InstallContentInfo if relevant. */
const bool is_temporary = content_info.is_temporary;
if (is_temporary) {
content_info = {
.digest = content_info.digest,
.info = content_info.info,
.placeholder_id = content_info.GetPlaceHolderId(),
.meta_type = content_info.meta_type,
.verify_digest = content_info.verify_digest,
};
}
/* Retrieve the install content meta data. */
AutoBuffer meta;
R_TRY(this->GetInstallContentMetaDataFromPath(std::addressof(meta), path, content_info, source_version));
/* Update the storage id if BuiltInSystem. */
if (m_install_storage == StorageId::BuiltInSystem) {
InstallContentMetaWriter writer(meta.Get(), meta.GetSize());
writer.SetStorageId(StorageId::BuiltInSystem);
}
/* Validate the expected key if we have an expectation. */
if (expected_key) {
InstallContentMetaReader reader(meta.Get(), meta.GetSize());
R_UNLESS(IsExpectedKey(*expected_key, reader.GetKey()), ncm::ResultUnexpectedContentMetaPrepared());
}
/* Push the data. */
R_TRY(m_data->Push(meta.Get(), meta.GetSize()));
/* If the placeholder is temporary, delete it. */
if (is_temporary) {
content_storage.DeletePlaceHolder(content_info.GetPlaceHolderId());
}
R_SUCCEED();
}
Result InstallTaskBase::PrepareContentMeta(ContentId content_id, s64 size, ContentMetaType meta_type, AutoBuffer *buffer) {
/* Create a reader. */
PackagedContentMetaReader reader(buffer->Get(), buffer->GetSize());
/* Initialize the temporary buffer. */
AutoBuffer tmp_buffer;
R_TRY(tmp_buffer.Initialize(reader.CalculateConvertInstallContentMetaSize()));
/* Convert packaged content meta to install content meta. */
reader.ConvertToInstallContentMeta(tmp_buffer.Get(), tmp_buffer.GetSize(), InstallContentInfo::Make(ContentInfo::Make(content_id, size, ContentInfo::DefaultContentAttributes, ContentType::Meta), meta_type));
/* Push the content meta. */
m_data->Push(tmp_buffer.Get(), tmp_buffer.GetSize());
R_SUCCEED();
}
void InstallTaskBase::PrepareAgain() {
this->SetProgressState(InstallProgressState::NotPrepared);
}
Result InstallTaskBase::PrepareDependency() {
R_SUCCEED();
}
Result InstallTaskBase::PrepareSystemUpdateDependency() {
/* Cleanup on failure. */
ON_RESULT_FAILURE { this->Cleanup(); };
/* Count the number of content meta entries. */
s32 count;
R_TRY(this->CountInstallContentMetaData(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
/* Skip non system update content metas. */
if (reader.GetHeader()->type != ContentMetaType::SystemUpdate) {
continue;
}
/* Get the content info. */
const auto *content_info = reader.GetContentInfo(ContentType::Meta);
/* List content meta infos. */
std::unique_ptr<ContentMetaInfo[]> content_meta_infos;
s32 num_content_meta_infos;
R_TRY(this->ReadContentMetaInfoList(std::addressof(num_content_meta_infos), std::addressof(content_meta_infos), reader.GetKey(), content_info->GetContentAttributes()));
/* Iterate over content meta infos. */
for (s32 j = 0; j < num_content_meta_infos; j++) {
ContentMetaInfo &content_meta_info = content_meta_infos[j];
const ContentMetaKey content_meta_info_key = content_meta_info.ToKey();
/* If exfat driver is not included or is required, prepare the content meta. */
if (!(content_meta_info.attributes & ContentMetaAttribute_IncludesExFatDriver) || (m_config & InstallConfig_RequiresExFatDriver)) {
R_TRY(this->PrepareContentMetaIfLatest(content_meta_info_key));
}
}
}
R_SUCCEED();
}
Result InstallTaskBase::GetSystemUpdateTaskApplyInfo(SystemUpdateTaskApplyInfo *out) {
/* Open the BuiltInSystem content meta database. */
ContentMetaDatabase meta_db;
R_TRY(OpenContentMetaDatabase(std::addressof(meta_db), StorageId::BuiltInSystem));
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(this->GetInstallContentMetaData(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
/* Skip non system update content metas. */
if (reader.GetHeader()->type != ContentMetaType::SystemUpdate) {
continue;
}
/* Get the content info. */
const auto *content_info = reader.GetContentInfo(ContentType::Meta);
/* List content meta infos. */
std::unique_ptr<ContentMetaInfo[]> content_meta_infos;
s32 num_content_meta_infos;
R_TRY(this->ReadContentMetaInfoList(std::addressof(num_content_meta_infos), std::addressof(content_meta_infos), reader.GetKey(), content_info->GetContentAttributes()));
/* Iterate over content meta infos. */
for (s32 j = 0; j < num_content_meta_infos; j++) {
const ContentMetaInfo &content_meta_info = content_meta_infos[j];
bool found = true;
/* Get the latest key. */
ContentMetaKey installed_key;
R_TRY_CATCH(meta_db.GetLatest(std::addressof(installed_key), content_meta_info.id)) {
R_CATCH(ncm::ResultContentMetaNotFound) {
/* Key doesn't exist, this is okay. */
found = false;
}
} R_END_TRY_CATCH;
/* Exfat driver included, but not required. */
if (content_meta_info.attributes & ContentMetaAttribute_IncludesExFatDriver && !(m_config & InstallConfig_RequiresExFatDriver)) {
continue;
}
/* No reboot is required if we're installing a version below. */
if (found && content_meta_info.version <= installed_key.version) {
continue;
}
/* If not rebootless, a reboot is required. */
if (!(content_meta_info.attributes & ContentMetaAttribute_Rebootless)) {
*out = SystemUpdateTaskApplyInfo::RequireReboot;
R_SUCCEED();
}
}
}
*out = SystemUpdateTaskApplyInfo::RequireNoReboot;
R_SUCCEED();
}
Result InstallTaskBase::PrepareContentMetaIfLatest(const ContentMetaKey &key) {
/* Check if the key is newer than what is already installed. */
bool newer_than_installed;
R_TRY(this->IsNewerThanInstalled(std::addressof(newer_than_installed), key));
if (newer_than_installed) {
/* Get and prepare install content meta info. */
InstallContentMetaInfo install_content_meta_info;
R_TRY(this->GetInstallContentMetaInfo(std::addressof(install_content_meta_info), key));
R_TRY(this->PrepareContentMeta(install_content_meta_info, key, util::nullopt));
}
R_SUCCEED();
}
Result InstallTaskBase::IsNewerThanInstalled(bool *out, const ContentMetaKey &key) {
/* Obtain a list of suitable storage ids. */
auto storage_list = GetStorageList(m_install_storage);
/* Iterate over storage ids. */
for (s32 i = 0; i < storage_list.Count(); i++) {
/* Open the content meta database. */
ContentMetaDatabase meta_db;
if (R_FAILED(OpenContentMetaDatabase(std::addressof(meta_db), storage_list[i]))) {
continue;
}
/* Get the latest key. */
ContentMetaKey latest_key;
R_TRY_CATCH(meta_db.GetLatest(std::addressof(latest_key), key.id)) {
R_CATCH(ncm::ResultContentMetaNotFound) {
/* Key doesn't exist, this is okay. */
continue;
}
} R_END_TRY_CATCH;
/* Check if installed key is newer. */
if (latest_key.version >= key.version) {
*out = false;
R_SUCCEED();
}
}
/* Input key is newer. */
*out = true;
R_SUCCEED();
}
Result InstallTaskBase::CountInstallContentMetaData(s32 *out_count) {
R_RETURN(m_data->Count(out_count));
}
Result InstallTaskBase::GetInstallContentMetaData(InstallContentMeta *out_content_meta, s32 index) {
R_RETURN(m_data->Get(out_content_meta, index));
}
Result InstallTaskBase::DeleteInstallContentMetaData(const ContentMetaKey *keys, s32 num_keys) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(this->CountInstallContentMetaData(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(this->GetInstallContentMetaData(std::addressof(content_meta), i));
/* Cleanup if the input keys contain this key. */
if (Contains(keys, num_keys, content_meta.GetReader().GetKey())) {
R_TRY(this->CleanupOne(content_meta));
}
}
/* Delete the data if count < 1. */
R_RETURN(m_data->Delete(keys, num_keys));
}
Result InstallTaskBase::GetInstallContentMetaDataFromPath(AutoBuffer *out, const Path &path, const InstallContentInfo &content_info, util::optional<u32> source_version) {
fs::ContentAttributes attr;
AutoBuffer meta;
R_TRY(TryReadContentMetaPath(std::addressof(attr), std::addressof(meta), path.str, ReadContentMetaPathWithoutExtendedDataOrDigestSuppressingFsAbort));
/* Create a reader. */
PackagedContentMetaReader reader(meta.Get(), meta.GetSize());
size_t meta_size;
AutoBuffer install_meta_data;
if (source_version) {
/* Declare buffers. */
constexpr size_t BufferCount = 2;
constexpr size_t BufferSize = 3_KB;
u8 buffers[BufferCount][BufferSize];
/* Create a mapper. */
auto mapper = MultiCacheReadonlyMapper<4>(Span<u8>(buffers[0], sizeof(buffers[0])), Span<u8>(buffers[1], sizeof(buffers[1])));
R_TRY(mapper.Initialize(path.str, static_cast<fs::ContentAttributes>(static_cast<u8>(attr) & fs::ContentAttributes_All), true));
/* Create an accessor. */
auto accessor = PatchMetaExtendedDataAccessor{std::addressof(mapper)};
/* Convert to fragment only install meta. */
R_TRY(MetaConverter::GetFragmentOnlyInstallContentMeta(std::addressof(install_meta_data), content_info, reader, std::addressof(accessor), source_version.value()));
} else {
/* Convert to install content meta. */
meta_size = reader.CalculateConvertInstallContentMetaSize();
R_TRY(install_meta_data.Initialize(meta_size));
reader.ConvertToInstallContentMeta(install_meta_data.Get(), install_meta_data.GetSize(), content_info);
}
/* Set output. */
*out = std::move(install_meta_data);
R_SUCCEED();
}
InstallContentInfo InstallTaskBase::MakeInstallContentInfoFrom(const InstallContentMetaInfo &info, const PlaceHolderId &placeholder_id, util::optional<bool> is_tmp) {
return {
.digest = info.digest,
.info = ContentInfo::Make(info.content_id, info.content_size, ContentInfo::DefaultContentAttributes, ContentType::Meta, 0),
.placeholder_id = placeholder_id,
.meta_type = info.key.type,
.install_state = InstallState::Prepared,
.verify_digest = info.verify_digest,
.storage_id = StorageId::BuiltInSystem,
.is_temporary = is_tmp ? *is_tmp : (m_install_storage != StorageId::BuiltInSystem),
};
}
InstallProgress InstallTaskBase::GetProgress() {
std::scoped_lock lk(m_progress_mutex);
return m_progress;
}
void InstallTaskBase::ResetLastResult() {
this->SetLastResult(ResultSuccess());
}
void InstallTaskBase::SetTotalSize(s64 size) {
std::scoped_lock lk(m_progress_mutex);
m_progress.total_size = size;
}
void InstallTaskBase::IncrementProgress(s64 size) {
std::scoped_lock lk(m_progress_mutex);
m_progress.installed_size += size;
}
void InstallTaskBase::SetLastResult(Result last_result) {
std::scoped_lock lk(m_progress_mutex);
m_data->SetLastResult(last_result);
m_progress.SetLastResult(last_result);
}
void InstallTaskBase::CleanupProgress() {
std::scoped_lock lk(m_progress_mutex);
m_progress = {};
}
InstallThroughput InstallTaskBase::GetThroughput() {
std::scoped_lock lk(m_throughput_mutex);
return m_throughput;
}
void InstallTaskBase::ResetThroughputMeasurement() {
std::scoped_lock lk(m_throughput_mutex);
m_throughput = { .elapsed_time = TimeSpan() };
m_throughput_start_time = TimeSpan();
}
void InstallTaskBase::StartThroughputMeasurement() {
std::scoped_lock lk(m_throughput_mutex);
m_throughput = { .elapsed_time = TimeSpan() };
m_throughput_start_time = os::GetSystemTick().ToTimeSpan();
}
void InstallTaskBase::UpdateThroughputMeasurement(s64 throughput) {
std::scoped_lock lk(m_throughput_mutex);
/* Update throughput only if start time has been set. */
if (m_throughput_start_time.GetNanoSeconds() != 0) {
m_throughput.installed += throughput;
m_throughput.elapsed_time = os::GetSystemTick().ToTimeSpan() - m_throughput_start_time;
}
}
Result InstallTaskBase::CalculateContentsSize(s64 *out_size, const ContentMetaKey &key, StorageId storage_id) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Open the content storage. */
ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), storage_id));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
/* Skip this content meta if the key doesn't match. */
if (reader.GetKey() != key) {
continue;
}
/* If the storage is unique and doesn't match, continue. */
if (IsUniqueStorage(storage_id) && reader.GetStorageId() != storage_id) {
continue;
}
/* Set the out size to 0. */
*out_size = 0;
/* Sum the sizes from the content infos. */
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const auto *content_info = reader.GetContentInfo(j);
/* If this content info isn't prepared, continue. */
if (content_info->install_state == InstallState::NotPrepared) {
continue;
}
/* Check if this content info has a placeholder. */
bool has_placeholder;
R_TRY(content_storage.HasPlaceHolder(std::addressof(has_placeholder), content_info->GetPlaceHolderId()));
/* Add the placeholder size to the total. */
if (has_placeholder) {
*out_size += content_info->GetSize();
}
}
/* No need to look for any further keys. */
R_SUCCEED();
}
*out_size = 0;
R_SUCCEED();
}
Result InstallTaskBase::ReadContentMetaInfoList(s32 *out_count, std::unique_ptr<ContentMetaInfo[]> *out_meta_infos, const ContentMetaKey &key, fs::ContentAttributes attr) {
/* Get the install content meta info. */
InstallContentMetaInfo install_content_meta_info;
R_TRY(this->GetInstallContentMetaInfo(std::addressof(install_content_meta_info), key));
/* Open the BuiltInSystem content storage. */
ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), StorageId::BuiltInSystem));
/* Write content meta to a placeholder. */
InstallContentInfo content_info;
R_TRY(this->WriteContentMetaToPlaceHolder(std::addressof(content_info), std::addressof(content_storage), install_content_meta_info, true));
const PlaceHolderId placeholder_id = content_info.GetPlaceHolderId();
/* Get the path of the new placeholder. */
Path path;
content_storage.GetPlaceHolderPath(std::addressof(path), placeholder_id);
/* Read the variation list. */
R_TRY(ReadVariationContentMetaInfoList(out_count, out_meta_infos, path, attr, m_firmware_variation_id));
/* Delete the placeholder. */
content_storage.DeletePlaceHolder(placeholder_id);
R_SUCCEED();
}
Result InstallTaskBase::FindMaxRequiredApplicationVersion(u32 *out) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
u32 max_version = 0;
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
/* Check if the meta type is for add on content. */
if (reader.GetKey().type == ContentMetaType::AddOnContent) {
const auto *extended_header = reader.GetExtendedHeader<AddOnContentMetaExtendedHeader>();
/* Set the max version if higher. */
max_version = std::max(max_version, extended_header->required_application_version);
}
}
*out = max_version;
R_SUCCEED();
}
Result InstallTaskBase::ListOccupiedSize(s32 *out_written, InstallTaskOccupiedSize *out_list, s32 out_list_size, s32 offset) {
AMS_ABORT_UNLESS(offset >= 0);
/* Count the number of content meta entries. */
s32 data_count;
R_TRY(m_data->Count(std::addressof(data_count)));
/* Iterate over content meta. */
s32 count = 0;
for (s32 i = offset; i < data_count && count < out_list_size; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
const StorageId storage_id = reader.GetStorageId();
s64 total_size = 0;
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const auto *content_info = reader.GetContentInfo(j);
/* Skip the content info if not prepared. */
if (content_info->GetInstallState() == InstallState::NotPrepared) {
continue;
}
/* Open the relevant content storage. */
ContentStorage content_storage;
R_TRY_CATCH(ncm::OpenContentStorage(std::addressof(content_storage), storage_id)) {
R_CATCH(ncm::ResultContentStorageNotActive) { break; }
} R_END_TRY_CATCH;
/* Check if this content info has a placeholder. */
bool has_placeholder;
R_TRY(content_storage.HasPlaceHolder(std::addressof(has_placeholder), content_info->GetPlaceHolderId()));
if (has_placeholder) {
total_size += content_info->GetSize();
}
}
/* Output this InstallTaskOccupiedSize. */
out_list[count++] = {
.key = reader.GetKey(),
.size = total_size,
.storage_id = storage_id,
};
}
/* Write the out count. */
*out_written = count;
R_SUCCEED();
}
void InstallTaskBase::SetProgressState(InstallProgressState state) {
std::scoped_lock lk(m_progress_mutex);
m_data->SetState(state);
m_progress.state = state;
}
Result InstallTaskBase::FindMaxRequiredSystemVersion(u32 *out) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
u32 max_version = 0;
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
if (reader.GetHeader()->type == ContentMetaType::Application) {
const auto *extended_header = reader.GetExtendedHeader<ApplicationMetaExtendedHeader>();
/* Set the max version if higher. */
if (extended_header->required_system_version >= max_version) {
max_version = extended_header->required_system_version;
}
} else if (reader.GetHeader()->type == ContentMetaType::Patch) {
const auto *extended_header = reader.GetExtendedHeader<PatchMetaExtendedHeader>();
/* Set the max version if higher. */
if (extended_header->required_system_version >= max_version) {
max_version = extended_header->required_system_version;
}
}
}
*out = max_version;
R_SUCCEED();
}
Result InstallTaskBase::CanContinue() {
switch (this->GetProgress().state) {
case InstallProgressState::NotPrepared:
case InstallProgressState::DataPrepared:
R_UNLESS(!this->IsCancelRequested(), ncm::ResultCreatePlaceHolderCancelled());
break;
case InstallProgressState::Prepared:
R_UNLESS(!this->IsCancelRequested(), ncm::ResultWritePlaceHolderCancelled());
break;
default:
break;
}
R_SUCCEED();
}
Result InstallTaskBase::ListRightsIds(s32 *out_count, Span<RightsId> out_span, const ContentMetaKey &key, s32 offset) {
/* Count the number of content meta entries. */
s32 count;
R_TRY(m_data->Count(std::addressof(count)));
/* Ensure count is >= 1. */
R_UNLESS(count >= 1, ncm::ResultContentMetaNotFound());
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(m_data->Get(std::addressof(content_meta), i));
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
/* List rights ids if the reader's key matches ours. */
if (reader.GetKey() == key) {
R_RETURN(this->ListRightsIdsByInstallContentMeta(out_count, out_span, content_meta, offset));
}
}
R_THROW(ncm::ResultContentMetaNotFound());
}
Result InstallTaskBase::ListRightsIdsByInstallContentMeta(s32 *out_count, Span<RightsId> out_span, const InstallContentMeta &content_meta, s32 offset) {
/* If the offset is greater than zero, we can't create a unique span of rights ids. */
/* Thus, we have nothing to list. */
if (offset > 0) {
*out_count = 0;
R_SUCCEED();
}
/* Create a reader. */
const InstallContentMetaReader reader = content_meta.GetReader();
s32 count = 0;
for (size_t i = 0; i < reader.GetContentCount(); i++) {
const auto *content_info = reader.GetContentInfo(i);
/* Skip meta content infos and already installed content infos. Also skip if the content meta has already been comitted. */
if (content_info->GetType() == ContentType::Meta || content_info->GetInstallState() == InstallState::Installed || reader.GetHeader()->committed) {
continue;
}
/* Open the relevant content storage. */
ContentStorage content_storage;
R_TRY(ncm::OpenContentStorage(std::addressof(content_storage), content_info->storage_id));
/* Get the rights id. */
RightsId rights_id;
R_TRY(content_storage.GetRightsId(std::addressof(rights_id), content_info->GetPlaceHolderId(), content_info->GetContentAttributes()));
/* Skip empty rights ids. */
if (rights_id.id == fs::InvalidRightsId) {
continue;
}
/* Output the rights id. */
out_span[count++] = rights_id;
}
/* Sort and remove duplicate ids from the output span. */
std::sort(out_span.begin(), out_span.end());
*out_count = std::distance(out_span.begin(), std::unique(out_span.begin(), out_span.end()));
R_SUCCEED();
}
}
| 56,541
|
C++
|
.cpp
| 1,110
| 38.902703
| 215
| 0.591498
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,842
|
ncm_content_meta_type.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_meta_type.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
const char *GetContentMetaTypeString(ContentMetaType type) {
switch (type) {
case ContentMetaType::Application: return "Application";
case ContentMetaType::Patch: return "Patch";
case ContentMetaType::AddOnContent: return "AddOnContent";
case ContentMetaType::DataPatch: return "DataPatch";
default: return "(unknown)";
}
}
}
| 1,135
|
C++
|
.cpp
| 27
| 37.296296
| 76
| 0.689593
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,843
|
ncm_package_system_downgrade_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_package_system_downgrade_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
Result PackageSystemDowngradeTask::PreCommit() {
constexpr size_t MaxContentMetas = 0x40;
auto &data = this->GetInstallData();
/* Count the number of content meta entries. */
s32 count;
R_TRY(data.Count(std::addressof(count)));
/* Iterate over content meta. */
for (s32 i = 0; i < count; i++) {
/* Obtain the content meta. */
InstallContentMeta content_meta;
R_TRY(data.Get(std::addressof(content_meta), i));
/* Create a reader. */
const auto reader = content_meta.GetReader();
const auto key = reader.GetKey();
/* Obtain a list of suitable storage ids. */
const auto storage_list = GetStorageList(this->GetInstallStorage());
/* Iterate over storage ids. */
for (s32 i = 0; i < storage_list.Count(); i++) {
/* Open the content meta database. */
ContentMetaDatabase meta_db;
if (R_FAILED(OpenContentMetaDatabase(std::addressof(meta_db), storage_list[i]))) {
continue;
}
/* List keys matching the type and id of the install content meta key. */
ncm::ContentMetaKey keys[MaxContentMetas];
const auto count = meta_db.ListContentMeta(keys, MaxContentMetas, key.type, { key.id });
/* Remove matching keys. */
for (auto i = 0; i < count.total; i++) {
meta_db.Remove(keys[i]);
}
}
}
R_SUCCEED();
}
Result PackageSystemDowngradeTask::Commit() {
R_TRY(this->PreCommit());
R_RETURN(InstallTaskBase::Commit());
}
Result PackageSystemDowngradeTask::PrepareContentMetaIfLatest(const ContentMetaKey &key) {
/* Get and prepare install content meta info. We aren't concerned if our key is older. */
InstallContentMetaInfo install_content_meta_info;
R_TRY(this->GetInstallContentMetaInfo(std::addressof(install_content_meta_info), key));
R_RETURN(this->PrepareContentMeta(install_content_meta_info, key, util::nullopt));
}
}
| 2,881
|
C++
|
.cpp
| 62
| 37.33871
| 104
| 0.624955
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,844
|
ncm_registered_host_content.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_registered_host_content.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
class RegisteredHostContent::RegisteredPath : public util::IntrusiveListBaseNode<RegisteredPath> {
NON_COPYABLE(RegisteredPath);
NON_MOVEABLE(RegisteredPath);
private:
ContentId m_content_id;
Path m_path;
public:
RegisteredPath(const ncm::ContentId &content_id, const Path &p) : m_content_id(content_id), m_path(p) {
/* ... */
}
ncm::ContentId GetContentId() const {
return m_content_id;
}
void GetPath(Path *out) const {
*out = m_path;
}
void SetPath(const Path &path) {
m_path = path;
}
};
RegisteredHostContent::~RegisteredHostContent() {
/* ... */
}
Result RegisteredHostContent::RegisterPath(const ncm::ContentId &content_id, const ncm::Path &path) {
std::scoped_lock lk(m_mutex);
/* Replace the path of any existing entries. */
for (auto ®istered_path : m_path_list) {
if (registered_path.GetContentId() == content_id) {
registered_path.SetPath(path);
R_SUCCEED();
}
}
/* Allocate a new registered path. TODO: Verify allocator. */
RegisteredPath *registered_path = new RegisteredPath(content_id, path);
R_UNLESS(registered_path != nullptr, ncm::ResultBufferInsufficient());
/* Insert the path into the list. */
m_path_list.push_back(*registered_path);
R_SUCCEED();
}
Result RegisteredHostContent::GetPath(Path *out, const ncm::ContentId &content_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the path of the content. */
for (const auto ®istered_path : m_path_list) {
if (registered_path.GetContentId() == content_id) {
registered_path.GetPath(out);
R_SUCCEED();
}
}
R_THROW(ncm::ResultContentNotFound());
}
void RegisteredHostContent::ClearPaths() {
/* Remove all paths. */
for (auto it = m_path_list.begin(); it != m_path_list.end(); /* ... */) {
auto *obj = std::addressof(*it);
it = m_path_list.erase(it);
delete obj;
}
}
}
| 2,993
|
C++
|
.cpp
| 76
| 30.697368
| 115
| 0.601447
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,845
|
ncm_read_only_content_storage_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_read_only_content_storage_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_read_only_content_storage_impl.hpp"
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
void MakeContentPath(PathString *out, ContentId id, MakeContentPathFunction func, const char *root_path) {
return func(out, id, root_path);
}
void MakeGameCardContentMetaPath(PathString *out, ContentId id, MakeContentPathFunction func, const char *root_path) {
/* Determine the content path. */
PathString path;
func(std::addressof(path), id, root_path);
/* Substitute the .nca extension with .cmnt.nca. */
*out = path.MakeSubString(0, path.GetLength() - 4);
out->Append(".cnmt.nca");
}
Result OpenContentIdFileImpl(fs::FileHandle *out, ContentId id, MakeContentPathFunction func, const char *root_path) {
PathString path;
MakeContentPath(std::addressof(path), id, func, root_path);
/* Open the content file. */
/* If absent, make the path for game card content meta and open again. */
R_TRY_CATCH(fs::OpenFile(out, path, fs::OpenMode_Read)) {
R_CATCH(fs::ResultPathNotFound) {
MakeGameCardContentMetaPath(std::addressof(path), id, func, root_path);
R_TRY(fs::OpenFile(out, path, fs::OpenMode_Read));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
}
Result ReadOnlyContentStorageImpl::Initialize(const char *path, MakeContentPathFunction content_path_func) {
R_TRY(this->EnsureEnabled());
m_root_path.Assign(path);
m_make_content_path_func = content_path_func;
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GeneratePlaceHolderId(sf::Out<PlaceHolderId> out) {
AMS_UNUSED(out);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::CreatePlaceHolder(PlaceHolderId placeholder_id, ContentId content_id, s64 size) {
AMS_UNUSED(placeholder_id, content_id, size);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::DeletePlaceHolder(PlaceHolderId placeholder_id) {
AMS_UNUSED(placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::HasPlaceHolder(sf::Out<bool> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::WritePlaceHolder(PlaceHolderId placeholder_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(placeholder_id, offset, data);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::Register(PlaceHolderId placeholder_id, ContentId content_id) {
AMS_UNUSED(placeholder_id, content_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::Delete(ContentId content_id) {
AMS_UNUSED(content_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::Has(sf::Out<bool> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Make the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Check if the file exists. */
bool has;
R_TRY(fs::HasFile(std::addressof(has), content_path));
/* If the file is absent, make the path for game card content meta and check presence again. */
if (!has) {
MakeGameCardContentMetaPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
R_TRY(fs::HasFile(std::addressof(has), content_path));
}
out.SetValue(has);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GetPath(sf::Out<Path> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Make the path for game card content meta. */
PathString content_path;
MakeGameCardContentMetaPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Check if the file exists. */
bool has_file;
R_TRY(fs::HasFile(std::addressof(has_file), content_path));
/* If the file is absent, make the path for regular content. */
if (!has_file) {
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
}
/* Substitute mount name with the common mount name. */
Path common_path;
R_TRY(fs::ConvertToFsCommonPath(common_path.str, sizeof(common_path.str), content_path));
out.SetValue(common_path);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GetPlaceHolderPath(sf::Out<Path> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::CleanupAllPlaceHolder() {
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::ListPlaceHolder(sf::Out<s32> out_count, const sf::OutArray<PlaceHolderId> &out_buf) {
AMS_UNUSED(out_count, out_buf);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetContentCount(sf::Out<s32> out_count) {
AMS_UNUSED(out_count);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::ListContentId(sf::Out<s32> out_count, const sf::OutArray<ContentId> &out_buf, s32 offset) {
AMS_UNUSED(out_count, out_buf, offset);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetSizeFromContentId(sf::Out<s64> out_size, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Open the file for the content id. */
fs::FileHandle file;
R_TRY(OpenContentIdFileImpl(std::addressof(file), content_id, m_make_content_path_func, m_root_path));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Determine the file size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
out_size.SetValue(file_size);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::DisableForcibly() {
m_disabled = true;
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::RevertToPlaceHolder(PlaceHolderId placeholder_id, ContentId old_content_id, ContentId new_content_id) {
AMS_UNUSED(placeholder_id, old_content_id, new_content_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::SetPlaceHolderSize(PlaceHolderId placeholder_id, s64 size) {
AMS_UNUSED(placeholder_id, size);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::ReadContentIdFile(const sf::OutBuffer &buf, ContentId content_id, s64 offset) {
/* Ensure offset is valid. */
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
/* Open the file for the content id. */
fs::FileHandle file;
R_TRY(OpenContentIdFileImpl(std::addressof(file), content_id, m_make_content_path_func, m_root_path));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Read from the given offset up to the given size. */
R_TRY(fs::ReadFile(file, offset, buf.GetPointer(), buf.GetSize()));
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
AMS_UNUSED(out_rights_id, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
AMS_UNUSED(out_rights_id, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromPlaceHolderId(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, attr);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromContentIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, ContentId content_id) {
/* Obtain the regular rights id for the content id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromContentIdDeprecated2(std::addressof(rights_id), content_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromContentIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id) {
R_RETURN(this->GetRightsIdFromContentId(out_rights_id, content_id, fs::ContentAttributes_None));
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromContentId(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the content path. */
Path path;
R_TRY(this->GetPath(std::addressof(path), content_id));
/* Get the rights id. */
ncm::RightsId rights_id;
R_TRY(GetRightsId(std::addressof(rights_id), path, attr));
out_rights_id.SetValue(rights_id);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::WriteContentForDebug(ContentId content_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(content_id, offset, data);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetFreeSpaceSize(sf::Out<s64> out_size) {
out_size.SetValue(0);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::GetTotalSpaceSize(sf::Out<s64> out_size) {
out_size.SetValue(0);
R_SUCCEED();
}
Result ReadOnlyContentStorageImpl::FlushPlaceHolder() {
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetSizeFromPlaceHolderId(sf::Out<s64> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::RepairInvalidFileAttribute() {
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::GetRightsIdFromPlaceHolderIdWithCache(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, ContentId cache_content_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, cache_content_id, attr);
R_THROW(ncm::ResultNotSupported());
}
Result ReadOnlyContentStorageImpl::RegisterPath(const ContentId &content_id, const Path &path) {
AMS_UNUSED(content_id, path);
R_THROW(ncm::ResultInvalidOperation());
}
Result ReadOnlyContentStorageImpl::ClearRegisteredPath() {
R_THROW(ncm::ResultInvalidOperation());
}
Result ReadOnlyContentStorageImpl::GetProgramId(sf::Out<ncm::ProgramId> out, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the path of the content. */
Path path;
R_TRY(this->GetPath(std::addressof(path), content_id));
/* Obtain the program id for the content. */
ncm::ProgramId program_id;
R_TRY(fs::GetProgramId(std::addressof(program_id), path.str, attr));
out.SetValue(program_id);
R_SUCCEED();
}
}
| 12,306
|
C++
|
.cpp
| 247
| 41.898785
| 202
| 0.678092
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,846
|
ncm_package_install_task_base.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_package_install_task_base.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
Result PackageInstallTaskBase::Initialize(const char *package_root_path, void *buffer, size_t buffer_size, StorageId storage_id, InstallTaskDataBase *data, u32 config) {
R_TRY(InstallTaskBase::Initialize(storage_id, data, config));
m_package_root.Assign(package_root_path);
m_buffer = buffer;
m_buffer_size = buffer_size;
R_SUCCEED();
}
Result PackageInstallTaskBase::OnWritePlaceHolder(const ContentMetaKey &key, InstallContentInfo *content_info) {
AMS_UNUSED(key);
/* Get the file path. */
PackagePath path;
if (content_info->GetType() == ContentType::Meta) {
this->CreateContentMetaPath(std::addressof(path), content_info->GetId());
} else {
this->CreateContentPath(std::addressof(path), content_info->GetId());
}
/* Open the file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Continuously write the file to the placeholder until there is nothing left to write. */
while (true) {
/* Read as much of the remainder of the file as possible. */
size_t size_read;
R_TRY(fs::ReadFile(std::addressof(size_read), file, content_info->written, m_buffer, m_buffer_size));
/* There is nothing left to read. */
if (size_read == 0) {
break;
}
/* Write the placeholder. */
R_TRY(this->WritePlaceHolderBuffer(content_info, m_buffer, size_read));
}
R_SUCCEED();
}
Result PackageInstallTaskBase::InstallTicket(const fs::RightsId &rights_id, ContentMetaType meta_type) {
AMS_UNUSED(meta_type);
/* Read ticket from file. */
s64 ticket_size;
std::unique_ptr<char[]> ticket;
{
fs::FileHandle ticket_file;
{
PackagePath ticket_path;
this->CreateTicketPath(std::addressof(ticket_path), rights_id);
R_TRY(fs::OpenFile(std::addressof(ticket_file), ticket_path, fs::OpenMode_Read));
}
ON_SCOPE_EXIT { fs::CloseFile(ticket_file); };
R_TRY(fs::GetFileSize(std::addressof(ticket_size), ticket_file));
ticket.reset(new (std::nothrow) char[static_cast<size_t>(ticket_size)]);
R_UNLESS(ticket != nullptr, ncm::ResultAllocationFailed());
R_TRY(fs::ReadFile(ticket_file, 0, ticket.get(), static_cast<size_t>(ticket_size)));
}
/* Read certificate from file. */
s64 cert_size;
std::unique_ptr<char[]> cert;
{
fs::FileHandle cert_file;
{
PackagePath cert_path;
this->CreateCertificatePath(std::addressof(cert_path), rights_id);
R_TRY(fs::OpenFile(std::addressof(cert_file), cert_path, fs::OpenMode_Read));
}
ON_SCOPE_EXIT { fs::CloseFile(cert_file); };
R_TRY(fs::GetFileSize(std::addressof(cert_size), cert_file));
cert.reset(new (std::nothrow) char[static_cast<size_t>(cert_size)]);
R_UNLESS(cert != nullptr, ncm::ResultAllocationFailed());
R_TRY(fs::ReadFile(cert_file, 0, cert.get(), static_cast<size_t>(cert_size)));
}
/* TODO: es::ImportTicket() */
/* TODO: How should es be handled without undesired effects? */
R_SUCCEED();
}
void PackageInstallTaskBase::CreateContentPath(PackagePath *out_path, ContentId content_id) {
char str[ContentIdStringLength + 1] = {};
GetStringFromContentId(str, sizeof(str), content_id);
out_path->AssignFormat("%s%s%s", m_package_root.Get(), str, ".nca");
}
void PackageInstallTaskBase::CreateContentMetaPath(PackagePath *out_path, ContentId content_id) {
char str[ContentIdStringLength + 1] = {};
GetStringFromContentId(str, sizeof(str), content_id);
out_path->AssignFormat("%s%s%s", m_package_root.Get(), str, ".cnmt.nca");
}
void PackageInstallTaskBase::CreateTicketPath(PackagePath *out_path, fs::RightsId id) {
char str[RightsIdStringLength + 1] = {};
GetStringFromRightsId(str, sizeof(str), id);
out_path->AssignFormat("%s%s%s", m_package_root.Get(), str, ".tik");
}
void PackageInstallTaskBase::CreateCertificatePath(PackagePath *out_path, fs::RightsId id) {
char str[RightsIdStringLength + 1] = {};
GetStringFromRightsId(str, sizeof(str), id);
out_path->AssignFormat("%s%s%s", m_package_root.Get(), str, ".cert");
}
}
| 5,365
|
C++
|
.cpp
| 110
| 39.790909
| 173
| 0.628369
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,847
|
ncm_content_management_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_management_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
constexpr inline size_t MaxPackagePathLength = 0x100;
Result ConvertToFsCommonPath(char *dst, size_t dst_size, const char *package_root_path, const char *entry_path) {
char package_path[MaxPackagePathLength];
const size_t path_len = util::SNPrintf(package_path, sizeof(package_path), "%s%s", package_root_path, entry_path);
AMS_ABORT_UNLESS(path_len < MaxPackagePathLength);
R_RETURN(fs::ConvertToFsCommonPath(dst, dst_size, package_path));
}
Result LoadContentMeta(ncm::AutoBuffer *out, const char *package_root_path, const fs::DirectoryEntry &entry) {
AMS_ABORT_UNLESS(impl::PathView(entry.name).HasSuffix(".cnmt.nca"));
char path[MaxPackagePathLength];
R_TRY(ConvertToFsCommonPath(path, sizeof(path), package_root_path, entry.name));
R_RETURN(ncm::TryReadContentMetaPath(out, path, ncm::ReadContentMetaPathWithoutExtendedDataOrDigest));
}
template<typename F>
Result ForEachFileInDirectory(const char *root_path, F f) {
/* Open the directory. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path, fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
while (true) {
/* Read the current entry. */
s64 count;
fs::DirectoryEntry entry;
R_TRY(fs::ReadDirectory(std::addressof(count), std::addressof(entry), dir, 1));
if (count == 0) {
break;
}
/* Invoke our handler on the entry. */
bool done;
R_TRY(f(std::addressof(done), entry));
R_SUCCEED_IF(done);
}
R_SUCCEED();
}
}
Result ContentMetaDatabaseBuilder::BuildFromPackageContentMeta(void *buf, size_t size, const ContentInfo &meta_info) {
/* Create a reader for the content meta. */
ncm::PackagedContentMetaReader package_meta_reader(buf, size);
/* Allocate space to hold the converted meta. */
const size_t meta_size = package_meta_reader.CalculateConvertContentMetaSize();
std::unique_ptr<char[]> meta(new (std::nothrow) char[meta_size]);
/* Convert the meta from packaged form to normal form. */
package_meta_reader.ConvertToContentMeta(meta.get(), meta_size, meta_info);
ncm::ContentMetaReader meta_reader(meta.get(), meta_size);
/* Insert the new metas into the database. */
R_TRY(m_db->Set(package_meta_reader.GetKey(), meta_reader.GetData(), meta_reader.GetSize()));
/* We're done. */
R_SUCCEED();
}
Result ContentMetaDatabaseBuilder::BuildFromStorage(ContentStorage *storage) {
/* Get the total count of contents. */
s32 total_count;
R_TRY(storage->GetContentCount(std::addressof(total_count)));
/* Loop over all contents, looking for a package we can build from. */
const size_t MaxContentIds = 64;
ContentId content_ids[MaxContentIds];
for (s32 offset = 0; offset < total_count; /* ... */) {
/* List contents at the current offset. */
s32 count;
R_TRY(storage->ListContentId(std::addressof(count), content_ids, MaxContentIds, offset));
/* Loop the contents we listed, looking for a correct one. */
for (s32 i = 0; i < count; i++) {
/* Get the path for this content id. */
auto &content_id = content_ids[i];
ncm::Path path;
storage->GetPath(std::addressof(path), content_id);
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
if (R_SUCCEEDED(ncm::TryReadContentMetaPath(std::addressof(package_meta), path.str, ncm::ReadContentMetaPathWithoutExtendedDataOrDigest))) {
/* Get the size of the content. */
s64 size;
R_TRY(storage->GetSize(std::addressof(size), content_id));
/* Build. */
R_TRY(this->BuildFromPackageContentMeta(package_meta.Get(), package_meta.GetSize(), ContentInfo::Make(content_id, size, ContentInfo::DefaultContentAttributes, ContentType::Meta)));
}
}
/* Advance. */
offset += count;
}
/* Commit our changes. */
R_RETURN(m_db->Commit());
}
Result ContentMetaDatabaseBuilder::BuildFromPackage(const char *package_root_path) {
/* Build the database by writing every entry in the package. */
R_TRY(ForEachFileInDirectory(package_root_path, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Never early terminate. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!impl::PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root_path, entry));
/* Try to parse a content id from the name. */
auto content_id = GetContentIdFromString(entry.name, sizeof(entry.name));
R_UNLESS(content_id, ncm::ResultInvalidPackageFormat());
/* Build using the meta. */
R_RETURN(this->BuildFromPackageContentMeta(package_meta.Get(), package_meta.GetSize(), ContentInfo::Make(*content_id, entry.file_size, ContentInfo::DefaultContentAttributes, ContentType::Meta)));
}));
/* Commit our changes. */
R_RETURN(m_db->Commit());
}
Result ContentMetaDatabaseBuilder::Cleanup() {
/* This cleans up the content meta by removing all entries. */
while (true) {
/* List as many keys as we can. */
constexpr s32 MaxKeys = 64;
ContentMetaKey keys[MaxKeys];
auto list_count = m_db->ListContentMeta(keys, MaxKeys);
/* Remove the listed keys. */
for (auto i = 0; i < list_count.written; i++) {
R_TRY(m_db->Remove(keys[i]));
}
/* If there aren't more keys to read, we're done. */
if (list_count.written < MaxKeys) {
break;
}
}
/* Commit our deletions. */
R_RETURN(m_db->Commit());
}
Result ListApplicationPackage(s32 *out_count, ApplicationId *out_ids, size_t max_out_ids, const char *package_root_path) {
size_t count = 0;
R_TRY(ForEachFileInDirectory(package_root_path, [&](bool *done, const fs::DirectoryEntry &entry) -> Result {
/* Never early terminate. */
*done = false;
/* We have nothing to list if we're not looking at a meta. */
R_SUCCEED_IF(!impl::PathView(entry.name).HasSuffix(".cnmt.nca"));
/* Read the content meta path, and build. */
ncm::AutoBuffer package_meta;
R_TRY(LoadContentMeta(std::addressof(package_meta), package_root_path, entry));
/* Create a reader for the meta. */
ncm::PackagedContentMetaReader package_meta_reader(package_meta.Get(), package_meta.GetSize());
/* Write the key to output if we're reading an application. */
const auto &key = package_meta_reader.GetKey();
if (key.type == ContentMetaType::Application) {
R_UNLESS(count < max_out_ids, ncm::ResultBufferInsufficient());
out_ids[count++] = { key.id };
}
R_SUCCEED();
}));
*out_count = static_cast<s32>(count);
R_SUCCEED();
}
}
| 8,573
|
C++
|
.cpp
| 163
| 41.490798
| 207
| 0.606216
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,848
|
ncm_on_memory_content_meta_database_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_on_memory_content_meta_database_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_on_memory_content_meta_database_impl.hpp"
namespace ams::ncm {
Result OnMemoryContentMetaDatabaseImpl::List(sf::Out<s32> out_entries_total, sf::Out<s32> out_entries_written, const sf::OutArray<ContentMetaKey> &out_info, ContentMetaType meta_type, ApplicationId application_id, u64 min, u64 max, ContentInstallType install_type) {
/* NOTE: This function is *almost* identical to the ContentMetaDatabaseImpl equivalent. */
/* The only difference is that the min max comparison is exclusive for OnMemoryContentMetaDatabaseImpl, */
/* but inclusive for ContentMetaDatabaseImpl. This may or may not be a Nintendo bug? */
R_TRY(this->EnsureEnabled());
size_t entries_total = 0;
size_t entries_written = 0;
/* Iterate over all entries. */
for (auto entry = m_kvs->begin(); entry != m_kvs->end(); entry++) {
const ContentMetaKey key = entry->GetKey();
/* Check if this entry matches the given filters. */
if (!((meta_type == ContentMetaType::Unknown || key.type == meta_type) && (min < key.id && key.id < max) && (install_type == ContentInstallType::Unknown || key.install_type == install_type))) {
continue;
}
/* If application id is present, check if it matches the filter. */
if (application_id != InvalidApplicationId) {
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Ensure application id matches, if present. */
if (const auto entry_application_id = reader.GetApplicationId(key); entry_application_id && application_id != *entry_application_id) {
continue;
}
}
/* Write the entry to the output buffer. */
if (entries_written < out_info.GetSize()) {
out_info[entries_written++] = key;
}
entries_total++;
}
out_entries_total.SetValue(entries_total);
out_entries_written.SetValue(entries_written);
R_SUCCEED();
}
Result OnMemoryContentMetaDatabaseImpl::GetLatestContentMetaKey(sf::Out<ContentMetaKey> out_key, u64 id) {
R_TRY(this->EnsureEnabled());
util::optional<ContentMetaKey> found_key = util::nullopt;
/* Find the last key with the desired program id. */
for (auto entry = m_kvs->lower_bound(ContentMetaKey::MakeUnknownType(id, 0)); entry != m_kvs->end(); entry++) {
/* No further entries will match the program id, discontinue. */
if (entry->GetKey().id != id) {
break;
}
/* On memory content database is interested in all keys. */
found_key = entry->GetKey();
}
/* Check if the key is absent. */
R_UNLESS(found_key, ncm::ResultContentMetaNotFound());
out_key.SetValue(*found_key);
R_SUCCEED();
}
Result OnMemoryContentMetaDatabaseImpl::LookupOrphanContent(const sf::OutArray<bool> &out_orphaned, const sf::InArray<ContentId> &content_ids) {
AMS_UNUSED(out_orphaned, content_ids);
R_THROW(ncm::ResultInvalidContentMetaDatabase());
}
Result OnMemoryContentMetaDatabaseImpl::Commit() {
R_TRY(this->EnsureEnabled());
R_SUCCEED();
}
}
| 4,226
|
C++
|
.cpp
| 81
| 42.91358
| 270
| 0.635725
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,849
|
ncm_content_meta.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_meta.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
namespace {
void ConvertPackageContentMetaHeaderToContentMetaHeader(ContentMetaHeader *dst, const PackagedContentMetaHeader &src) {
/* Set destination. */
*dst = {
.extended_header_size = src.extended_header_size,
.content_count = src.content_count,
.content_meta_count = src.content_meta_count,
.attributes = src.attributes,
.platform = src.platform,
};
}
void ConvertPackageContentMetaHeaderToInstallContentMetaHeader(InstallContentMetaHeader *dst, const PackagedContentMetaHeader &src) {
/* Set destination. */
static_assert(std::is_same<InstallContentMetaHeader, PackagedContentMetaHeader>::value);
std::memcpy(dst, std::addressof(src), sizeof(*dst));
}
void ConvertInstallContentMetaHeaderToContentMetaHeader(ContentMetaHeader *dst, const InstallContentMetaHeader &src) {
/* Set destination. */
*dst = {
.extended_header_size = src.extended_header_size,
.content_count = src.content_count,
.content_meta_count = src.content_meta_count,
.attributes = src.attributes,
.platform = src.platform,
};
}
Result FindDeltaIndex(s32 *out_index, const PatchMetaExtendedDataReader &reader, u32 src_version, u32 dst_version) {
/* Iterate over all deltas. */
auto header = reader.GetHeader();
for (s32 i = 0; i < static_cast<s32>(header->delta_count); i++) {
/* Check if the current delta matches the versions. */
auto delta = reader.GetPatchDeltaHeader(i);
if ((src_version == 0 || delta->delta.source_version == src_version) && delta->delta.destination_version == dst_version) {
*out_index = i;
R_SUCCEED();
}
}
/* We didn't find the delta. */
R_THROW(ncm::ResultDeltaNotFound());
}
s32 CountContentExceptForMeta(const PatchMetaExtendedDataReader &reader, s32 delta_index) {
/* Iterate over packaged content infos, checking for those which aren't metas. */
s32 count = 0;
auto delta = reader.GetPatchDeltaHeader(delta_index);
for (s32 i = 0; i < static_cast<s32>(delta->content_count); i++) {
if (reader.GetPatchDeltaPackagedContentInfo(delta_index, i)->GetType() != ContentType::Meta) {
count++;
}
}
return count;
}
}
size_t PackagedContentMetaReader::CalculateConvertInstallContentMetaSize() const {
/* Prepare the header. */
const auto *header = this->GetHeader();
if ((header->type == ContentMetaType::SystemUpdate && this->GetExtendedHeaderSize() > 0) || header->type == ContentMetaType::Delta) {
/* Newer SystemUpdates and Deltas contain extended data. */
return this->CalculateSizeImpl<InstallContentMetaHeader, InstallContentInfo>(header->extended_header_size, header->content_count + 1, header->content_meta_count, this->GetExtendedDataSize(), false);
} else if (header->type == ContentMetaType::Patch) {
/* Subtract the number of delta fragments for patches, include extended data. */
return this->CalculateSizeImpl<InstallContentMetaHeader, InstallContentInfo>(header->extended_header_size, header->content_count - this->CountDeltaFragments() + 1, header->content_meta_count, this->GetExtendedDataSize(), false);
}
/* No extended data or delta fragments by default. */
return this->CalculateSizeImpl<InstallContentMetaHeader, InstallContentInfo>(header->extended_header_size, header->content_count + 1, header->content_meta_count, 0, false);
}
size_t PackagedContentMetaReader::CountDeltaFragments() const {
size_t count = 0;
for (size_t i = 0; i < this->GetContentCount(); i++) {
if (this->GetContentInfo(i)->GetType() == ContentType::DeltaFragment) {
count++;
}
}
return count;
}
size_t PackagedContentMetaReader::CalculateConvertContentMetaSize() const {
const auto *header = this->GetHeader();
return this->CalculateSizeImpl<ContentMetaHeader, ContentInfo>(header->extended_header_size, header->content_count + 1, header->content_meta_count, 0, false);
}
void PackagedContentMetaReader::ConvertToInstallContentMeta(void *dst, size_t size, const InstallContentInfo &meta) {
/* Ensure we have enough space to convert. */
AMS_ABORT_UNLESS(size >= this->CalculateConvertInstallContentMetaSize());
/* Prepare for conversion. */
const auto *packaged_header = this->GetHeader();
uintptr_t dst_addr = reinterpret_cast<uintptr_t>(dst);
/* Convert the header. */
InstallContentMetaHeader header;
ConvertPackageContentMetaHeaderToInstallContentMetaHeader(std::addressof(header), *packaged_header);
header.content_count += 1;
/* Don't include deltas. */
if (packaged_header->type == ContentMetaType::Patch) {
header.content_count -= this->CountDeltaFragments();
}
/* Copy the header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(header), sizeof(header));
dst_addr += sizeof(header);
/* Copy the extended header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), reinterpret_cast<void *>(this->GetExtendedHeaderAddress()), packaged_header->extended_header_size);
dst_addr += packaged_header->extended_header_size;
/* Copy the top level meta. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(meta), sizeof(meta));
dst_addr += sizeof(meta);
/* Copy content infos. */
for (size_t i = 0; i < this->GetContentCount(); i++) {
const auto *packaged_content_info = this->GetContentInfo(i);
/* Don't copy any delta fragments. */
if (packaged_header->type == ContentMetaType::Patch) {
if (packaged_content_info->GetType() == ContentType::DeltaFragment) {
continue;
}
}
/* Create the install content info. */
InstallContentInfo install_content_info = InstallContentInfo::Make(*packaged_content_info, packaged_header->type);
/* Copy the info. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(install_content_info), sizeof(InstallContentInfo));
dst_addr += sizeof(InstallContentInfo);
}
/* Copy content meta infos. */
for (size_t i = 0; i < this->GetContentMetaCount(); i++) {
std::memcpy(reinterpret_cast<void *>(dst_addr), this->GetContentMetaInfo(i), sizeof(ContentMetaInfo));
dst_addr += sizeof(ContentMetaInfo);
}
}
Result PackagedContentMetaReader::ConvertToFragmentOnlyInstallContentMeta(void *dst, size_t size, const InstallContentInfo &meta, u32 source_version) {
/* Ensure that we have enough space. */
size_t required_size;
R_TRY(this->CalculateConvertFragmentOnlyInstallContentMetaSize(std::addressof(required_size), source_version));
AMS_ABORT_UNLESS(size >= required_size);
/* Find the delta index. */
PatchMetaExtendedDataReader reader(this->GetExtendedData(), this->GetExtendedDataSize());
s32 index;
R_TRY(FindDeltaIndex(std::addressof(index), reader, source_version, this->GetKey().version));
auto delta = reader.GetPatchDeltaHeader(index);
/* Prepare for conversion. */
const auto *packaged_header = this->GetHeader();
uintptr_t dst_addr = reinterpret_cast<uintptr_t>(dst);
/* Convert the header. */
InstallContentMetaHeader header;
ConvertPackageContentMetaHeaderToInstallContentMetaHeader(std::addressof(header), *packaged_header);
header.install_type = ContentInstallType::FragmentOnly;
/* Set the content count. */
auto fragment_count = CountContentExceptForMeta(reader, index);
header.content_count = static_cast<u16>(fragment_count) + 1;
/* Copy the header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(header), sizeof(header));
dst_addr += sizeof(header);
/* Copy the extended header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), reinterpret_cast<void *>(this->GetExtendedHeaderAddress()), packaged_header->extended_header_size);
dst_addr += packaged_header->extended_header_size;
/* Copy the top level meta. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(meta), sizeof(meta));
dst_addr += sizeof(meta);
s32 count = 0;
for (s32 i = 0; i < static_cast<s32>(delta->content_count); i++) {
auto packaged_content_info = reader.GetPatchDeltaPackagedContentInfo(index, i);
if (packaged_content_info->GetType() != ContentType::Meta) {
/* Create the install content info. */
InstallContentInfo install_content_info = InstallContentInfo::Make(*packaged_content_info, packaged_header->type);
/* Copy the info. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(install_content_info), sizeof(InstallContentInfo));
dst_addr += sizeof(InstallContentInfo);
/* Increment the count. */
count++;
}
}
/* Assert that we copied the right number of infos. */
AMS_ASSERT(count == fragment_count);
R_SUCCEED();
}
Result PackagedContentMetaReader::CalculateConvertFragmentOnlyInstallContentMetaSize(size_t *out_size, u32 source_version) const {
/* Find the delta index. */
PatchMetaExtendedDataReader reader(this->GetExtendedData(), this->GetExtendedDataSize());
s32 index;
R_TRY(FindDeltaIndex(std::addressof(index), reader, source_version, this->GetKey().version));
/* Get the fragment count. */
const auto fragment_count = CountContentExceptForMeta(reader, index);
/* Recalculate. */
*out_size = this->CalculateConvertFragmentOnlyInstallContentMetaSize(fragment_count);
R_SUCCEED();
}
void PackagedContentMetaReader::ConvertToContentMeta(void *dst, size_t size, const ContentInfo &meta) {
/* Ensure we have enough space to convert. */
AMS_ABORT_UNLESS(size >= this->CalculateConvertContentMetaSize());
/* Prepare for conversion. */
const auto *packaged_header = this->GetHeader();
uintptr_t dst_addr = reinterpret_cast<uintptr_t>(dst);
/* Convert the header. */
ContentMetaHeader header;
ConvertPackageContentMetaHeaderToContentMetaHeader(std::addressof(header), *packaged_header);
header.content_count += 1;
/* Don't include deltas. */
if (packaged_header->type == ContentMetaType::Patch) {
header.content_count -= this->CountDeltaFragments();
}
/* Copy the header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(header), sizeof(header));
dst_addr += sizeof(header);
/* Copy the extended header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), reinterpret_cast<void *>(this->GetExtendedHeaderAddress()), packaged_header->extended_header_size);
dst_addr += packaged_header->extended_header_size;
/* Copy the top level meta. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(meta), sizeof(meta));
dst_addr += sizeof(meta);
/* Copy content infos. */
for (size_t i = 0; i < this->GetContentCount(); i++) {
/* Don't copy any delta fragments. */
if (packaged_header->type == ContentMetaType::Patch) {
if (this->GetContentInfo(i)->GetType() == ContentType::DeltaFragment) {
continue;
}
}
/* Copy the current info. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(this->GetContentInfo(i)->info), sizeof(ContentInfo));
dst_addr += sizeof(ContentInfo);
}
/* Copy content meta infos. */
for (size_t i = 0; i < this->GetContentMetaCount(); i++) {
std::memcpy(reinterpret_cast<void *>(dst_addr), this->GetContentMetaInfo(i), sizeof(ContentMetaInfo));
dst_addr += sizeof(ContentMetaInfo);
}
}
size_t InstallContentMetaReader::CalculateConvertSize() const {
return CalculateSizeImpl<ContentMetaHeader, ContentInfo>(this->GetExtendedHeaderSize(), this->GetContentCount(), this->GetContentMetaCount(), this->GetExtendedDataSize(), false);
}
void InstallContentMetaReader::ConvertToContentMeta(void *dst, size_t size) const {
/* Ensure we have enough space to convert. */
AMS_ABORT_UNLESS(size >= this->CalculateConvertSize());
/* Prepare for conversion. */
const auto *install_header = this->GetHeader();
uintptr_t dst_addr = reinterpret_cast<uintptr_t>(dst);
/* Convert the header. */
ContentMetaHeader header;
ConvertInstallContentMetaHeaderToContentMetaHeader(std::addressof(header), *install_header);
/* Copy the header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(header), sizeof(header));
dst_addr += sizeof(header);
/* Copy the extended header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), reinterpret_cast<void *>(this->GetExtendedHeaderAddress()), install_header->extended_header_size);
dst_addr += install_header->extended_header_size;
/* Copy content infos. */
for (size_t i = 0; i < this->GetContentCount(); i++) {
/* Copy the current info. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(this->GetContentInfo(i)->info), sizeof(ContentInfo));
dst_addr += sizeof(ContentInfo);
}
/* Copy content meta infos. */
for (size_t i = 0; i < this->GetContentMetaCount(); i++) {
std::memcpy(reinterpret_cast<void *>(dst_addr), this->GetContentMetaInfo(i), sizeof(ContentMetaInfo));
dst_addr += sizeof(ContentMetaInfo);
}
}
Result MetaConverter::CountContentExceptForMeta(s32 *out, PatchMetaExtendedDataAccessor *accessor, const PatchDeltaHeader &header, s32 delta_index) {
/* Get the count. */
s32 count = 0;
for (auto i = 0; i < static_cast<int>(header.content_count); ++i) {
/* Get the delta content info. */
PackagedContentInfo content_info;
R_TRY(accessor->GetPatchDeltaContentInfo(std::addressof(content_info), delta_index, i));
if (content_info.GetType() != ContentType::Meta) {
++count;
}
}
*out = count;
R_SUCCEED();
}
Result MetaConverter::FindDeltaIndex(s32 *out, PatchMetaExtendedDataAccessor *accessor, u32 source_version, u32 destination_version) {
/* Get the header. */
PatchMetaExtendedDataHeader header;
header.delta_count = 0;
R_TRY(accessor->GetHeader(std::addressof(header)));
/* Iterate over all deltas. */
for (s32 i = 0; i < static_cast<s32>(header.delta_count); i++) {
/* Get the current patch delta header. */
PatchDeltaHeader delta_header;
R_TRY(accessor->GetPatchDeltaHeader(std::addressof(delta_header), i));
/* Check if the current delta matches the versions. */
if ((source_version == 0 || delta_header.delta.source_version == source_version) && delta_header.delta.destination_version == destination_version) {
*out = i;
R_SUCCEED();
}
}
/* We didn't find the delta. */
R_THROW(ncm::ResultDeltaNotFound());
}
Result MetaConverter::GetFragmentOnlyInstallContentMeta(AutoBuffer *out, const InstallContentInfo &meta, const PackagedContentMetaReader &reader, PatchMetaExtendedDataAccessor *accessor, u32 source_version) {
/* Find the appropriate delta index. */
s32 delta_index = 0;
R_TRY(FindDeltaIndex(std::addressof(delta_index), accessor, source_version, reader.GetHeader()->version));
/* Get the delta header. */
PatchDeltaHeader delta_header;
R_TRY(accessor->GetPatchDeltaHeader(std::addressof(delta_header), delta_index));
/* Count content except for meta. */
s32 fragment_count = 0;
R_TRY(CountContentExceptForMeta(std::addressof(fragment_count), accessor, delta_header, delta_index));
/* Determine the required size. */
const size_t meta_size = reader.CalculateConvertFragmentOnlyInstallContentMetaSize(fragment_count);
/* Initialize the out buffer. */
R_TRY(out->Initialize(meta_size));
/* Prepare for conversion. */
const auto *packaged_header = reader.GetHeader();
uintptr_t dst_addr = reinterpret_cast<uintptr_t>(out->Get());
/* Convert the header. */
InstallContentMetaHeader header;
ConvertPackageContentMetaHeaderToInstallContentMetaHeader(std::addressof(header), *packaged_header);
header.install_type = ContentInstallType::FragmentOnly;
/* Set the content count. */
header.content_count = static_cast<u16>(fragment_count) + 1;
/* Copy the header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(header), sizeof(header));
dst_addr += sizeof(header);
/* Copy the extended header. */
std::memcpy(reinterpret_cast<void *>(dst_addr), reader.GetExtendedHeader<void>(), packaged_header->extended_header_size);
dst_addr += packaged_header->extended_header_size;
/* Copy the top level meta. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(meta), sizeof(meta));
dst_addr += sizeof(meta);
s32 count = 0;
for (s32 i = 0; i < static_cast<s32>(delta_header.content_count); i++) {
/* Get the delta content info. */
PackagedContentInfo content_info;
R_TRY(accessor->GetPatchDeltaContentInfo(std::addressof(content_info), delta_index, i));
if (content_info.GetType() != ContentType::Meta) {
/* Create the install content info. */
InstallContentInfo install_content_info = InstallContentInfo::Make(content_info, packaged_header->type);
/* Copy the info. */
std::memcpy(reinterpret_cast<void *>(dst_addr), std::addressof(install_content_info), sizeof(InstallContentInfo));
dst_addr += sizeof(InstallContentInfo);
/* Increment the count. */
count++;
}
}
/* Assert that we copied the right number of infos. */
AMS_ASSERT(count == fragment_count);
R_SUCCEED();
}
}
| 20,063
|
C++
|
.cpp
| 352
| 46.5625
| 240
| 0.635344
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,850
|
ncm_integrated_content_storage_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_integrated_content_storage_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
Result IntegratedContentStorageImpl::GeneratePlaceHolderId(sf::Out<PlaceHolderId> out) {
AMS_UNUSED(out);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::CreatePlaceHolder(PlaceHolderId placeholder_id, ContentId content_id, s64 size) {
AMS_UNUSED(placeholder_id, content_id, size);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::DeletePlaceHolder(PlaceHolderId placeholder_id) {
AMS_UNUSED(placeholder_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::HasPlaceHolder(sf::Out<bool> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(placeholder_id);
/* Integrated storages cannot have placeholders. */
*out = false;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::WritePlaceHolder(PlaceHolderId placeholder_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(placeholder_id, offset, data);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::Register(PlaceHolderId placeholder_id, ContentId content_id) {
AMS_UNUSED(placeholder_id, content_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::Delete(ContentId content_id) {
AMS_UNUSED(content_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::Has(sf::Out<bool> out, ContentId content_id) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* If we don't locate the content, set the output to false. */
*out = false;
ON_RESULT_INCLUDED(ncm::ResultContentNotFound) { *out = false; };
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
R_TRY(data.interface->Has(out, content_id));
/* If it doesn't, continue on. */
R_UNLESS(*out, ncm::ResultContentNotFound());
/* If it does, we're done looking. */
R_SUCCEED();
}));
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetPath(sf::Out<Path> out, ContentId content_id) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentNotFound());
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), content_id));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentNotFound());
/* If it does, get the path. */
R_RETURN(data.interface->GetPath(out, content_id));
}));
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetPlaceHolderPath(sf::Out<Path> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::CleanupAllPlaceHolder() {
R_SUCCEED();
}
Result IntegratedContentStorageImpl::ListPlaceHolder(sf::Out<s32> out_count, const sf::OutArray<PlaceHolderId> &out_buf) {
AMS_UNUSED(out_buf);
*out_count = 0;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetContentCount(sf::Out<s32> out_count) {
*out_count = 0;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::ListContentId(sf::Out<s32> out_count, const sf::OutArray<ContentId> &out_buf, s32 offset) {
AMS_UNUSED(out_buf, offset);
*out_count = 0;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetSizeFromContentId(sf::Out<s64> out_size, ContentId content_id) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentNotFound());
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), content_id));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentNotFound());
/* If it does, get the size. */
R_RETURN(data.interface->GetSizeFromContentId(out_size, content_id));
}));
R_SUCCEED();
}
Result IntegratedContentStorageImpl::DisableForcibly() {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
m_disabled = true;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::RevertToPlaceHolder(PlaceHolderId placeholder_id, ContentId old_content_id, ContentId new_content_id) {
AMS_UNUSED(placeholder_id, old_content_id, new_content_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::SetPlaceHolderSize(PlaceHolderId placeholder_id, s64 size) {
AMS_UNUSED(placeholder_id, size);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::ReadContentIdFile(const sf::OutBuffer &buf, ContentId content_id, s64 offset) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentNotFound());
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), content_id));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentNotFound());
/* If it does, read the file. */
R_RETURN(data.interface->ReadContentIdFile(buf, content_id, offset));
}));
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
/* Obtain the regular rights id for the placeholder id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromPlaceHolderIdDeprecated2(std::addressof(rights_id), placeholder_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
R_RETURN(this->GetRightsIdFromPlaceHolderId(out_rights_id, placeholder_id, fs::ContentAttributes_None));
}
Result IntegratedContentStorageImpl::GetRightsIdFromPlaceHolderId(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, attr);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::GetRightsIdFromContentIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, ContentId content_id) {
/* Obtain the regular rights id for the content id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromContentIdDeprecated2(std::addressof(rights_id), content_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetRightsIdFromContentIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id) {
R_RETURN(this->GetRightsIdFromContentId(out_rights_id, content_id, fs::ContentAttributes_None));
}
Result IntegratedContentStorageImpl::GetRightsIdFromContentId(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id, fs::ContentAttributes attr) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentNotFound());
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), content_id));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentNotFound());
/* If it does, read the file. */
R_RETURN(data.interface->GetRightsIdFromContentId(out_rights_id, content_id, attr));
}));
R_SUCCEED();
}
Result IntegratedContentStorageImpl::WriteContentForDebug(ContentId content_id, s64 offset, const sf::InBuffer &data) {
AMS_UNUSED(content_id, offset, data);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::GetFreeSpaceSize(sf::Out<s64> out_size) {
out_size.SetValue(0);
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetTotalSpaceSize(sf::Out<s64> out_size) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Determine the total size. */
s64 total_size = 0;
R_TRY(m_list.ForAll([&](const auto &data) {
/* Get the current size. */
s64 cur_size;
R_TRY(data.interface->GetTotalSpaceSize(std::addressof(cur_size)));
/* Add to the total. */
total_size += cur_size;
R_SUCCEED();
}));
*out_size = total_size;
R_SUCCEED();
}
Result IntegratedContentStorageImpl::FlushPlaceHolder() {
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::GetSizeFromPlaceHolderId(sf::Out<s64> out, PlaceHolderId placeholder_id) {
AMS_UNUSED(out, placeholder_id);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::RepairInvalidFileAttribute() {
R_SUCCEED();
}
Result IntegratedContentStorageImpl::GetRightsIdFromPlaceHolderIdWithCache(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, ContentId cache_content_id, fs::ContentAttributes attr) {
AMS_UNUSED(out_rights_id, placeholder_id, cache_content_id, attr);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::RegisterPath(const ContentId &content_id, const Path &path) {
AMS_UNUSED(content_id, path);
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::ClearRegisteredPath() {
R_THROW(ncm::ResultInvalidOperation());
}
Result IntegratedContentStorageImpl::GetProgramId(sf::Out<ncm::ProgramId> out, ContentId content_id, fs::ContentAttributes attr) {
/* Lock ourselves. */
std::scoped_lock lk(m_mutex);
/* Check that we're enabled. */
R_TRY(this->EnsureEnabled());
/* Check that our list has interfaces to check. */
R_UNLESS(m_list.GetCount() > 0, ncm::ResultContentNotFound());
/* Check each interface in turn. */
R_TRY(m_list.TryEach([&](const auto &data) {
/* Check if the current interface has it. */
bool has;
R_TRY(data.interface->Has(std::addressof(has), content_id));
/* If it doesn't, continue on. */
R_UNLESS(has, ncm::ResultContentNotFound());
/* If it does, read the file. */
R_RETURN(data.interface->GetProgramId(out, content_id, attr));
}));
R_SUCCEED();
}
}
| 12,941
|
C++
|
.cpp
| 270
| 39.433333
| 204
| 0.649662
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,851
|
ncm_fs_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_fs_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_fs_utils.hpp"
namespace ams::ncm::impl {
namespace {
constinit std::atomic<u32> g_mount_name_count;
}
bool PathView::HasPrefix(util::string_view prefix) const {
return m_path.compare(0, prefix.length(), prefix) == 0;
}
bool PathView::HasSuffix(util::string_view suffix) const {
return m_path.compare(m_path.length() - suffix.length(), suffix.length(), suffix) == 0;
}
util::string_view PathView::GetFileName() const {
auto pos = m_path.find_last_of("/");
return pos != util::string_view::npos ? m_path.substr(pos + 1) : m_path;
}
MountName CreateUniqueMountName() {
MountName name = {};
util::SNPrintf(name.str, sizeof(name.str), "@ncm%08x", g_mount_name_count.fetch_add(1));
return name;
}
RootDirectoryPath GetRootDirectoryPath(const MountName &mount_name) {
RootDirectoryPath path = {};
util::SNPrintf(path.str, sizeof(path.str), "%s:/", mount_name.str);
return path;
}
Result CopyFile(const char *dst_path, const char *src_path) {
fs::FileHandle src_file, dst_file;
/* Open the source file and get its size. */
R_TRY(fs::OpenFile(std::addressof(src_file), src_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(src_file); };
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), src_file));
/* Create the destination file. */
R_TRY(fs::CreateFile(dst_path, file_size));
/* Open the destination file. */
R_TRY(fs::OpenFile(std::addressof(dst_file), dst_path, fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(dst_file); };
/* Allocate a buffer with which to copy. */
constexpr size_t BufferSize = 4_KB;
AutoBuffer buffer;
R_TRY(buffer.Initialize(BufferSize));
/* Repeatedly read until we've copied all the data. */
s64 offset = 0;
while (offset < file_size) {
const size_t read_size = std::min(static_cast<size_t>(file_size - offset), buffer.GetSize());
R_TRY(fs::ReadFile(src_file, offset, buffer.Get(), read_size));
R_TRY(fs::WriteFile(dst_file, offset, buffer.Get(), read_size, fs::WriteOption::None));
offset += read_size;
}
/* Flush the destination file. */
R_TRY(fs::FlushFile(dst_file));
R_SUCCEED();
}
}
| 3,098
|
C++
|
.cpp
| 70
| 37.514286
| 105
| 0.642952
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,852
|
ncm_storage_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_storage_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
Result SelectDownloadableStorage(StorageId *out_storage_id, StorageId storage_id, s64 required_size) {
auto list = GetStorageList(storage_id);
for (s32 i = 0; i < list.Count(); i++) {
auto candidate = list[i];
/* Open the content meta database. NOTE: This is unused. */
ContentMetaDatabase content_meta_database;
if (R_FAILED(ncm::OpenContentMetaDatabase(std::addressof(content_meta_database), candidate))) {
continue;
}
/* Open the content storage. */
ContentStorage content_storage;
if (R_FAILED(ncm::OpenContentStorage(std::addressof(content_storage), candidate))) {
continue;
}
/* Get the free space on this storage. */
s64 free_space_size;
R_TRY(content_storage.GetFreeSpaceSize(std::addressof(free_space_size)));
/* There must be more free space than is required. */
if (free_space_size <= required_size) {
continue;
}
/* Output the storage id. */
*out_storage_id = storage_id;
R_SUCCEED();
}
R_THROW(ncm::ResultNotEnoughInstallSpace());
}
Result SelectPatchStorage(StorageId *out_storage_id, StorageId storage_id, PatchId patch_id) {
auto list = GetStorageList(storage_id);
u32 version = 0;
*out_storage_id = storage_id;
for (s32 i = 0; i < list.Count(); i++) {
auto candidate = list[i];
/* Open the content meta database. */
ContentMetaDatabase content_meta_database;
if (R_FAILED(ncm::OpenContentMetaDatabase(std::addressof(content_meta_database), candidate))) {
continue;
}
/* Get the latest key. */
ContentMetaKey key;
R_TRY_CATCH(content_meta_database.GetLatest(std::addressof(key), patch_id.value)) {
R_CATCH(ncm::ResultContentMetaNotFound) { continue; }
} R_END_TRY_CATCH;
if (key.version > version) {
version = key.version;
*out_storage_id = candidate;
}
}
R_SUCCEED();
}
const char *GetStorageIdString(StorageId storage_id) {
switch (storage_id) {
case StorageId::None: return "None";
case StorageId::Host: return "Host";
case StorageId::GameCard: return "GameCard";
case StorageId::BuiltInSystem: return "BuiltInSystem";
case StorageId::BuiltInUser: return "BuiltInUser";
default: return "(unknown)";
}
}
const char *GetStorageIdStringForPlayReport(StorageId storage_id) {
switch (storage_id) {
case StorageId::None: return "None";
case StorageId::Host: return "Host";
case StorageId::Card: return "Card";
case StorageId::BuildInSystem: return "BuildInSystem";
case StorageId::BuildInUser: return "BuildInUser";
default: return "(unknown)";
}
}
}
| 3,911
|
C++
|
.cpp
| 88
| 34.590909
| 107
| 0.593011
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,853
|
ncm_content_info_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_info_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
namespace {
constexpr inline s64 EncryptionMetadataSize = 16_KB;
constexpr inline s64 ConcatenationFileSizeMax = 4_GB;
constexpr s64 CalculateAdditionalContentSize(s64 file_size, s64 cluster_size) {
/* Account for the encryption header. */
s64 size = EncryptionMetadataSize;
/* Account for the file size splitting costs. */
size += ((file_size / ConcatenationFileSizeMax) + 1) * cluster_size;
/* Account for various overhead costs. */
size += cluster_size * 3;
return size;
}
template<typename Handler>
Result ForEachContentInfo(const ContentMetaKey &key, ncm::ContentMetaDatabase *db, Handler handler) {
constexpr s32 MaxPerIteration = 0x10;
ContentInfo info_list[MaxPerIteration];
s32 offset = 0;
while (true) {
/* List the content infos. */
s32 count;
R_TRY(db->ListContentInfo(std::addressof(count), info_list, MaxPerIteration, key, offset));
/* Handle all that we listed. */
for (s32 i = 0; i < count; i++) {
bool done = false;
R_TRY(handler(std::addressof(done), info_list[i]));
if (done) {
break;
}
}
/* Check if we're done. */
if (count != MaxPerIteration) {
break;
}
offset += count;
}
R_SUCCEED();
}
}
s64 CalculateRequiredSize(s64 file_size, s64 cluster_size) {
return file_size + CalculateAdditionalContentSize(file_size, cluster_size);
}
s64 CalculateRequiredSizeForExtension(s64 file_size, s64 cluster_size) {
return file_size + ((file_size / ConcatenationFileSizeMax) + 1) * cluster_size;
}
Result EstimateRequiredSize(s64 *out_size, const ContentMetaKey &key, ncm::ContentMetaDatabase *db) {
s64 size = 0;
R_TRY(ForEachContentInfo(key, db, [&size](bool *out_done, const ContentInfo &info) -> Result {
size += CalculateRequiredSize(info.GetSize(), MaxClusterSize);
*out_done = false;
R_SUCCEED();
}));
*out_size = size;
R_SUCCEED();
}
}
| 3,076
|
C++
|
.cpp
| 72
| 32.666667
| 109
| 0.599799
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,854
|
ncm_package_system_update_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_package_system_update_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
PackageSystemUpdateTask::~PackageSystemUpdateTask() {
if (m_context_path.GetLength() > 0) {
fs::DeleteFile(m_context_path);
}
this->Inactivate();
}
void PackageSystemUpdateTask::Inactivate() {
if (m_gamecard_content_meta_database_active) {
InactivateContentMetaDatabase(StorageId::GameCard);
m_gamecard_content_meta_database_active = false;
}
}
Result PackageSystemUpdateTask::Initialize(const char *package_root, const char *context_path, void *buffer, size_t buffer_size, bool requires_exfat_driver, FirmwareVariationId firmware_variation_id) {
/* Set the firmware variation id. */
this->SetFirmwareVariationId(firmware_variation_id);
/* Activate the game card content meta database. */
R_TRY(ActivateContentMetaDatabase(StorageId::GameCard));
m_gamecard_content_meta_database_active = true;
auto meta_db_guard = SCOPE_GUARD { this->Inactivate(); };
/* Open the game card content meta database. */
OpenContentMetaDatabase(std::addressof(m_package_db), StorageId::GameCard);
ContentMetaDatabaseBuilder builder(std::addressof(m_package_db));
/* Cleanup and build the content meta database. */
R_TRY(builder.Cleanup());
R_TRY(builder.BuildFromPackage(package_root));
/* Create a new context file. */
fs::DeleteFile(context_path);
R_TRY(FileInstallTaskData::Create(context_path, GameCardMaxContentMetaCount));
auto context_guard = SCOPE_GUARD { fs::DeleteFile(context_path); };
/* Initialize data. */
R_TRY(m_data.Initialize(context_path));
/* Initialize PackageInstallTaskBase. */
u32 config = !requires_exfat_driver ? InstallConfig_SystemUpdate : InstallConfig_SystemUpdate | InstallConfig_RequiresExFatDriver;
R_TRY(PackageInstallTaskBase::Initialize(package_root, buffer, buffer_size, StorageId::BuiltInSystem, std::addressof(m_data), config));
/* Cancel guards. */
context_guard.Cancel();
meta_db_guard.Cancel();
/* Set the context path. */
m_context_path.Assign(context_path);
R_SUCCEED();
}
util::optional<ContentMetaKey> PackageSystemUpdateTask::GetSystemUpdateMetaKey() {
StorageContentMetaKey storage_keys[0x10];
s32 ofs = 0;
s32 count = 0;
do {
/* List content meta keys. */
if (R_FAILED(this->ListContentMetaKey(std::addressof(count), storage_keys, util::size(storage_keys), ofs, ListContentMetaKeyFilter::All))) {
break;
}
/* Add listed keys to the offset. */
ofs += count;
/* Check if any of these keys are for a SystemUpdate. */
for (s32 i = 0; i < count; i++) {
const ContentMetaKey &key = storage_keys[i].key;
if (key.type == ContentMetaType::SystemUpdate) {
return key;
}
}
} while (count > 0);
return util::nullopt;
}
Result PackageSystemUpdateTask::GetInstallContentMetaInfo(InstallContentMetaInfo *out, const ContentMetaKey &key) {
/* Get the content info for the key. */
ContentInfo info;
R_TRY(this->GetContentInfoOfContentMeta(std::addressof(info), key));
/* Create a new install content meta info. */
*out = InstallContentMetaInfo::MakeUnverifiable(info.GetId(), info.GetSize(), key);
R_SUCCEED();
}
Result PackageSystemUpdateTask::PrepareInstallContentMetaData() {
/* Obtain a SystemUpdate key. */
ContentMetaKey key;
auto list_count = m_package_db.ListContentMeta(std::addressof(key), 1, ContentMetaType::SystemUpdate);
R_UNLESS(list_count.written > 0, ncm::ResultSystemUpdateNotFoundInPackage());
/* Get the content info for the key. */
ContentInfo info;
R_TRY(this->GetContentInfoOfContentMeta(std::addressof(info), key));
/* Prepare the content meta. */
R_RETURN(this->PrepareContentMeta(InstallContentMetaInfo::MakeUnverifiable(info.GetId(), info.GetSize(), key), key, util::nullopt));
}
Result PackageSystemUpdateTask::PrepareDependency() {
R_RETURN(this->PrepareSystemUpdateDependency());
}
Result PackageSystemUpdateTask::GetContentInfoOfContentMeta(ContentInfo *out, const ContentMetaKey &key) {
s32 ofs = 0;
while (true) {
/* List content infos. */
s32 count;
ContentInfo info;
R_TRY(m_package_db.ListContentInfo(std::addressof(count), std::addressof(info), 1, key, ofs++));
/* No content infos left to list. */
if (count == 0) {
break;
}
/* Check if the info is for meta content. */
if (info.GetType() == ContentType::Meta) {
*out = info;
R_SUCCEED();
}
}
/* Not found. */
R_THROW(ncm::ResultContentInfoNotFound());
}
}
| 5,788
|
C++
|
.cpp
| 122
| 38.54918
| 205
| 0.645201
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,855
|
ncm_content_meta_database_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_meta_database_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_content_meta_database_impl.hpp"
namespace ams::ncm {
Result ContentMetaDatabaseImpl::GetContentInfoImpl(ContentInfo *out, const ContentMetaKey &key, ContentType type, util::optional<u8> id_offset) const {
R_TRY(this->EnsureEnabled());
/* Find the meta key. */
const auto it = m_kvs->lower_bound(key);
R_UNLESS(it != m_kvs->end(), ncm::ResultContentMetaNotFound());
R_UNLESS(it->GetKey().id == key.id, ncm::ResultContentMetaNotFound());
const auto found_key = it->GetKey();
/* Create a reader for this content meta. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, found_key));
ContentMetaReader reader(meta, meta_size);
/* Find the content info. */
const ContentInfo *content_info = nullptr;
if (id_offset) {
content_info = reader.GetContentInfo(type, *id_offset);
} else {
content_info = reader.GetContentInfo(type);
}
R_UNLESS(content_info != nullptr, ncm::ResultContentNotFound());
/* Save output. */
*out = *content_info;
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::Set(const ContentMetaKey &key, const sf::InBuffer &value) {
R_TRY(this->EnsureEnabled());
R_RETURN(m_kvs->Set(key, value.GetPointer(), value.GetSize()));
}
Result ContentMetaDatabaseImpl::Get(sf::Out<u64> out_size, const ContentMetaKey &key, const sf::OutBuffer &out_value) {
R_TRY(this->EnsureEnabled());
/* Get the entry from our key-value store. */
size_t size;
R_TRY_CATCH(m_kvs->Get(std::addressof(size), out_value.GetPointer(), out_value.GetSize(), key)) {
R_CONVERT(kvdb::ResultKeyNotFound, ncm::ResultContentMetaNotFound())
} R_END_TRY_CATCH;
out_size.SetValue(size);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::Remove(const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
R_TRY_CATCH(m_kvs->Remove(key)) {
R_CONVERT(kvdb::ResultKeyNotFound, ncm::ResultContentMetaNotFound())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetContentIdByType(sf::Out<ContentId> out_content_id, const ContentMetaKey &key, ContentType type) {
R_RETURN(this->GetContentIdImpl(out_content_id.GetPointer(), key, type, util::nullopt));
}
Result ContentMetaDatabaseImpl::ListContentInfo(sf::Out<s32> out_count, const sf::OutArray<ContentInfo> &out_info, const ContentMetaKey &key, s32 offset) {
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
/* Obtain the content meta for the given key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Read content infos from the given offset up to the given count. */
size_t count;
for (count = 0; count < out_info.GetSize() && count + offset < reader.GetContentCount(); count++) {
out_info[count] = *reader.GetContentInfo(offset + count);
}
out_count.SetValue(count);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::List(sf::Out<s32> out_entries_total, sf::Out<s32> out_entries_written, const sf::OutArray<ContentMetaKey> &out_info, ContentMetaType meta_type, ApplicationId application_id, u64 min, u64 max, ContentInstallType install_type) {
R_TRY(this->EnsureEnabled());
size_t entries_total = 0;
size_t entries_written = 0;
/* Iterate over all entries. */
for (auto &entry : *m_kvs) {
const ContentMetaKey key = entry.GetKey();
/* Check if this entry matches the given filters. */
if (!((meta_type == ContentMetaType::Unknown || key.type == meta_type) && (min <= key.id && key.id <= max) && (install_type == ContentInstallType::Unknown || key.install_type == install_type))) {
continue;
}
/* If application id is present, check if it matches the filter. */
if (application_id != InvalidApplicationId) {
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Ensure application id matches, if present. */
if (const auto entry_application_id = reader.GetApplicationId(key); entry_application_id && application_id != *entry_application_id) {
continue;
}
}
/* Write the entry to the output buffer. */
if (entries_written < out_info.GetSize()) {
out_info[entries_written++] = key;
}
entries_total++;
}
out_entries_total.SetValue(entries_total);
out_entries_written.SetValue(entries_written);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetLatestContentMetaKey(sf::Out<ContentMetaKey> out_key, u64 id) {
R_TRY(this->EnsureEnabled());
util::optional<ContentMetaKey> found_key = util::nullopt;
/* Find the last key with the desired program id. */
for (auto entry = m_kvs->lower_bound(ContentMetaKey::MakeUnknownType(id, 0)); entry != m_kvs->end(); entry++) {
/* No further entries will match the program id, discontinue. */
if (entry->GetKey().id != id) {
break;
}
/* We are only interested in keys with the Full content install type. */
if (entry->GetKey().install_type == ContentInstallType::Full) {
found_key = entry->GetKey();
}
}
/* Check if the key is absent. */
R_UNLESS(found_key, ncm::ResultContentMetaNotFound());
out_key.SetValue(*found_key);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::ListApplication(sf::Out<s32> out_entries_total, sf::Out<s32> out_entries_written, const sf::OutArray<ApplicationContentMetaKey> &out_keys, ContentMetaType type) {
R_TRY(this->EnsureEnabled());
size_t entries_total = 0;
size_t entries_written = 0;
/* Iterate over all entries. */
for (auto &entry : *m_kvs) {
const ContentMetaKey key = entry.GetKey();
/* Check if this entry matches the given filters. */
if (!(type == ContentMetaType::Unknown || key.type == type)) {
continue;
}
/* Check if the entry has an application id. */
ContentMetaReader reader(entry.GetValuePointer(), entry.GetValueSize());
if (const auto entry_application_id = reader.GetApplicationId(key); entry_application_id) {
/* Write the entry to the output buffer. */
if (entries_written < out_keys.GetSize()) {
out_keys[entries_written++] = { key, *entry_application_id };
}
entries_total++;
}
}
out_entries_total.SetValue(entries_total);
out_entries_written.SetValue(entries_written);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::Has(sf::Out<bool> out, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
*out = false;
/* Check if key is present. */
size_t size;
R_TRY_CATCH(m_kvs->GetValueSize(&size, key)) {
R_CONVERT(kvdb::ResultKeyNotFound, ResultSuccess());
} R_END_TRY_CATCH;
*out = true;
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::HasAll(sf::Out<bool> out, const sf::InArray<ContentMetaKey> &keys) {
R_TRY(this->EnsureEnabled());
*out = false;
/* Check if keys are present. */
for (size_t i = 0; i < keys.GetSize(); i++) {
/* Check if we have the current key. */
bool has;
R_TRY(this->Has(std::addressof(has), keys[i]));
/* If we don't, then we can early return because we don't have all. */
R_SUCCEED_IF(!has);
}
*out = true;
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetSize(sf::Out<u64> out_size, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Determine the content meta size for the key. */
size_t size;
R_TRY(this->GetContentMetaSize(&size, key));
out_size.SetValue(size);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetRequiredSystemVersion(sf::Out<u32> out_version, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Only applications and patches have a required system version. */
R_UNLESS(key.type == ContentMetaType::Application || key.type == ContentMetaType::Patch, ncm::ResultInvalidContentMetaKey());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Obtain the required system version. */
switch (key.type) {
case ContentMetaType::Application:
out_version.SetValue(reader.GetExtendedHeader<ApplicationMetaExtendedHeader>()->required_system_version);
break;
case ContentMetaType::Patch:
out_version.SetValue(reader.GetExtendedHeader<PatchMetaExtendedHeader>()->required_system_version);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetPatchContentMetaId(sf::Out<u64> out_patch_id, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Only applications can have patches. */
R_UNLESS(key.type == ContentMetaType::Application || key.type == ContentMetaType::AddOnContent, ncm::ResultInvalidContentMetaKey());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Obtain the patch id. */
switch (key.type) {
case ContentMetaType::Application:
out_patch_id.SetValue(reader.GetExtendedHeader<ApplicationMetaExtendedHeader>()->patch_id.value);
break;
case ContentMetaType::AddOnContent:
R_UNLESS(reader.GetExtendedHeaderSize() == sizeof(AddOnContentMetaExtendedHeader), ncm::ResultInvalidAddOnContentMetaExtendedHeader());
out_patch_id.SetValue(reader.GetExtendedHeader<AddOnContentMetaExtendedHeader>()->data_patch_id.value);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::DisableForcibly() {
m_disabled = true;
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::LookupOrphanContent(const sf::OutArray<bool> &out_orphaned, const sf::InArray<ContentId> &content_ids) {
R_TRY(this->EnsureEnabled());
R_UNLESS(out_orphaned.GetSize() >= content_ids.GetSize(), ncm::ResultBufferInsufficient());
/* Default to orphaned for all content ids. */
for (size_t i = 0; i < out_orphaned.GetSize(); i++) {
out_orphaned[i] = true;
}
auto IsOrphanedContent = [](const sf::InArray<ContentId> &list, const ncm::ContentId &id) ALWAYS_INLINE_LAMBDA -> util::optional<size_t> {
/* Check if any input content ids match our found content id. */
for (size_t i = 0; i < list.GetSize(); i++) {
if (list[i] == id) {
return util::make_optional(i);
}
}
return util::nullopt;
};
/* Iterate over all entries. */
for (auto &entry : *m_kvs) {
ContentMetaReader reader(entry.GetValuePointer(), entry.GetValueSize());
/* Check if any of this entry's content infos matches one of the content ids for lookup. */
/* If they do, then the content id isn't orphaned. */
for (size_t i = 0; i < reader.GetContentCount(); i++) {
if (auto found = IsOrphanedContent(content_ids, reader.GetContentInfo(i)->GetId()); found) {
out_orphaned[*found] = false;
}
}
}
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::Commit() {
R_TRY(this->EnsureEnabled());
/* Save and commit. */
R_TRY(m_kvs->Save());
R_RETURN(fs::CommitSaveData(m_mount_name));
}
Result ContentMetaDatabaseImpl::HasContent(sf::Out<bool> out, const ContentMetaKey &key, const ContentId &content_id) {
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Optimistically suppose that we will find the content. */
out.SetValue(true);
/* Check if any content infos contain a matching id. */
for (size_t i = 0; i < reader.GetContentCount(); i++) {
R_SUCCEED_IF(content_id == reader.GetContentInfo(i)->GetId());
}
/* We didn't find a content info. */
out.SetValue(false);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::ListContentMetaInfo(sf::Out<s32> out_entries_written, const sf::OutArray<ContentMetaInfo> &out_meta_info, const ContentMetaKey &key, s32 offset) {
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Read content meta infos from the given offset up to the given count. */
size_t count;
for (count = 0; count < out_meta_info.GetSize() && count + offset < reader.GetContentMetaCount(); count++) {
out_meta_info[count] = *reader.GetContentMetaInfo(count + offset);
}
/* Set the ouput value. */
out_entries_written.SetValue(count);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetAttributes(sf::Out<u8> out_attributes, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Set the ouput value. */
out_attributes.SetValue(reader.GetHeader()->attributes);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetRequiredApplicationVersion(sf::Out<u32> out_version, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Get the required version. */
u32 required_version;
switch (key.type) {
case ContentMetaType::AddOnContent:
required_version = reader.GetExtendedHeader<AddOnContentMetaExtendedHeader>()->required_application_version;
break;
case ContentMetaType::Application:
/* As of 9.0.0, applications can be dependent on a specific base application version. */
AMS_ABORT_UNLESS(hos::GetVersion() >= hos::Version_9_0_0);
required_version = reader.GetExtendedHeader<ApplicationMetaExtendedHeader>()->required_application_version;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Set the ouput value. */
out_version.SetValue(required_version);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetContentIdByTypeAndIdOffset(sf::Out<ContentId> out_content_id, const ContentMetaKey &key, ContentType type, u8 id_offset) {
R_RETURN(this->GetContentIdImpl(out_content_id.GetPointer(), key, type, util::make_optional(id_offset)));
}
Result ContentMetaDatabaseImpl::GetCount(sf::Out<u32> out_count) {
R_TRY(this->EnsureEnabled());
out_count.SetValue(m_kvs->GetCount());
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetOwnerApplicationId(sf::Out<ApplicationId> out_id, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Ensure this type of key has an owner. */
R_UNLESS(key.type == ContentMetaType::Application || key.type == ContentMetaType::Patch || key.type == ContentMetaType::AddOnContent, ncm::ResultInvalidContentMetaKey());
/* Applications are their own owner. */
if (key.type == ContentMetaType::Application) {
out_id.SetValue({key.id});
R_SUCCEED();
}
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Get the owner application id. */
ApplicationId owner_application_id;
switch (key.type) {
case ContentMetaType::Patch:
owner_application_id = reader.GetExtendedHeader<PatchMetaExtendedHeader>()->application_id;
break;
case ContentMetaType::AddOnContent:
owner_application_id = reader.GetExtendedHeader<AddOnContentMetaExtendedHeader>()->application_id;
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Set the output value. */
out_id.SetValue(owner_application_id);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetContentAccessibilities(sf::Out<u8> out_accessibilities, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Ensure this type of key is for an add-on content. */
R_UNLESS(key.type == ContentMetaType::AddOnContent, ncm::ResultInvalidContentMetaKey());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Set the ouput value. */
out_accessibilities.SetValue(reader.GetExtendedHeader<AddOnContentMetaExtendedHeader>()->content_accessibilities);
R_SUCCEED();
}
Result ContentMetaDatabaseImpl::GetContentInfoByType(sf::Out<ContentInfo> out_content_info, const ContentMetaKey &key, ContentType type) {
R_RETURN(this->GetContentInfoImpl(out_content_info.GetPointer(), key, type, util::nullopt));
}
Result ContentMetaDatabaseImpl::GetContentInfoByTypeAndIdOffset(sf::Out<ContentInfo> out_content_info, const ContentMetaKey &key, ContentType type, u8 id_offset) {
R_RETURN(this->GetContentInfoImpl(out_content_info.GetPointer(), key, type, util::make_optional(id_offset)));
}
Result ContentMetaDatabaseImpl::GetPlatform(sf::Out<ncm::ContentMetaPlatform> out, const ContentMetaKey &key) {
R_TRY(this->EnsureEnabled());
/* Obtain the content meta for the key. */
const void *meta;
size_t meta_size;
R_TRY(this->GetContentMetaPointer(&meta, &meta_size, key));
/* Create a reader. */
ContentMetaReader reader(meta, meta_size);
/* Set the ouput value. */
out.SetValue(reader.GetHeader()->platform);
R_SUCCEED();
}
}
| 20,995
|
C++
|
.cpp
| 421
| 39.971496
| 262
| 0.622739
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,856
|
ncm_package_install_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_package_install_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
bool PackageInstallTask::IsContentMetaContentName(const char *name) {
return impl::PathView(name).HasSuffix(".cnmt");
}
Result PackageInstallTask::Initialize(const char *package_root, StorageId storage_id, void *buffer, size_t buffer_size, bool ignore_ticket) {
R_RETURN(PackageInstallTaskBase::Initialize(package_root, buffer, buffer_size, storage_id, std::addressof(m_data), ignore_ticket ? InstallConfig_IgnoreTicket : InstallConfig_None));
}
Result PackageInstallTask::GetInstallContentMetaInfo(InstallContentMetaInfo *out_info, const ContentMetaKey &key) {
AMS_UNUSED(out_info, key);
R_THROW(ncm::ResultContentNotFound());
}
Result PackageInstallTask::PrepareInstallContentMetaData() {
/* Open the directory. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), this->GetPackageRootPath(), fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
while (true) {
/* Read the current entry. */
s64 count;
fs::DirectoryEntry entry;
R_TRY(fs::ReadDirectory(std::addressof(count), std::addressof(entry), dir, 1));
/* No more entries remain, we are done. */
if (count == 0) {
break;
}
/* Check if this entry is content meta. */
if (this->IsContentMetaContentName(entry.name)) {
/* Prepare content meta if id is valid. */
util::optional<ContentId> id = GetContentIdFromString(entry.name, strnlen(entry.name, fs::EntryNameLengthMax + 1));
R_UNLESS(id, ncm::ResultInvalidPackageFormat());
R_TRY(this->PrepareContentMeta(InstallContentMetaInfo::MakeUnverifiable(*id, entry.file_size), util::nullopt, util::nullopt));
}
}
R_SUCCEED();
}
}
| 2,612
|
C++
|
.cpp
| 53
| 41.792453
| 189
| 0.673205
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,857
|
ncm_content_id_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_id_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
namespace {
void GetStringFromBytes(char *dst, const void *src, size_t count) {
for (size_t i = 0; i < count; i++) {
util::SNPrintf(dst + 2 * i, 3, "%02x", static_cast<const u8 *>(src)[i]);
}
}
bool GetBytesFromString(void *dst, size_t dst_size, const char *src, size_t src_size) {
/* Each byte is comprised of hex characters. */
if (!util::IsAligned(src_size, 2) || (dst_size * 2 < src_size)) {
return false;
}
/* Convert each character pair to a byte until we reach the end. */
for (size_t i = 0; i < src_size; i += 2) {
char tmp[3];
util::Strlcpy(tmp, src + i, sizeof(tmp));
char *err = nullptr;
reinterpret_cast<u8 *>(dst)[i / 2] = static_cast<u8>(std::strtoul(tmp, std::addressof(err), 16));
if (*err != '\x00') {
return false;
}
}
return true;
}
}
ContentIdString GetContentIdString(ContentId id) {
ContentIdString str;
GetStringFromContentId(str.data, sizeof(str), id);
return str;
}
void GetStringFromContentId(char *dst, size_t dst_size, ContentId id) {
AMS_ABORT_UNLESS(dst_size > ContentIdStringLength);
GetStringFromBytes(dst, std::addressof(id), sizeof(id));
}
void GetStringFromRightsId(char *dst, size_t dst_size, fs::RightsId id) {
AMS_ABORT_UNLESS(dst_size > RightsIdStringLength);
GetStringFromBytes(dst, std::addressof(id), sizeof(id));
}
void GetTicketFileStringFromRightsId(char *dst, size_t dst_size, fs::RightsId id) {
AMS_ABORT_UNLESS(dst_size > TicketFileStringLength);
ContentIdString str;
GetStringFromRightsId(str.data, sizeof(str), id);
util::SNPrintf(dst, dst_size, "%s.tik", str.data);
}
void GetCertificateFileStringFromRightsId(char *dst, size_t dst_size, fs::RightsId id) {
AMS_ABORT_UNLESS(dst_size > CertFileStringLength);
ContentIdString str;
GetStringFromRightsId(str.data, sizeof(str), id);
util::SNPrintf(dst, dst_size, "%s.cert", str.data);
}
util::optional<ContentId> GetContentIdFromString(const char *str, size_t len) {
if (len < ContentIdStringLength) {
return util::nullopt;
}
ContentId content_id;
return GetBytesFromString(std::addressof(content_id), sizeof(content_id), str, ContentIdStringLength) ? util::optional<ContentId>(content_id) : util::nullopt;
}
}
| 3,316
|
C++
|
.cpp
| 74
| 36.540541
| 166
| 0.628332
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,858
|
ncm_content_manager_factory.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_manager_factory.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_content_manager_factory.hpp"
namespace ams::ncm {
sf::SharedPointer<IContentManager> CreateDefaultContentManager(const ContentManagerConfig &config) {
auto ref = sf::CreateSharedObjectEmplaced<IContentManager, ContentManagerImpl>();
R_ABORT_UNLESS(ref.GetImpl().Initialize(config));
return ref;
}
}
| 1,011
|
C++
|
.cpp
| 24
| 39.083333
| 104
| 0.755081
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,859
|
ncm_submission_package_install_task.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_submission_package_install_task.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
class SubmissionPackageInstallTask::Impl {
private:
fs::FileHandleStorage m_storage;
util::optional<impl::MountName> m_mount_name;
public:
explicit Impl(fs::FileHandle file) : m_storage(file), m_mount_name(util::nullopt) { /* ... */ }
~Impl() {
if (m_mount_name) {
fs::fsa::Unregister(m_mount_name->str);
}
}
Result Initialize() {
AMS_ASSERT(!m_mount_name);
/* Allocate a partition file system. */
auto partition_file_system = std::make_unique<fssystem::PartitionFileSystem>();
R_UNLESS(partition_file_system != nullptr, ncm::ResultAllocationFailed());
/* Initialize the partition file system. */
R_TRY(partition_file_system->Initialize(std::addressof(m_storage)));
/* Create a mount name and register the file system. */
auto mount_name = impl::CreateUniqueMountName();
R_TRY(fs::fsa::Register(mount_name.str, std::move(partition_file_system)));
/* Initialize members. */
m_mount_name = mount_name;
R_SUCCEED();
}
const impl::MountName &GetMountName() const {
return *m_mount_name;
}
};
SubmissionPackageInstallTask::SubmissionPackageInstallTask() : m_impl(nullptr) { /* ... */ }
SubmissionPackageInstallTask::~SubmissionPackageInstallTask() { /* ... */ }
Result SubmissionPackageInstallTask::Initialize(fs::FileHandle file, StorageId storage_id, void *buffer, size_t buffer_size, bool ignore_ticket) {
AMS_ASSERT(!m_impl);
/* Allocate impl. */
m_impl.reset(new (std::nothrow) Impl(file));
R_UNLESS(m_impl != nullptr, ncm::ResultAllocationFailed());
/* Initialize impl. */
R_TRY(m_impl->Initialize());
/* Initialize parent. N doesn't check the result. */
PackageInstallTask::Initialize(impl::GetRootDirectoryPath(m_impl->GetMountName()).str, storage_id, buffer, buffer_size, ignore_ticket);
R_SUCCEED();
}
}
| 2,916
|
C++
|
.cpp
| 61
| 38.459016
| 150
| 0.623592
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,860
|
ncm_content_meta_utils.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_meta_utils.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
Result MountContentMetaByRemoteFileSystemProxy(const char *mount_name, const char *path, fs::ContentAttributes attr) {
R_RETURN(fs::MountContent(mount_name, path, attr, fs::ContentType_Meta));
}
constinit MountContentMetaFunction g_mount_content_meta_func = MountContentMetaByRemoteFileSystemProxy;
}
namespace impl {
Result MountContentMetaImpl(const char *mount_name, const char *path, fs::ContentAttributes attr) {
R_RETURN(g_mount_content_meta_func(mount_name, path, attr));
}
}
bool IsContentMetaFileName(const char *name) {
return impl::PathView(name).HasSuffix(".cnmt");
}
Result ReadContentMetaPathAlongWithExtendedDataAndDigest(AutoBuffer *out, const char *path, fs::ContentAttributes attr) {
/* Mount the content. */
auto mount_name = impl::CreateUniqueMountName();
R_TRY(impl::MountContentMetaImpl(mount_name.str, path, attr));
ON_SCOPE_EXIT { fs::Unmount(mount_name.str); };
/* Open the root directory. */
auto root_path = impl::GetRootDirectoryPath(mount_name);
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path.str, fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
/* Loop directory reading until we find the entry we're looking for. */
while (true) {
/* Read one entry, and finish when we fail to read. */
fs::DirectoryEntry entry;
s64 num_read;
R_TRY(fs::ReadDirectory(std::addressof(num_read), std::addressof(entry), dir, 1));
if (num_read == 0) {
break;
}
/* If this is the content meta file, parse it. */
if (IsContentMetaFileName(entry.name)) {
/* Create the file path. */
impl::FilePathString file_path(root_path.str);
file_path.Append(entry.name);
/* Open the content meta file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), file_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the meta size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
const size_t meta_size = static_cast<size_t>(file_size);
/* Create a buffer for the meta. */
R_TRY(out->Initialize(meta_size));
/* Read the meta into the buffer. */
R_RETURN(fs::ReadFile(file, 0, out->Get(), meta_size));
}
}
R_THROW(ncm::ResultContentMetaNotFound());
}
Result ReadContentMetaPathAlongWithExtendedDataAndDigestSuppressingFsAbort(AutoBuffer *out, const char *path, fs::ContentAttributes attr) {
fs::ScopedAutoAbortDisabler aad;
R_RETURN(ReadContentMetaPathAlongWithExtendedDataAndDigest(out, path, attr));
}
Result ReadContentMetaPathWithoutExtendedDataOrDigest(AutoBuffer *out, const char *path, fs::ContentAttributes attr) {
/* Mount the content. */
auto mount_name = impl::CreateUniqueMountName();
R_TRY(impl::MountContentMetaImpl(mount_name.str, path, attr));
ON_SCOPE_EXIT { fs::Unmount(mount_name.str); };
/* Open the root directory. */
auto root_path = impl::GetRootDirectoryPath(mount_name);
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path.str, fs::OpenDirectoryMode_File));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
/* Loop directory reading until we find the entry we're looking for. */
while (true) {
/* Read one entry, and finish when we fail to read. */
fs::DirectoryEntry entry;
s64 num_read;
R_TRY(fs::ReadDirectory(std::addressof(num_read), std::addressof(entry), dir, 1));
if (num_read == 0) {
break;
}
/* If this is the content meta file, parse it. */
if (IsContentMetaFileName(entry.name)) {
/* Create the file path. */
impl::FilePathString file_path(root_path.str);
file_path.Append(entry.name);
/* Open the content meta file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), file_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the meta size. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
const size_t meta_file_size = static_cast<size_t>(file_size);
/* Check that the meta size is large enough. */
R_UNLESS(meta_file_size >= sizeof(PackagedContentMetaHeader), ncm::ResultInvalidContentMetaFileSize());
/* Read the header. */
PackagedContentMetaHeader header;
size_t read_size = 0;
R_TRY(fs::ReadFile(std::addressof(read_size), file, 0, std::addressof(header), sizeof(header)));
/* Check the right size was read. */
R_UNLESS(read_size == sizeof(PackagedContentMetaHeader), ncm::ResultInvalidContentMetaFileSize());
/* Determine the meta size. */
const size_t meta_size = PackagedContentMetaReader(std::addressof(header), sizeof(header)).GetExtendedDataOffset();
/* Create a buffer for the meta. */
R_TRY(out->Initialize(meta_size));
/* Read the meta into the buffer. */
R_RETURN(fs::ReadFile(file, 0, out->Get(), meta_size));
}
}
R_THROW(ncm::ResultContentMetaNotFound());
}
Result ReadContentMetaPathWithoutExtendedDataOrDigestSuppressingFsAbort(AutoBuffer *out, const char *path, fs::ContentAttributes attr) {
fs::ScopedAutoAbortDisabler aad;
R_RETURN(ReadContentMetaPathAlongWithExtendedDataAndDigest(out, path, attr));
}
Result TryReadContentMetaPath(fs::ContentAttributes *out_attr, AutoBuffer *out, const char *path, ReadContentMetaPathFunction func) {
/* Try with attributes = none. */
fs::ContentAttributes attr = fs::ContentAttributes_None;
R_TRY_CATCH(func(out, path, attr)) {
R_CATCH(fs::ResultNcaHeaderSignature1VerificationFailed) {
/* On signature failure, try with attributes = all. */
attr = fs::ContentAttributes_All;
R_TRY(func(out, path, attr));
}
} R_END_TRY_CATCH;
/* Set output attributes. */
*out_attr = attr;
R_SUCCEED();
}
Result TryReadContentMetaPath(AutoBuffer *out, const char *path, ReadContentMetaPathFunction func) {
/* Try with attributes = none. */
fs::ContentAttributes attr = fs::ContentAttributes_None;
R_TRY_CATCH(func(out, path, attr)) {
R_CATCH(fs::ResultNcaHeaderSignature1VerificationFailed) {
/* On signature failure, try with attributes = all. */
attr = fs::ContentAttributes_All;
R_TRY(func(out, path, attr));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result ReadVariationContentMetaInfoList(s32 *out_count, std::unique_ptr<ContentMetaInfo[]> *out_meta_infos, const Path &path, fs::ContentAttributes attr, FirmwareVariationId firmware_variation_id) {
AutoBuffer meta;
R_TRY(ReadContentMetaPathAlongWithExtendedDataAndDigestSuppressingFsAbort(std::addressof(meta), path.str, attr));
/* Create a reader for the content meta. */
PackagedContentMetaReader reader(meta.Get(), meta.GetSize());
/* Define a helper to output the base meta infos. */
const auto ReadMetaInfoListFromBase = [&] () ALWAYS_INLINE_LAMBDA -> Result {
/* Output the base content meta info count. */
*out_count = reader.GetContentMetaCount();
/* Create a buffer to hold the infos. NOTE: N does not check for nullptr before accessing. */
std::unique_ptr<ContentMetaInfo[]> buffer(new (std::nothrow) ContentMetaInfo[reader.GetContentMetaCount()]);
AMS_ABORT_UNLESS(buffer != nullptr);
/* Copy all base meta infos to output */
for (size_t i = 0; i < reader.GetContentMetaCount(); i++) {
buffer[i] = *reader.GetContentMetaInfo(i);
}
/* Write out the buffer we've populated. */
*out_meta_infos = std::move(buffer);
R_SUCCEED();
};
/* If there are no firmware variations to list, read meta infos from base. */
R_UNLESS(reader.GetExtendedDataSize() != 0, ReadMetaInfoListFromBase());
SystemUpdateMetaExtendedDataReader extended_data_reader(reader.GetExtendedData(), reader.GetExtendedDataSize());
util::optional<s32> firmware_variation_index = util::nullopt;
/* NOTE: Atmosphere extension to support downgrading. */
/* If all firmware variations refer to base, don't require the current variation be present. */
bool force_refer_to_base = true;
/* Find the input firmware variation id. */
for (size_t i = 0; i < extended_data_reader.GetFirmwareVariationCount(); i++) {
if (*extended_data_reader.GetFirmwareVariationId(i) == firmware_variation_id) {
firmware_variation_index = i;
break;
} else {
/* Check if the current variation refers to base. */
const FirmwareVariationInfo *cur_variation_info = extended_data_reader.GetFirmwareVariationInfo(i);
const bool cur_refers_to_base = extended_data_reader.GetHeader()->version == 1 || cur_variation_info->refer_to_base;
/* We force referral to base on unsupported variation only if all supported variations refer to base. */
force_refer_to_base &= cur_refers_to_base;
}
}
/* We couldn't find the input firmware variation id. */
if (!firmware_variation_index) {
/* Unless we can force a referral to base, the firmware isn't supported. */
R_UNLESS(force_refer_to_base, ncm::ResultInvalidFirmwareVariation());
/* Force a referral to base. */
R_RETURN(ReadMetaInfoListFromBase());
}
/* Obtain the variation info. */
const FirmwareVariationInfo *variation_info = extended_data_reader.GetFirmwareVariationInfo(*firmware_variation_index);
/* Refer to base if variation info says we should, or if version is 1. */
const bool refer_to_base = extended_data_reader.GetHeader()->version == 1 || variation_info->refer_to_base;
R_UNLESS(!refer_to_base, ReadMetaInfoListFromBase());
/* Output the content meta count. */
const u32 content_meta_count = variation_info->content_meta_count;
*out_count = content_meta_count;
/* We're done if there are no content metas to list. */
R_SUCCEED_IF(content_meta_count == 0);
/* Allocate a buffer for the content meta infos. */
std::unique_ptr<ContentMetaInfo[]> buffer(new (std::nothrow) ContentMetaInfo[content_meta_count]);
AMS_ABORT_UNLESS(buffer != nullptr);
/* Get the content meta infos. */
Span<const ContentMetaInfo> meta_infos;
extended_data_reader.GetContentMetaInfoList(std::addressof(meta_infos), content_meta_count);
/* Copy the meta infos to the buffer. */
for (size_t i = 0; i < content_meta_count; i++) {
buffer[i] = meta_infos[i];
}
/* Output the content meta info buffer. */
*out_meta_infos = std::move(buffer);
R_SUCCEED();
}
void SetMountContentMetaFunction(MountContentMetaFunction func) {
g_mount_content_meta_func = func;
}
}
| 12,760
|
C++
|
.cpp
| 231
| 44.272727
| 202
| 0.626113
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,861
|
ncm_content_manager_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_manager_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_content_storage_impl.hpp"
#include "ncm_read_only_content_storage_impl.hpp"
#include "ncm_host_content_storage_impl.hpp"
#include "ncm_content_meta_database_impl.hpp"
#include "ncm_on_memory_content_meta_database_impl.hpp"
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
alignas(os::MemoryPageSize) u8 g_system_content_meta_database_heap[512_KB];
alignas(os::MemoryPageSize) u8 g_gamecard_content_meta_database_heap[512_KB];
alignas(os::MemoryPageSize) u8 g_sd_and_user_content_meta_database_heap[2_MB + 512_KB];
ContentMetaMemoryResource g_system_content_meta_memory_resource(g_system_content_meta_database_heap, sizeof(g_system_content_meta_database_heap));
ContentMetaMemoryResource g_gamecard_content_meta_memory_resource(g_gamecard_content_meta_database_heap, sizeof(g_gamecard_content_meta_database_heap));
ContentMetaMemoryResource g_sd_and_user_content_meta_memory_resource(g_sd_and_user_content_meta_database_heap, sizeof(g_sd_and_user_content_meta_database_heap));
constexpr fs::SystemSaveDataId BuiltInSystemSaveDataId = 0x8000000000000120;
constexpr u64 BuiltInSystemSaveDataSize = 0x6c000;
constexpr u64 BuiltInSystemSaveDataJournalSize = 0x6c000;
constexpr u32 BuiltInSystemSaveDataFlags = fs::SaveDataFlags_KeepAfterResettingSystemSaveData | fs::SaveDataFlags_KeepAfterRefurbishment;
constexpr SystemSaveDataInfo BuiltInSystemSystemSaveDataInfo = {
.id = BuiltInSystemSaveDataId,
.size = BuiltInSystemSaveDataSize,
.journal_size = BuiltInSystemSaveDataJournalSize,
.flags = BuiltInSystemSaveDataFlags,
.space_id = fs::SaveDataSpaceId::System
};
constexpr fs::SystemSaveDataId BuiltInUserSaveDataId = 0x8000000000000121;
constexpr u64 BuiltInUserSaveDataSize = 0x29e000;
constexpr u64 BuiltInUserSaveDataJournalSize = 0x29e000;
constexpr u32 BuiltInUserSaveDataFlags = 0;
constexpr SystemSaveDataInfo BuiltInUserSystemSaveDataInfo = {
.id = BuiltInUserSaveDataId,
.size = BuiltInUserSaveDataSize,
.journal_size = BuiltInUserSaveDataJournalSize,
.flags = BuiltInUserSaveDataFlags,
.space_id = fs::SaveDataSpaceId::System
};
constexpr fs::SystemSaveDataId SdCardSaveDataId = 0x8000000000000124;
constexpr u64 SdCardSaveDataSize = 0xa08000;
constexpr u64 SdCardSaveDataJournalSize = 0xa08000;
constexpr u32 SdCardSaveDataFlags = 0;
constexpr SystemSaveDataInfo SdCardSystemSaveDataInfo = {
.id = SdCardSaveDataId,
.size = SdCardSaveDataSize,
.journal_size = SdCardSaveDataJournalSize,
.flags = SdCardSaveDataFlags,
.space_id = fs::SaveDataSpaceId::SdSystem,
};
using RootPath = kvdb::BoundedString<32>;
inline void ReplaceMountName(char *out_path, const char *mount_name, const char *path) {
std::strcpy(out_path, mount_name);
std::strcat(out_path, std::strchr(path, ':'));
}
Result EnsureBuiltInSystemSaveDataFlags() {
u32 cur_flags = 0;
/* Obtain the existing flags. */
R_TRY(fs::GetSaveDataFlags(std::addressof(cur_flags), BuiltInSystemSaveDataId));
/* Update the flags if needed. */
if (cur_flags != BuiltInSystemSaveDataFlags) {
R_TRY(fs::SetSaveDataFlags(BuiltInSystemSaveDataId, fs::SaveDataSpaceId::System, BuiltInSystemSaveDataFlags));
}
R_SUCCEED();
}
ALWAYS_INLINE Result GetContentStorageNotActiveResult(StorageId storage_id) {
switch (storage_id) {
case StorageId::GameCard: R_THROW(ncm::ResultGameCardContentStorageNotActive());
case StorageId::BuiltInSystem: R_THROW(ncm::ResultBuiltInSystemContentStorageNotActive());
case StorageId::BuiltInUser: R_THROW(ncm::ResultBuiltInUserContentStorageNotActive());
case StorageId::SdCard: R_THROW(ncm::ResultSdCardContentStorageNotActive());
default: R_THROW(ncm::ResultUnknownContentStorageNotActive());
}
}
ALWAYS_INLINE Result GetContentMetaDatabaseNotActiveResult(StorageId storage_id) {
switch (storage_id) {
case StorageId::GameCard: R_THROW(ncm::ResultGameCardContentMetaDatabaseNotActive());
case StorageId::BuiltInSystem: R_THROW(ncm::ResultBuiltInSystemContentMetaDatabaseNotActive());
case StorageId::BuiltInUser: R_THROW(ncm::ResultBuiltInUserContentMetaDatabaseNotActive());
case StorageId::SdCard: R_THROW(ncm::ResultSdCardContentMetaDatabaseNotActive());
default: R_THROW(ncm::ResultUnknownContentMetaDatabaseNotActive());
}
}
ALWAYS_INLINE bool IsSignedSystemPartitionOnSdCardValid(const char *bis_mount_name) {
/* Signed system partition should never be checked on < 4.0.0, as it did not exist before then. */
AMS_ABORT_UNLESS(hos::GetVersion() >= hos::Version_4_0_0);
/* If we're importing from system on SD, make sure that the signed system partition is valid. */
const auto version = hos::GetVersion();
if (version >= hos::Version_8_0_0) {
/* On >= 8.0.0, a simpler method was added to check validity. */
/* This also works on < 4.0.0 (though the system partition will never be on-sd there), */
/* and so this will always return false. */
char path[fs::MountNameLengthMax + 2 /* :/ */ + 1];
util::SNPrintf(path, sizeof(path), "%s:/", bis_mount_name);
return fs::IsSignedSystemPartitionOnSdCardValid(path);
} else {
/* On 4.0.0-7.0.1, use the remote command to validate the system partition. */
return fs::IsSignedSystemPartitionOnSdCardValidDeprecated();
}
}
Result EnsureAndMountSystemSaveData(const char *mount_name, const SystemSaveDataInfo &info) {
constexpr u64 OwnerId = 0;
/* Don't create save if absent - We want to handle this case ourselves. */
fs::DisableAutoSaveDataCreation();
/* Mount existing system save data if present, otherwise create it then mount. */
R_TRY_CATCH(fs::MountSystemSaveData(mount_name, info.space_id, info.id)) {
R_CATCH(fs::ResultTargetNotFound) {
/* On 1.0.0, not all flags existed. Mask when appropriate. */
constexpr u32 SaveDataFlags100Mask = fs::SaveDataFlags_KeepAfterResettingSystemSaveData;
const u32 flags = (hos::GetVersion() >= hos::Version_2_0_0) ? (info.flags) : (info.flags & SaveDataFlags100Mask);
R_TRY(fs::CreateSystemSaveData(info.space_id, info.id, OwnerId, info.size, info.journal_size, flags));
R_TRY(fs::MountSystemSaveData(mount_name, info.space_id, info.id));
}
} R_END_TRY_CATCH;
R_SUCCEED();
}
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Create() {
/* Create all storages. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
const auto &root = m_roots[i];
/* If we should, skip. */
if (!root.config.has_value() || root.config->skip_verify_and_create) {
continue;
}
/* Mount the relevant content storage. */
R_TRY(fs::MountContentStorage(root.mount_name, root.config->content_storage_id));
ON_SCOPE_EXIT { fs::Unmount(root.mount_name); };
/* Ensure the content storage root's path exists. */
R_TRY(fs::EnsureDirectory(root.path));
/* Initialize content and placeholder directories for the root. */
R_TRY(ContentStorageImpl::InitializeBase(root.path));
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Verify() {
/* Verify all storages. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
const auto &root = m_roots[i];
/* If we should, skip. */
if (!root.config.has_value() || root.config->skip_verify_and_create) {
continue;
}
/* Substitute the mount name in the root's path with a unique one. */
char path[0x80];
auto mount_name = impl::CreateUniqueMountName();
ReplaceMountName(path, mount_name.str, root.path);
/* Mount the relevant content storage. */
R_TRY(fs::MountContentStorage(mount_name.str, root.config->content_storage_id));
ON_SCOPE_EXIT { fs::Unmount(mount_name.str); };
/* Ensure the root, content and placeholder directories exist for the storage. */
R_TRY(ContentStorageImpl::VerifyBase(path));
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Open(sf::Out<sf::SharedPointer<IContentStorage>> out, RightsIdCache &rights_id_cache, RegisteredHostContent ®istered_host_content) {
/* Get the interface. */
const bool has_intf = m_config->is_integrated ? m_integrated_content_storage != nullptr : m_roots->content_storage != nullptr;
if (hos::GetVersion() >= hos::Version_2_0_0) {
/* Obtain the content storage if already active. */
R_UNLESS(has_intf, GetContentStorageNotActiveResult(m_config->storage_id));
} else {
/* 1.0.0 activates content storages as soon as they are opened. */
if (!has_intf) {
R_TRY(this->Activate(rights_id_cache, registered_host_content));
}
}
*out = m_config->is_integrated ? m_integrated_content_storage : m_roots->content_storage;
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Activate(RightsIdCache &rights_id_cache, RegisteredHostContent ®istered_host_content) {
/* If necessary, create the integrated storage. */
if (m_config->is_integrated && !m_integrated_content_storage) {
m_integrated_content_storage = sf::CreateSharedObjectEmplaced<IContentStorage, IntegratedContentStorageImpl>();
}
/* Activate all storages. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
auto &root = m_roots[i];
/* If we should, skip. */
if (root.config.has_value() && root.config->skip_activate) {
continue;
}
/* Activate. */
R_TRY(this->Activate(root, rights_id_cache, registered_host_content));
/* If we're integrated, add the storage. */
if (m_config->is_integrated) {
/* Determine the index of the storage. */
int index;
for (index = 0; index < m_config->num_content_storage_ids; ++index) {
if (m_config->content_storage_ids[index] == root.config->content_storage_id) {
break;
}
}
/* Add the storage. */
m_integrated_content_storage.GetImpl().Add(root.content_storage, index + 1);
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Inactivate(RegisteredHostContent ®istered_host_content) {
/* If we have an integrated storage, disable it. */
if (m_integrated_content_storage != nullptr) {
R_TRY(m_integrated_content_storage->DisableForcibly());
m_integrated_content_storage.Reset();
}
/* Disable and unmount all storages. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
auto &root = m_roots[i];
if (root.content_storage != nullptr) {
/* N doesn't bother checking the result of this. */
root.content_storage->DisableForcibly();
root.content_storage = nullptr;
if (root.storage_id == StorageId::Host) {
registered_host_content.ClearPaths();
} else {
fs::Unmount(root.mount_name);
}
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Activate(RightsIdCache &rights_id_cache, RegisteredHostContent ®istered_host_content, fs::ContentStorageId content_storage_id) {
/* Check that we have the desired storage id in some root. */
ContentStorageRoot *root = this->GetRoot(content_storage_id);
R_UNLESS(root != nullptr, ncm::ResultUnknownStorage());
/* If necessary, create the integrated storage. */
if (m_config->is_integrated && !m_integrated_content_storage) {
m_integrated_content_storage = sf::CreateSharedObjectEmplaced<IContentStorage, IntegratedContentStorageImpl>();
}
/* Activate. */
R_TRY(this->Activate(*root, rights_id_cache, registered_host_content));
/* If we're integrated, add the storage. */
if (m_config->is_integrated) {
/* Determine the index of the storage. */
int index;
for (index = 0; index < m_config->num_content_storage_ids; ++index) {
if (m_config->content_storage_ids[index] == root->config->content_storage_id) {
break;
}
}
/* Add the storage. */
m_integrated_content_storage.GetImpl().Add(root->content_storage, index + 1);
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentStorageRoot::Activate(ContentStorageRoot &root, RightsIdCache &rights_id_cache, RegisteredHostContent ®istered_host_content) {
/* Check if the storage is already activated. */
R_SUCCEED_IF(root.content_storage != nullptr);
/* Handle based on whether or not we have a content storage config. */
if (root.config.has_value()) {
/* Mount the content storage. */
R_TRY(fs::MountContentStorage(root.mount_name, root.config->content_storage_id));
ON_RESULT_FAILURE { fs::Unmount(root.mount_name); };
/* Create a content storage. */
auto content_storage = sf::CreateSharedObjectEmplaced<IContentStorage, ContentStorageImpl>();
/* Initialize content storage with an appropriate path function. */
switch (root.storage_id) {
case StorageId::BuiltInSystem:
R_TRY(content_storage.GetImpl().Initialize(root.path, MakeFlatContentFilePath, MakeFlatPlaceHolderFilePath, false, std::addressof(rights_id_cache)));
break;
case StorageId::SdCard:
R_TRY(content_storage.GetImpl().Initialize(root.path, MakeSha256HierarchicalContentFilePath_ForFat16KCluster, MakeSha256HierarchicalPlaceHolderFilePath_ForFat16KCluster, true, std::addressof(rights_id_cache)));
break;
default:
R_TRY(content_storage.GetImpl().Initialize(root.path, MakeSha256HierarchicalContentFilePath_ForFat16KCluster, MakeSha256HierarchicalPlaceHolderFilePath_ForFat16KCluster, false, std::addressof(rights_id_cache)));
break;
}
root.content_storage = std::move(content_storage);
} else {
switch (root.storage_id) {
case ncm::StorageId::Host:
root.content_storage = sf::CreateSharedObjectEmplaced<IContentStorage, HostContentStorageImpl>(std::addressof(registered_host_content));
break;
case ncm::StorageId::GameCard:
{
/* Get the gamecard handle. */
fs::GameCardHandle handle{};
R_TRY(fs::GetGameCardHandle(std::addressof(handle)));
/* Mount the secure gamecard partition. */
R_TRY(fs::MountGameCardPartition(root.mount_name, handle, fs::GameCardPartition::Secure));
ON_RESULT_FAILURE { fs::Unmount(root.mount_name); };
/* Create the content storage. */
auto content_storage = sf::CreateSharedObjectEmplaced<IContentStorage, ReadOnlyContentStorageImpl>();
R_TRY(content_storage.GetImpl().Initialize(root.path, MakeFlatContentFilePath));
root.content_storage = std::move(content_storage);
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Create() {
/* Create all content meta databases. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
const auto &root = m_roots[i];
/* If we should, skip. */
if (!root.save_data_info.has_value()) {
continue;
}
/* Mount (and optionally create) save data for the root. */
R_TRY(EnsureAndMountSystemSaveData(root.mount_name, *root.save_data_info));
ON_SCOPE_EXIT { fs::Unmount(root.mount_name); };
/* Ensure the content meta database root's path exists. */
R_TRY(fs::EnsureDirectory(root.path));
/* Commit our changes. */
R_TRY(fs::CommitSaveData(root.mount_name));
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Verify() {
/* Verify all content meta databases. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
const auto &root = m_roots[i];
/* If we should, skip. */
if (!root.save_data_info.has_value()) {
continue;
}
/* Mount save data for non-existing content meta databases. */
const bool mount = !root.content_meta_database;
if (mount) {
R_TRY(fs::MountSystemSaveData(root.mount_name, root.save_data_info->space_id, root.save_data_info->id));
}
auto mount_guard = SCOPE_GUARD { if (mount) { fs::Unmount(root.mount_name); } };
/* Ensure the root path exists. */
bool has_dir = false;
R_TRY(fs::HasDirectory(std::addressof(has_dir), root.path));
R_UNLESS(has_dir, ncm::ResultInvalidContentMetaDatabase());
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Open(sf::Out<sf::SharedPointer<IContentMetaDatabase>> out) {
/* Get the interface. */
const bool has_intf = m_config->is_integrated ? m_integrated_content_meta_database != nullptr : m_roots->content_meta_database != nullptr;
if (hos::GetVersion() >= hos::Version_2_0_0) {
/* Obtain the content meta database if already active. */
R_UNLESS(has_intf, GetContentMetaDatabaseNotActiveResult(m_config->storage_id));
} else {
/* 1.0.0 activates content meta database as soon as they are opened. */
if (!has_intf) {
R_TRY(this->Activate());
}
}
*out = m_config->is_integrated ? m_integrated_content_meta_database : m_roots->content_meta_database;
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Cleanup() {
/* Cleanup all content meta databases. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
const auto &root = m_roots[i];
/* If we should, skip. */
if (!root.save_data_info.has_value()) {
continue;
}
/* Delete save data for the content meta database. */
R_TRY(fs::DeleteSaveData(root.save_data_info->space_id, root.save_data_info->id));
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Activate() {
/* If necessary, create the integrated meta database. */
if (m_config->is_integrated && !m_integrated_content_meta_database) {
m_integrated_content_meta_database = sf::CreateSharedObjectEmplaced<IContentMetaDatabase, IntegratedContentMetaDatabaseImpl>();
}
/* Activate all meta databases. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
auto &root = m_roots[i];
/* If we should, skip. */
if (root.storage_config.has_value() && root.storage_config->skip_activate) {
continue;
}
/* Activate. */
R_TRY(this->Activate(root));
/* If we're integrated, add the meta database. */
if (m_config->is_integrated) {
/* Determine the index of the meta database. */
int index;
for (index = 0; index < m_config->num_content_storage_ids; ++index) {
if (m_config->content_storage_ids[index] == root.storage_config->content_storage_id) {
break;
}
}
/* Add the meta database. */
m_integrated_content_meta_database.GetImpl().Add(root.content_meta_database, index + 1);
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Inactivate() {
/* If we have an integrated meta database, disable it. */
/* NOTE: Nintendo does not reset the integrated DB, presumably they just forgot... */
/* ...this breaks this, hard, so we'll do the correct thing. */
if (m_integrated_content_meta_database != nullptr) {
R_TRY(m_integrated_content_meta_database->DisableForcibly());
m_integrated_content_meta_database.Reset();
}
/* Disable and unmount all storages. */
for (auto i = 0; i < m_num_roots; ++i) {
/* Get the current root. */
auto &root = m_roots[i];
if (root.content_meta_database != nullptr) {
/* N doesn't bother checking the result of this. */
root.content_meta_database->DisableForcibly();
root.content_meta_database = nullptr;
root.kvs = util::nullopt;
/* Additionally, if we have savedata, unmount. */
if (root.save_data_info.has_value()) {
fs::Unmount(root.mount_name);
}
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Activate(ContentMetaDatabaseRoot &root) {
/* If the root is already activated, there's nothing to do. */
R_SUCCEED_IF(root.content_meta_database != nullptr);
/* Make a new kvs. */
root.kvs.emplace();
/* If we should, mount save data for this route. */
if (root.save_data_info.has_value()) {
/* Mount save data for this root. */
R_TRY(fs::MountSystemSaveData(root.mount_name, root.save_data_info->space_id, root.save_data_info->id));
ON_RESULT_FAILURE { fs::Unmount(root.mount_name); };
/* Initialize and load the key value store from the filesystem. */
R_TRY(root.kvs->Initialize(root.path, root.max_content_metas, root.memory_resource));
R_TRY(root.kvs->Load());
/* Create the content meta database. */
root.content_meta_database = sf::CreateSharedObjectEmplaced<IContentMetaDatabase, ContentMetaDatabaseImpl>(std::addressof(*root.kvs), root.mount_name);
} else {
if (root.storage_id == StorageId::BuiltInSystem) {
/* Create a temporary mount name, and mount the partition. */
auto tmp_mount_name = impl::CreateUniqueMountName();
switch (root.storage_config->content_storage_id) {
case fs::ContentStorageId::System:
R_TRY(fs::MountBis(tmp_mount_name.str, fs::BisPartitionId::System));
break;
case fs::ContentStorageId::System0:
R_TRY(fs::MountBis(tmp_mount_name.str, fs::BisPartitionId::System0));
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
ON_SCOPE_EXIT { fs::Unmount(tmp_mount_name.str); };
/* Initialize and load the key value store from the filesystem. */
char path[fs::EntryNameLengthMax];
util::SNPrintf(path, sizeof(path), "%s:/cnmtdb.arc", tmp_mount_name.str);
R_TRY(root.kvs->InitializeForReadOnlyArchiveFile(path, root.max_content_metas, root.memory_resource));
R_TRY(root.kvs->Load());
/* Create an on memory content meta database. */
root.content_meta_database = sf::CreateSharedObjectEmplaced<IContentMetaDatabase, OnMemoryContentMetaDatabaseImpl>(std::addressof(*root.kvs));
} else {
/* Initialize the key value store. */
R_TRY(root.kvs->Initialize(root.max_content_metas, root.memory_resource));
/* Create an on memory content meta database. */
root.content_meta_database = sf::CreateSharedObjectEmplaced<IContentMetaDatabase, OnMemoryContentMetaDatabaseImpl>(std::addressof(*root.kvs));
}
}
R_SUCCEED();
}
Result ContentManagerImpl::IntegratedContentMetaDatabaseRoot::Activate(fs::ContentStorageId content_storage_id) {
/* Check that we have the desired storage id in some root. */
ContentMetaDatabaseRoot *root = this->GetRoot(content_storage_id);
R_UNLESS(root != nullptr, ncm::ResultUnknownStorage());
/* If necessary, create the integrated meta database. */
if (m_config->is_integrated && !m_integrated_content_meta_database) {
m_integrated_content_meta_database = sf::CreateSharedObjectEmplaced<IContentMetaDatabase, IntegratedContentMetaDatabaseImpl>();
}
/* Activate. */
R_TRY(this->Activate(*root));
/* If we're integrated, add the storage. */
if (m_config->is_integrated) {
/* Determine the index of the meta database. */
int index;
for (index = 0; index < m_config->num_content_storage_ids; ++index) {
if (m_config->content_storage_ids[index] == root->storage_config->content_storage_id) {
break;
}
}
/* Add the meta database. */
m_integrated_content_meta_database.GetImpl().Add(root->content_meta_database, index + 1);
}
R_SUCCEED();
}
ContentManagerImpl::~ContentManagerImpl() {
std::scoped_lock lk(m_mutex);
/* Disable and unmount all content storage roots. */
for (size_t i = 0; i < m_num_integrated_content_storage_entries; ++i) {
this->InactivateContentStorage(m_integrated_content_storage_roots[i].m_config->storage_id);
}
/* Disable and unmount all content meta database roots. */
for (size_t i = 0; i < m_num_integrated_content_meta_entries; ++i) {
this->InactivateContentMetaDatabase(m_integrated_content_meta_database_roots[i].m_config->storage_id);
}
}
Result ContentManagerImpl::GetIntegratedContentStorageConfig(IntegratedContentStorageConfig **out, fs::ContentStorageId content_storage_id) {
for (size_t i = 0; i < m_num_integrated_configs; ++i) {
auto &integrated_config = m_integrated_configs[i];
for (auto n = 0; n < integrated_config.num_content_storage_ids; n++) {
if (integrated_config.content_storage_ids[n] == content_storage_id) {
*out = std::addressof(integrated_config);
R_SUCCEED();
}
}
}
R_THROW(ncm::ResultUnknownStorage());
}
Result ContentManagerImpl::GetIntegratedContentStorageRoot(IntegratedContentStorageRoot **out, StorageId id) {
/* Storage must not be StorageId::Any or StorageId::None. */
R_UNLESS(IsUniqueStorage(id), ncm::ResultUnknownStorage());
/* Find a root with a matching storage id. */
for (size_t i = 0; i < m_num_integrated_content_storage_entries; ++i) {
if (auto &root = m_integrated_content_storage_roots[i]; root.m_config->storage_id == id) {
*out = std::addressof(root);
R_SUCCEED();
}
}
R_THROW(ncm::ResultUnknownStorage());
}
Result ContentManagerImpl::GetIntegratedContentMetaDatabaseRoot(IntegratedContentMetaDatabaseRoot **out, StorageId id) {
/* Storage must not be StorageId::Any or StorageId::None. */
R_UNLESS(IsUniqueStorage(id), ncm::ResultUnknownStorage());
/* Find a root with a matching storage id. */
for (size_t i = 0; i < m_num_integrated_content_meta_entries; ++i) {
if (auto &root = m_integrated_content_meta_database_roots[i]; root.m_config->storage_id == id) {
*out = std::addressof(root);
R_SUCCEED();
}
}
R_THROW(ncm::ResultUnknownStorage());
}
Result ContentManagerImpl::InitializeContentStorageRoot(ContentStorageRoot *out, StorageId storage_id, util::optional<ContentStorageConfig> config) {
out->storage_id = storage_id;
out->config = config;
out->content_storage = nullptr;
/* Create a new mount name and copy it to out. */
std::strcpy(out->mount_name, impl::CreateUniqueMountName().str);
util::SNPrintf(out->path, sizeof(out->path), "%s:/", out->mount_name);
R_SUCCEED();
}
Result ContentManagerImpl::InitializeContentMetaDatabaseRoot(ContentMetaDatabaseRoot *out, StorageId storage_id, util::optional<ContentStorageConfig> storage_config) {
out->storage_id = storage_id;
out->storage_config = storage_config;
/* Set the storage-specific info. */
switch (storage_id) {
case ncm::StorageId::Host:
out->save_data_info = util::nullopt;
out->max_content_metas = HostMaxContentMetaCount;
out->memory_resource = std::addressof(g_sd_and_user_content_meta_memory_resource);
break;
case ncm::StorageId::GameCard:
out->save_data_info = util::nullopt;
out->max_content_metas = GameCardMaxContentMetaCount;
out->memory_resource = std::addressof(g_gamecard_content_meta_memory_resource);
break;
case ncm::StorageId::BuiltInSystem:
/* If we should, skip save data info. */
if (storage_config.has_value() && (storage_config->content_storage_id != fs::ContentStorageId::System || storage_config->skip_verify_and_create)) {
out->save_data_info = util::nullopt;
} else {
/* Otherwise, use normal save data info. */
out->save_data_info = BuiltInSystemSystemSaveDataInfo;
}
out->max_content_metas = SystemMaxContentMetaCount;
out->memory_resource = std::addressof(g_system_content_meta_memory_resource);
break;
case ncm::StorageId::BuiltInUser:
out->save_data_info = BuiltInUserSystemSaveDataInfo;
out->max_content_metas = UserMaxContentMetaCount;
out->memory_resource = std::addressof(g_sd_and_user_content_meta_memory_resource);
break;
case ncm::StorageId::SdCard:
out->save_data_info = SdCardSystemSaveDataInfo;
out->max_content_metas = SdCardMaxContentMetaCount;
out->memory_resource = std::addressof(g_sd_and_user_content_meta_memory_resource);
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
/* Clear the kvs. */
out->kvs = util::nullopt;
/* Create a new mount name and copy it to out. */
std::strcpy(out->mount_name, impl::CreateUniqueMountName().str);
out->mount_name[0] = '#';
util::SNPrintf(out->path, sizeof(out->path), "%s:/meta", out->mount_name);
R_SUCCEED();
}
Result ContentManagerImpl::InitializeIntegratedContentStorageRoot(IntegratedContentStorageRoot *out, const IntegratedContentStorageConfig *config, size_t root_idx, size_t root_count) {
/* Set config and roots. */
out->m_config = config;
out->m_roots = std::addressof(m_content_storage_roots[root_idx]);
out->m_num_roots = root_count;
R_SUCCEED();
}
Result ContentManagerImpl::InitializeIntegratedContentMetaDatabaseRoot(IntegratedContentMetaDatabaseRoot *out, const IntegratedContentStorageConfig *config, size_t root_idx, size_t root_count) {
/* Set config and roots. */
out->m_config = config;
out->m_roots = std::addressof(m_content_meta_database_roots[root_idx]);
out->m_num_roots = root_count;
R_SUCCEED();
}
Result ContentManagerImpl::ImportContentMetaDatabaseImpl(ContentMetaDatabaseRoot *root, const char *import_mount_name) {
/* Check that the root is system. */
AMS_ABORT_UNLESS(root->storage_id == ncm::StorageId::BuiltInSystem);
std::scoped_lock lk(m_mutex);
/* Print the savedata path. */
PathString savedata_db_path;
savedata_db_path.AssignFormat("%s/%s", root->path, "imkvdb.arc");
/* Print a path for the mounted partition. */
PathString bis_db_path;
bis_db_path.AssignFormat("%s:/%s", import_mount_name, "cnmtdb.arc");
/* Mount the savedata. */
R_TRY(fs::MountSystemSaveData(root->mount_name, root->save_data_info->space_id, root->save_data_info->id));
ON_SCOPE_EXIT { fs::Unmount(root->mount_name); };
/* Ensure the path exists for us to import to. */
R_TRY(fs::EnsureDirectory(root->path));
/* Copy the file from bis to our save. */
R_TRY(impl::CopyFile(savedata_db_path, bis_db_path));
/* Commit the import. */
R_RETURN(fs::CommitSaveData(root->mount_name));
}
Result ContentManagerImpl::BuildContentMetaDatabase(StorageId storage_id) {
if (hos::GetVersion() < hos::Version_5_0_0) {
/* On < 5.0.0, perform an actual build of the database. */
R_RETURN(this->BuildContentMetaDatabaseImpl(storage_id));
} else {
/* On 5.0.0+, building just performs an import. */
R_RETURN(this->ImportContentMetaDatabase(storage_id, false));
}
}
Result ContentManagerImpl::BuildContentMetaDatabaseImpl(StorageId storage_id) {
/* Temporarily activate the database. */
R_TRY(this->ActivateContentMetaDatabase(storage_id));
ON_SCOPE_EXIT { this->InactivateContentMetaDatabase(storage_id); };
/* Open the content meta database and storage. */
ContentMetaDatabase meta_db;
ContentStorage storage;
R_TRY(ncm::OpenContentMetaDatabase(std::addressof(meta_db), storage_id));
R_TRY(ncm::OpenContentStorage(std::addressof(storage), storage_id));
/* Create a builder, and build. */
ContentMetaDatabaseBuilder builder(std::addressof(meta_db));
R_RETURN(builder.BuildFromStorage(std::addressof(storage)));
}
Result ContentManagerImpl::ImportContentMetaDatabase(StorageId storage_id, bool from_signed_partition) {
/* Only support importing BuiltInSystem. */
AMS_ABORT_UNLESS(storage_id == StorageId::BuiltInSystem);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *integrated_root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(integrated_root), storage_id));
/* Obtain the root. */
ContentMetaDatabaseRoot *root = integrated_root->GetRoot(fs::ContentStorageId::System);
R_UNLESS(root != nullptr, ncm::ResultUnknownStorage());
/* Get a mount name for the system partition. */
auto bis_mount_name = impl::CreateUniqueMountName();
/* Mount the BIS partition that contains the database we're importing. */
R_TRY(fs::MountBis(bis_mount_name.str, fs::BisPartitionId::System));
ON_SCOPE_EXIT { fs::Unmount(bis_mount_name.str); };
/* If we're not importing from a signed partition (or the partition signature is valid), import. */
if (!from_signed_partition || IsSignedSystemPartitionOnSdCardValid(bis_mount_name.str)) {
R_TRY(this->ImportContentMetaDatabaseImpl(root, bis_mount_name.str));
}
R_SUCCEED();
}
bool ContentManagerImpl::IsNeedRebuildSystemContentMetaDatabase() {
/* TODO: Should hos::GetVersion() >= hos::Version_17_0_0 be checked? */
/* If we do not actually have a content meta db, we should re-build. */
if (R_FAILED(this->VerifyContentMetaDatabase(StorageId::BuiltInSystem))) {
return true;
}
/* We have a content meta db. Temporarily, activate it. */
if (R_FAILED(this->ActivateContentMetaDatabase(StorageId::BuiltInSystem))) {
return true;
}
ON_SCOPE_EXIT { this->InactivateContentMetaDatabase(StorageId::BuiltInSystem); };
/* Open the content meta db. */
ContentMetaDatabase meta_db;
R_ABORT_UNLESS(ncm::OpenContentMetaDatabase(std::addressof(meta_db), StorageId::BuiltInSystem));
/* List the meta db's contents. */
const auto list_count = meta_db.ListContentMeta(nullptr, 0);
/* We need to rebuild if the db has zero entries. */
return list_count.total == 0;
}
Result ContentManagerImpl::Initialize(const ContentManagerConfig &config) {
/* Initialize based on whether integrated content is enabled. */
if (config.IsIntegratedSystemContentEnabled()) {
constexpr const IntegratedContentStorageConfig IntegratedConfigsForIntegratedSystemContent[] = {
{ ncm::StorageId::BuiltInSystem, { fs::ContentStorageId::System, fs::ContentStorageId::System0 }, 2, true },
{ ncm::StorageId::BuiltInUser, { fs::ContentStorageId::User }, 1, false },
{ ncm::StorageId::SdCard, { fs::ContentStorageId::SdCard }, 1, false },
{ ncm::StorageId::GameCard, { }, 0, false },
{ ncm::StorageId::Host, { }, 0, false },
};
constexpr const ContentStorageConfig ContentStorageConfigsForIntegratedSystemContent[] = {
{ .content_storage_id = fs::ContentStorageId::System, .skip_verify_and_create = true, .skip_activate = true, },
{ .content_storage_id = fs::ContentStorageId::System0, .skip_verify_and_create = true, .skip_activate = false, },
{ .content_storage_id = fs::ContentStorageId::User, .skip_verify_and_create = false, .skip_activate = false, },
{ .content_storage_id = fs::ContentStorageId::SdCard, .skip_verify_and_create = false, .skip_activate = false, },
};
constexpr const ncm::StorageId ActivatedStoragesForIntegratedSystemContent[] = {
ncm::StorageId::BuiltInSystem,
};
R_RETURN(this->Initialize(config, IntegratedConfigsForIntegratedSystemContent, util::size(IntegratedConfigsForIntegratedSystemContent), ContentStorageConfigsForIntegratedSystemContent, util::size(ContentStorageConfigsForIntegratedSystemContent), ActivatedStoragesForIntegratedSystemContent, util::size(ActivatedStoragesForIntegratedSystemContent)));
} else {
constexpr const IntegratedContentStorageConfig IntegratedConfigs[] = {
{ ncm::StorageId::BuiltInSystem, { fs::ContentStorageId::System }, 1, false },
{ ncm::StorageId::BuiltInUser, { fs::ContentStorageId::User }, 1, false },
{ ncm::StorageId::SdCard, { fs::ContentStorageId::SdCard }, 1, false },
{ ncm::StorageId::GameCard, { }, 0, false },
{ ncm::StorageId::Host, { }, 0, false },
};
constexpr const ContentStorageConfig ContentStorageConfigs[] = {
{ .content_storage_id = fs::ContentStorageId::System, .skip_verify_and_create = false, .skip_activate = false, },
{ .content_storage_id = fs::ContentStorageId::User, .skip_verify_and_create = false, .skip_activate = false, },
{ .content_storage_id = fs::ContentStorageId::SdCard, .skip_verify_and_create = false, .skip_activate = false, },
};
constexpr const ncm::StorageId ActivatedStorages[] = {
ncm::StorageId::BuiltInSystem,
};
R_RETURN(this->Initialize(config, IntegratedConfigs, util::size(IntegratedConfigs), ContentStorageConfigs, util::size(ContentStorageConfigs), ActivatedStorages, util::size(ActivatedStorages)));
}
}
Result ContentManagerImpl::Initialize(const ContentManagerConfig &manager_config, const IntegratedContentStorageConfig *integrated_configs, size_t num_integrated_configs, const ContentStorageConfig *configs, size_t num_configs, const ncm::StorageId *activated_storages, size_t num_activated_storages) {
std::scoped_lock lk(m_mutex);
/* Check if we've already initialized. */
R_SUCCEED_IF(m_initialized);
/* Set our configs. */
for (size_t i = 0; i < num_integrated_configs; ++i) {
m_integrated_configs[i] = integrated_configs[i];
}
m_num_integrated_configs = num_integrated_configs;
for (size_t i = 0; i < num_configs; ++i) {
m_configs[i] = configs[i];
}
m_num_configs = num_configs;
/* Setup roots. */
m_num_integrated_content_storage_entries = 0;
m_num_content_storage_entries = 0;
m_num_integrated_content_meta_entries = 0;
m_num_content_meta_entries = 0;
for (size_t i = 0; i < m_num_integrated_configs; ++i) {
/* Get the integrated config. */
const auto &integrated_config = m_integrated_configs[i];
/* Set up storage and meta db roots. */
size_t content_storage_root_idx = m_num_content_storage_entries;
size_t content_meta_root_idx = m_num_content_meta_entries;
if (integrated_config.num_content_storage_ids > 0) {
/* If we have content storage ids, set up storage/meta db roots for each. */
for (auto n = 0; n < integrated_config.num_content_storage_ids; n++) {
/* Get the config. */
const auto &config = this->GetContentStorageConfig(integrated_config.content_storage_ids[n]);
R_TRY(this->InitializeContentStorageRoot(std::addressof(m_content_storage_roots[m_num_content_storage_entries++]), integrated_config.storage_id, config));
R_TRY(this->InitializeContentMetaDatabaseRoot(std::addressof(m_content_meta_database_roots[m_num_content_meta_entries++]), integrated_config.storage_id, config));
}
} else {
/* If we have no content storage ids, set up a single storage/meta db root. */
R_TRY(this->InitializeContentStorageRoot(std::addressof(m_content_storage_roots[m_num_content_storage_entries++]), integrated_config.storage_id, util::nullopt));
R_TRY(this->InitializeContentMetaDatabaseRoot(std::addressof(m_content_meta_database_roots[m_num_content_meta_entries++]), integrated_config.storage_id, util::nullopt));
}
R_TRY(this->InitializeIntegratedContentStorageRoot(std::addressof(m_integrated_content_storage_roots[m_num_integrated_content_storage_entries++]), std::addressof(integrated_config), content_storage_root_idx, m_num_content_storage_entries - content_storage_root_idx));
R_TRY(this->InitializeIntegratedContentMetaDatabaseRoot(std::addressof(m_integrated_content_meta_database_roots[m_num_integrated_content_meta_entries++]), std::addressof(integrated_config), content_meta_root_idx, m_num_content_meta_entries - content_meta_root_idx));
}
/* Activate storages. */
for (size_t i = 0; i < num_activated_storages; i++) {
const auto storage_id = activated_storages[i];
if (storage_id == ncm::StorageId::BuiltInSystem) {
R_TRY(this->InitializeStorageBuiltInSystem(manager_config));
} else {
R_TRY(this->InitializeStorage(storage_id));
}
}
m_initialized = true;
R_SUCCEED();
}
Result ContentManagerImpl::InitializeStorageBuiltInSystem(const ContentManagerConfig &manager_config) {
/* Setup and activate the storage for BuiltInSystem. */
if (R_FAILED(this->VerifyContentStorage(StorageId::BuiltInSystem))) {
R_TRY(this->CreateContentStorage(StorageId::BuiltInSystem));
}
R_TRY(this->ActivateContentStorage(StorageId::BuiltInSystem));
/* NOTE: This logic is unofficial. */
/* Beginning with 17.0.0+, save management behavior changed. The primary symptom of this is either verify fail */
/* or an empty kvs, both of which we can fix by performing a rebuild. */
if (this->IsNeedRebuildSystemContentMetaDatabase()) {
/* Clean up the system content meta database, to ensure creation can succeed. */
this->CleanupContentMetaDatabase(StorageId::BuiltInSystem);
/* Create the content meta database. */
R_TRY(this->CreateContentMetaDatabase(StorageId::BuiltInSystem));
/* Rebuild the content meta database. */
R_TRY(this->BuildContentMetaDatabaseImpl(StorageId::BuiltInSystem));
}
/* Setup the content meta database for system. */
if (R_FAILED(this->VerifyContentMetaDatabase(StorageId::BuiltInSystem))) {
R_TRY(this->CreateContentMetaDatabase(StorageId::BuiltInSystem));
/* Try to build or import a database, depending on our configuration. */
if (manager_config.ShouldBuildDatabase()) {
/* If we should build the database, do so. */
R_TRY(this->BuildContentMetaDatabase(StorageId::BuiltInSystem));
R_TRY(this->VerifyContentMetaDatabase(StorageId::BuiltInSystem));
} else if (manager_config.ShouldImportDatabaseFromSignedSystemPartitionOnSd()) {
/* Otherwise if we should import the database from the SD, do so. */
R_TRY(this->ImportContentMetaDatabase(StorageId::BuiltInSystem, true));
R_TRY(this->VerifyContentMetaDatabase(StorageId::BuiltInSystem));
}
}
/* Ensure correct flags on the BuiltInSystem save data. */
/* NOTE: Nintendo does not check this succeeds, and it does on older system versions. */
/* We will not check the error, either, even though this kind of defeats the call's purpose. */
if (hos::GetVersion() >= hos::Version_2_0_0) {
EnsureBuiltInSystemSaveDataFlags();
}
/* Activate the content meta database. */
R_TRY(this->ActivateContentMetaDatabase(StorageId::BuiltInSystem));
R_SUCCEED();
}
Result ContentManagerImpl::InitializeStorage(ncm::StorageId storage_id) {
/* Setup and activate the storage. */
if (R_FAILED(this->VerifyContentStorage(storage_id))) {
R_TRY(this->CreateContentStorage(storage_id));
}
R_TRY(this->ActivateContentStorage(StorageId::BuiltInSystem));
/* Setup the content meta database for system. */
if (R_FAILED(this->VerifyContentMetaDatabase(storage_id))) {
R_TRY(this->CreateContentMetaDatabase(storage_id));
}
R_TRY(this->ActivateContentMetaDatabase(storage_id));
R_SUCCEED();
}
Result ContentManagerImpl::CreateContentStorage(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content storage root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), storage_id));
R_RETURN(root->Create());
}
Result ContentManagerImpl::CreateContentMetaDatabase(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Create());
}
Result ContentManagerImpl::VerifyContentStorage(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content storage root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), storage_id));
R_RETURN(root->Verify());
}
Result ContentManagerImpl::VerifyContentMetaDatabase(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Verify());
}
Result ContentManagerImpl::OpenContentStorage(sf::Out<sf::SharedPointer<IContentStorage>> out, StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content storage root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), storage_id));
R_RETURN(root->Open(out, m_rights_id_cache, m_registered_host_content));
}
Result ContentManagerImpl::OpenContentMetaDatabase(sf::Out<sf::SharedPointer<IContentMetaDatabase>> out, StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Open(out));
}
Result ContentManagerImpl::CloseContentStorageForcibly(StorageId storage_id) {
R_RETURN(this->InactivateContentStorage(storage_id));
}
Result ContentManagerImpl::CloseContentMetaDatabaseForcibly(StorageId storage_id) {
R_RETURN(this->InactivateContentMetaDatabase(storage_id));
}
Result ContentManagerImpl::CleanupContentMetaDatabase(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Cleanup());
}
Result ContentManagerImpl::ActivateContentStorage(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content storage root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), storage_id));
R_RETURN(root->Activate(m_rights_id_cache, m_registered_host_content));
}
Result ContentManagerImpl::InactivateContentStorage(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content storage root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), storage_id));
R_RETURN(root->Inactivate(m_registered_host_content));
}
Result ContentManagerImpl::ActivateContentMetaDatabase(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Activate());
}
Result ContentManagerImpl::InactivateContentMetaDatabase(StorageId storage_id) {
std::scoped_lock lk(m_mutex);
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), storage_id));
R_RETURN(root->Inactivate());
}
Result ContentManagerImpl::InvalidateRightsIdCache() {
m_rights_id_cache.Invalidate();
R_SUCCEED();
}
Result ContentManagerImpl::GetMemoryReport(sf::Out<MemoryReport> out) {
/* Populate content meta resource states. */
MemoryReport report = {
.system_content_meta_resource_state = {
.peak_total_alloc_size = g_system_content_meta_memory_resource.GetPeakTotalAllocationSize(),
.peak_alloc_size = g_system_content_meta_memory_resource.GetPeakAllocationSize(),
.allocatable_size = g_system_content_meta_memory_resource.GetAllocator()->GetAllocatableSize(),
.total_free_size = g_system_content_meta_memory_resource.GetAllocator()->GetTotalFreeSize(),
},
.sd_and_user_content_meta_resource_state {
.peak_total_alloc_size = g_sd_and_user_content_meta_memory_resource.GetPeakTotalAllocationSize(),
.peak_alloc_size = g_sd_and_user_content_meta_memory_resource.GetPeakAllocationSize(),
.allocatable_size = g_sd_and_user_content_meta_memory_resource.GetAllocator()->GetAllocatableSize(),
.total_free_size = g_sd_and_user_content_meta_memory_resource.GetAllocator()->GetTotalFreeSize(),
},
.gamecard_content_meta_resource_state {
.peak_total_alloc_size = g_gamecard_content_meta_memory_resource.GetPeakTotalAllocationSize(),
.peak_alloc_size = g_gamecard_content_meta_memory_resource.GetPeakAllocationSize(),
.allocatable_size = g_gamecard_content_meta_memory_resource.GetAllocator()->GetAllocatableSize(),
.total_free_size = g_gamecard_content_meta_memory_resource.GetAllocator()->GetTotalFreeSize(),
},
.heap_resource_state = {},
};
/* Populate heap memory resource state. */
GetHeapState().GetMemoryResourceState(std::addressof(report.heap_resource_state));
/* Output the report. */
out.SetValue(report);
R_SUCCEED();
}
Result ContentManagerImpl::ActivateFsContentStorage(fs::ContentStorageId content_storage_id) {
/* Get the integrated config for the storage. */
IntegratedContentStorageConfig *integrated_config;
R_TRY(this->GetIntegratedContentStorageConfig(std::addressof(integrated_config), content_storage_id));
{
/* Obtain the integrated content meta database root. */
IntegratedContentStorageRoot *root;
R_TRY(this->GetIntegratedContentStorageRoot(std::addressof(root), integrated_config->storage_id));
R_TRY(root->Activate(m_rights_id_cache, m_registered_host_content, content_storage_id));
}
{
/* Obtain the integrated content meta database root. */
IntegratedContentMetaDatabaseRoot *root;
R_TRY(this->GetIntegratedContentMetaDatabaseRoot(std::addressof(root), integrated_config->storage_id));
R_TRY(root->Activate(content_storage_id));
}
R_SUCCEED();
}
}
| 57,426
|
C++
|
.cpp
| 980
| 46.882653
| 361
| 0.626007
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,862
|
ncm_make_path.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_make_path.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
namespace {
void MakeContentName(PathString *out, ContentId id) {
out->AssignFormat("%s.nca", GetContentIdString(id).data);
}
void MakePlaceHolderName(PathString *out, PlaceHolderId id) {
auto &bytes = id.uuid.data;
char tmp[3];
/* Create a hex string from bytes. */
for (size_t i = 0; i < sizeof(bytes); i++) {
util::SNPrintf(tmp, util::size(tmp), "%02x", bytes[i]);
out->Append(tmp);
}
/* Append file extension. */
out->Append(".nca");
}
u16 Get16BitSha256HashPrefix(ContentId id) {
u8 hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(hash, sizeof(hash), std::addressof(id), sizeof(id));
return static_cast<u16>(hash[0]) | (static_cast<u16>(hash[1]) << 8);
}
u8 Get8BitSha256HashPrefix(ContentId id) {
u8 hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(hash, sizeof(hash), std::addressof(id), sizeof(id));
return hash[0];
}
u8 Get8BitSha256HashPrefix(PlaceHolderId id) {
u8 hash[crypto::Sha256Generator::HashSize];
crypto::GenerateSha256(hash, sizeof(hash), std::addressof(id), sizeof(id));
return hash[0];
}
}
void MakeFlatContentFilePath(PathString *out, ContentId content_id, const char *root_path) {
/* Create the content name from the content id. */
PathString content_name;
MakeContentName(std::addressof(content_name), content_id);
/* Format the output path. */
out->AssignFormat("%s/%s", root_path, content_name.Get());
}
void MakeSha256HierarchicalContentFilePath_ForFat4KCluster(PathString *out, ContentId content_id, const char *root_path) {
/* Hash the content id. */
const u16 hash = Get16BitSha256HashPrefix(content_id);
const u32 hash_upper = (hash >> 10) & 0x3f;
const u32 hash_lower = (hash >> 4) & 0x3f;
/* Create the content name from the content id. */
PathString content_name;
MakeContentName(std::addressof(content_name), content_id);
/* Format the output path. */
out->AssignFormat("%s/%08X/%08X/%s", root_path, hash_upper, hash_lower, content_name.Get());
}
void MakeSha256HierarchicalContentFilePath_ForFat32KCluster(PathString *out, ContentId content_id, const char *root_path) {
/* Hash the content id. */
const u32 hash = (Get16BitSha256HashPrefix(content_id) >> 6) & 0x3FF;
/* Create the content name from the content id. */
PathString content_name;
MakeContentName(std::addressof(content_name), content_id);
/* Format the output path. */
out->AssignFormat("%s/%08X/%s", root_path, hash, content_name.Get());
}
void MakeSha256HierarchicalContentFilePath_ForFat16KCluster(PathString *out, ContentId content_id, const char *root_path) {
/* Hash the content id. */
const u32 hash_byte = static_cast<u32>(Get8BitSha256HashPrefix(content_id));
/* Create the content name from the content id. */
PathString content_name;
MakeContentName(std::addressof(content_name), content_id);
/* Format the output path. */
out->AssignFormat("%s/%08X/%s", root_path, hash_byte, content_name.Get());
}
size_t GetHierarchicalContentDirectoryDepth(MakeContentPathFunction func) {
if (func == MakeFlatContentFilePath) {
return 1;
} else if (func == MakeSha256HierarchicalContentFilePath_ForFat4KCluster) {
return 3;
} else if (func == MakeSha256HierarchicalContentFilePath_ForFat16KCluster ||
func == MakeSha256HierarchicalContentFilePath_ForFat32KCluster) {
return 2;
} else {
AMS_ABORT();
}
}
void MakeFlatPlaceHolderFilePath(PathString *out, PlaceHolderId placeholder_id, const char *root_path) {
/* Create the placeholder name from the placeholder id. */
PathString placeholder_name;
MakePlaceHolderName(std::addressof(placeholder_name), placeholder_id);
/* Format the output path. */
out->AssignFormat("%s/%s", root_path, placeholder_name.Get());
}
void MakeSha256HierarchicalPlaceHolderFilePath_ForFat16KCluster(PathString *out, PlaceHolderId placeholder_id, const char *root_path) {
/* Hash the placeholder id. */
const u32 hash_byte = static_cast<u32>(Get8BitSha256HashPrefix(placeholder_id));
/* Create the placeholder name from the placeholder id. */
PathString placeholder_name;
MakePlaceHolderName(std::addressof(placeholder_name), placeholder_id);
/* Format the output path. */
out->AssignFormat("%s/%08X/%s", root_path, hash_byte, placeholder_name.Get());
}
size_t GetHierarchicalPlaceHolderDirectoryDepth(MakePlaceHolderPathFunction func) {
if (func == MakeFlatPlaceHolderFilePath) {
return 1;
} else if (func == MakeSha256HierarchicalPlaceHolderFilePath_ForFat16KCluster) {
return 2;
} else {
AMS_ABORT();
}
}
}
| 5,963
|
C++
|
.cpp
| 122
| 40.286885
| 139
| 0.651755
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,863
|
ncm_install_task_data.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_install_task_data.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::ncm {
namespace {
using BoundedPath = kvdb::BoundedString<64>;
constexpr inline bool Includes(const ContentMetaKey *keys, s32 count, const ContentMetaKey &key) {
for (s32 i = 0; i < count; i++) {
if (keys[i] == key) {
return true;
}
}
return false;
}
}
Result InstallTaskDataBase::Get(InstallContentMeta *out, s32 index) {
/* Determine the data size. */
size_t data_size;
R_TRY(this->GetSize(std::addressof(data_size), index));
/* Create a buffer and read data into it. */
std::unique_ptr<char[]> buffer(new (std::nothrow) char[data_size]);
R_UNLESS(buffer != nullptr, ncm::ResultAllocationFailed());
R_TRY(this->Get(index, buffer.get(), data_size));
/* Output the buffer and size. */
out->data = std::move(buffer);
out->size = data_size;
R_SUCCEED();
}
Result InstallTaskDataBase::Update(const InstallContentMeta &content_meta, s32 index) {
R_RETURN(this->Update(index, content_meta.data.get(), content_meta.size));
}
Result InstallTaskDataBase::Has(bool *out, u64 id) {
s32 count;
R_TRY(this->Count(std::addressof(count)));
/* Iterate over each entry. */
for (s32 i = 0; i < count; i++) {
InstallContentMeta content_meta;
R_TRY(this->Get(std::addressof(content_meta), i));
/* If the id matches we are successful. */
if (content_meta.GetReader().GetKey().id == id) {
*out = true;
R_SUCCEED();
}
}
/* We didn't find the value. */
*out = false;
R_SUCCEED();
}
Result MemoryInstallTaskData::GetProgress(InstallProgress *out_progress) {
/* Initialize install progress. */
InstallProgress install_progress = {
.state = m_state,
};
install_progress.SetLastResult(m_last_result);
/* Only states after prepared are allowed. */
if (m_state != InstallProgressState::NotPrepared && m_state != InstallProgressState::DataPrepared) {
for (auto &data_holder : m_data_list) {
const InstallContentMetaReader reader = data_holder.GetReader();
/* Sum the sizes from this entry's content infos. */
for (size_t i = 0; i < reader.GetContentCount(); i++) {
const InstallContentInfo *content_info = reader.GetContentInfo(i);
install_progress.installed_size += content_info->GetSize();
install_progress.total_size += content_info->GetSizeWritten();
}
}
}
*out_progress = install_progress;
R_SUCCEED();
}
Result MemoryInstallTaskData::GetSystemUpdateTaskApplyInfo(SystemUpdateTaskApplyInfo *out_info) {
*out_info = m_system_update_task_apply_info;
R_SUCCEED();
}
Result MemoryInstallTaskData::SetState(InstallProgressState state) {
m_state = state;
R_SUCCEED();
}
Result MemoryInstallTaskData::SetLastResult(Result result) {
m_last_result = result;
R_SUCCEED();
}
Result MemoryInstallTaskData::SetSystemUpdateTaskApplyInfo(SystemUpdateTaskApplyInfo info) {
m_system_update_task_apply_info = info;
R_SUCCEED();
}
Result MemoryInstallTaskData::Push(const void *data, size_t size) {
/* Allocate a new data holder. */
auto holder = std::unique_ptr<DataHolder>(new (std::nothrow) DataHolder());
R_UNLESS(holder != nullptr, ncm::ResultAllocationFailed());
/* Allocate memory for the content meta data. */
holder->data = std::unique_ptr<char[]>(new (std::nothrow) char[size]);
R_UNLESS(holder->data != nullptr, ncm::ResultAllocationFailed());
holder->size = size;
/* Copy data to the data holder. */
std::memcpy(holder->data.get(), data, size);
/* Put the data holder into the data list. */
m_data_list.push_back(*holder);
/* Relinquish control over the memory allocated to the data holder. */
holder.release();
R_SUCCEED();
}
Result MemoryInstallTaskData::Count(s32 *out) {
*out = m_data_list.size();
R_SUCCEED();
}
Result MemoryInstallTaskData::GetSize(size_t *out_size, s32 index) {
/* Find the correct entry in the list. */
s32 count = 0;
for (auto &data_holder : m_data_list) {
if (index == count++) {
*out_size = data_holder.size;
R_SUCCEED();
}
}
/* Out of bounds indexing is an unrecoverable error. */
AMS_ABORT();
}
Result MemoryInstallTaskData::Get(s32 index, void *out, size_t out_size) {
/* Find the correct entry in the list. */
s32 count = 0;
for (auto &data_holder : m_data_list) {
if (index == count++) {
R_UNLESS(out_size >= data_holder.size, ncm::ResultBufferInsufficient());
std::memcpy(out, data_holder.data.get(), data_holder.size);
R_SUCCEED();
}
}
/* Out of bounds indexing is an unrecoverable error. */
AMS_ABORT();
}
Result MemoryInstallTaskData::Update(s32 index, const void *data, size_t data_size) {
/* Find the correct entry in the list. */
s32 count = 0;
for (auto &data_holder : m_data_list) {
if (index == count++) {
R_UNLESS(data_size == data_holder.size, ncm::ResultBufferInsufficient());
std::memcpy(data_holder.data.get(), data, data_size);
R_SUCCEED();
}
}
/* Out of bounds indexing is an unrecoverable error. */
AMS_ABORT();
}
Result MemoryInstallTaskData::Delete(const ContentMetaKey *keys, s32 num_keys) {
/* Iterate over keys. */
for (s32 i = 0; i < num_keys; i++) {
const auto &key = keys[i];
/* Find and remove matching data from the list. */
for (auto &data_holder : m_data_list) {
if (key == data_holder.GetReader().GetKey()) {
m_data_list.erase(m_data_list.iterator_to(data_holder));
delete std::addressof(data_holder);
break;
}
}
}
R_SUCCEED();
}
Result MemoryInstallTaskData::Cleanup() {
while (!m_data_list.empty()) {
auto *data_holder = std::addressof(m_data_list.front());
m_data_list.pop_front();
delete data_holder;
}
R_SUCCEED();
}
Result FileInstallTaskData::Create(const char *path, s32 max_entries) {
/* Create the file. */
R_TRY(fs::CreateFile(path, 0));
/* Open the file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path, fs::OpenMode_Write | fs::OpenMode_AllowAppend));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Create an initial header and write it to the file. */
const Header header = MakeInitialHeader(max_entries);
R_RETURN(fs::WriteFile(file, 0, std::addressof(header), sizeof(Header), fs::WriteOption::Flush));
}
Result FileInstallTaskData::Initialize(const char *path) {
std::strncpy(m_path, path, sizeof(m_path));
m_path[sizeof(m_path) - 1] = '\x00';
R_RETURN(this->Read(std::addressof(m_header), sizeof(Header), 0));
}
Result FileInstallTaskData::GetProgress(InstallProgress *out_progress) {
/* Initialize install progress. */
InstallProgress install_progress = {
.state = m_header.progress_state,
};
install_progress.SetLastResult(m_header.last_result);
/* Only states after prepared are allowed. */
if (m_header.progress_state != InstallProgressState::NotPrepared && m_header.progress_state != InstallProgressState::DataPrepared) {
for (size_t i = 0; i < m_header.count; i++) {
/* Obtain the content meta for this entry. */
InstallContentMeta content_meta;
R_TRY(InstallTaskDataBase::Get(std::addressof(content_meta), i));
const InstallContentMetaReader reader = content_meta.GetReader();
/* Sum the sizes from this entry's content infos. */
for (size_t j = 0; j < reader.GetContentCount(); j++) {
const InstallContentInfo *content_info = reader.GetContentInfo(j);
install_progress.installed_size += content_info->GetSize();
install_progress.total_size += content_info->GetSizeWritten();
}
}
}
*out_progress = install_progress;
R_SUCCEED();
}
Result FileInstallTaskData::GetSystemUpdateTaskApplyInfo(SystemUpdateTaskApplyInfo *out_info) {
*out_info = m_header.system_update_task_apply_info;
R_SUCCEED();
}
Result FileInstallTaskData::SetState(InstallProgressState state) {
m_header.progress_state = state;
R_RETURN(this->WriteHeader());
}
Result FileInstallTaskData::SetLastResult(Result result) {
m_header.last_result = result;
R_RETURN(this->WriteHeader());
}
Result FileInstallTaskData::SetSystemUpdateTaskApplyInfo(SystemUpdateTaskApplyInfo info) {
m_header.system_update_task_apply_info = info;
R_RETURN(this->WriteHeader());
}
Result FileInstallTaskData::Push(const void *data, size_t data_size) {
R_UNLESS(m_header.count < m_header.max_entries, ncm::ResultBufferInsufficient());
/* Create a new entry info. Data of the given size will be stored at the end of the file. */
const EntryInfo entry_info = { m_header.last_data_offset, static_cast<s64>(data_size) };
/* Write the new entry info. */
R_TRY(this->Write(std::addressof(entry_info), sizeof(EntryInfo), GetEntryInfoOffset(m_header.count)));
/* Write the data to the offset in the entry info. */
R_TRY(this->Write(data, data_size, entry_info.offset));
/* Update the header for the new entry. */
m_header.last_data_offset += data_size;
m_header.count++;
/* Write the updated header. */
R_RETURN(this->WriteHeader());
}
Result FileInstallTaskData::Count(s32 *out) {
*out = m_header.count;
R_SUCCEED();
}
Result FileInstallTaskData::GetSize(size_t *out_size, s32 index) {
EntryInfo entry_info;
R_TRY(this->GetEntryInfo(std::addressof(entry_info), index));
*out_size = entry_info.size;
R_SUCCEED();
}
Result FileInstallTaskData::Get(s32 index, void *out, size_t out_size) {
/* Obtain the entry info. */
EntryInfo entry_info;
R_TRY(this->GetEntryInfo(std::addressof(entry_info), index));
/* Read the entry to the output buffer. */
R_UNLESS(entry_info.size <= static_cast<s64>(out_size), ncm::ResultBufferInsufficient());
R_RETURN(this->Read(out, out_size, entry_info.offset));
}
Result FileInstallTaskData::Update(s32 index, const void *data, size_t data_size) {
/* Obtain the entry info. */
EntryInfo entry_info;
R_TRY(this->GetEntryInfo(std::addressof(entry_info), index));
/* Data size must match existing data size. */
R_UNLESS(entry_info.size == static_cast<s64>(data_size), ncm::ResultBufferInsufficient());
R_RETURN(this->Write(data, data_size, entry_info.offset));
}
Result FileInstallTaskData::Delete(const ContentMetaKey *keys, s32 num_keys) {
/* Create the path for the temporary data. */
BoundedPath tmp_path(m_path);
tmp_path.Append(".tmp");
/* Create a new temporary install task data. */
FileInstallTaskData install_task_data;
R_TRY(FileInstallTaskData::Create(tmp_path, m_header.max_entries));
R_TRY(install_task_data.Initialize(tmp_path));
/* Get the number of entries. */
s32 count;
R_TRY(this->Count(std::addressof(count)));
/* Copy entries that are not excluded to the new install task data. */
for (s32 i = 0; i < count; i++) {
InstallContentMeta content_meta;
R_TRY(InstallTaskDataBase::Get(std::addressof(content_meta), i));
/* Check if entry is excluded. If not, push it to our new install task data. */
if (Includes(keys, num_keys, content_meta.GetReader().GetKey())) {
continue;
}
/* NOTE: Nintendo doesn't check that this operation succeeds. */
install_task_data.Push(content_meta.data.get(), content_meta.size);
}
/* Change from our current data to the new data. */
m_header = install_task_data.m_header;
R_TRY(fs::DeleteFile(m_path));
R_RETURN(fs::RenameFile(tmp_path, m_path));
}
Result FileInstallTaskData::Cleanup() {
m_header = MakeInitialHeader(m_header.max_entries);
R_RETURN(this->WriteHeader());
}
Result FileInstallTaskData::GetEntryInfo(EntryInfo *out_entry_info, s32 index) {
AMS_ABORT_UNLESS(static_cast<u32>(index) < m_header.count);
R_RETURN(this->Read(out_entry_info, sizeof(EntryInfo), GetEntryInfoOffset(index)));
}
Result FileInstallTaskData::Write(const void *data, size_t size, s64 offset) {
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), m_path, fs::OpenMode_Write | fs::OpenMode_AllowAppend));
ON_SCOPE_EXIT { fs::CloseFile(file); };
R_RETURN(fs::WriteFile(file, offset, data, size, fs::WriteOption::Flush));
}
Result FileInstallTaskData::Read(void *out, size_t out_size, s64 offset) {
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), m_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
R_RETURN(fs::ReadFile(file, offset, out, out_size));
}
Result FileInstallTaskData::WriteHeader() {
R_RETURN(this->Write(std::addressof(m_header), sizeof(Header), 0));
}
}
| 14,976
|
C++
|
.cpp
| 326
| 36.533742
| 140
| 0.609671
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,864
|
ncm_content_storage_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/ncm/ncm_content_storage_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "ncm_content_storage_impl.hpp"
#include "ncm_fs_utils.hpp"
namespace ams::ncm {
namespace {
constexpr inline const char * const BaseContentDirectory = "/registered";
void MakeBaseContentDirectoryPath(PathString *out, const char *root_path) {
out->AssignFormat("%s%s", root_path, BaseContentDirectory);
}
void MakeContentPath(PathString *out, ContentId id, MakeContentPathFunction func, const char *root_path) {
PathString path;
MakeBaseContentDirectoryPath(std::addressof(path), root_path);
func(out, id, path);
}
Result EnsureContentDirectory(ContentId id, MakeContentPathFunction func, const char *root_path) {
PathString path;
MakeContentPath(std::addressof(path), id, func, root_path);
R_RETURN(fs::EnsureParentDirectory(path));
}
Result DeleteContentFile(ContentId id, MakeContentPathFunction func, const char *root_path) {
/* Create the content path. */
PathString path;
MakeContentPath(std::addressof(path), id, func, root_path);
/* Delete the content. */
R_TRY_CATCH(fs::DeleteFile(path)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultContentNotFound())
} R_END_TRY_CATCH;
R_SUCCEED();
}
template<typename F>
Result TraverseDirectory(bool *out_should_continue, const char *root_path, int max_level, F f) {
/* If the level is zero, we're done. */
R_SUCCEED_IF(max_level <= 0);
/* On 1.0.0, NotRequireFileSize was not a valid open mode. */
const auto open_dir_mode = hos::GetVersion() >= hos::Version_2_0_0 ? (fs::OpenDirectoryMode_All | fs::OpenDirectoryMode_NotRequireFileSize) : (fs::OpenDirectoryMode_All);
/* Retry traversal upon request. */
bool retry_dir_read = true;
while (retry_dir_read) {
retry_dir_read = false;
/* Open the directory at the given path. All entry types are allowed. */
fs::DirectoryHandle dir;
R_TRY(fs::OpenDirectory(std::addressof(dir), root_path, open_dir_mode));
ON_SCOPE_EXIT { fs::CloseDirectory(dir); };
while (true) {
/* Read a single directory entry. */
fs::DirectoryEntry entry;
s64 entry_count;
R_TRY(fs::ReadDirectory(std::addressof(entry_count), std::addressof(entry), dir, 1));
/* Directory has no entries to process. */
if (entry_count == 0) {
break;
}
/* Path of the current entry. */
PathString current_path;
current_path.AssignFormat("%s/%s", root_path, entry.name);
/* Call the process function. */
bool should_continue = true;
bool should_retry_dir_read = false;
R_TRY(f(std::addressof(should_continue), std::addressof(should_retry_dir_read), current_path, entry));
/* If the provided function wishes to terminate immediately, we should respect it. */
if (!should_continue) {
*out_should_continue = false;
R_SUCCEED();
}
/* Mark for retry. */
if (should_retry_dir_read) {
retry_dir_read = true;
break;
}
/* If the entry is a directory, recurse. */
if (entry.type == fs::DirectoryEntryType_Directory) {
R_TRY(TraverseDirectory(std::addressof(should_continue), current_path, max_level - 1, f));
if (!should_continue) {
*out_should_continue = false;
R_SUCCEED();
}
}
}
}
R_SUCCEED();
}
template<typename F>
Result TraverseDirectory(const char *root_path, int max_level, F f) {
bool should_continue = false;
R_RETURN(TraverseDirectory(std::addressof(should_continue), root_path, max_level, f));
}
bool IsContentPath(const char *path) {
impl::PathView view(path);
/* Ensure nca suffix. */
if (!view.HasSuffix(".nca")) {
return false;
}
/* File name should be the size of a content id plus the nca file extension. */
auto file_name = view.GetFileName();
if (file_name.length() != ContentIdStringLength + 4) {
return false;
}
/* Ensure file name is comprised of hex characters. */
for (size_t i = 0; i < ContentIdStringLength; i++) {
if (!std::isxdigit(static_cast<unsigned char>(file_name[i]))) {
return false;
}
}
return true;
}
bool IsPlaceHolderPath(const char *path) {
return IsContentPath(path);
}
Result CleanDirectoryRecursively(const PathString &path) {
if (hos::GetVersion() >= hos::Version_3_0_0) {
R_TRY(fs::CleanDirectoryRecursively(path));
} else {
/* CleanDirectoryRecursively didn't exist on < 3.0.0, so we will polyfill it. */
/* We'll delete the directory, then recreate it. */
R_TRY(fs::DeleteDirectoryRecursively(path));
R_TRY(fs::CreateDirectory(path));
}
R_SUCCEED();
}
}
ContentStorageImpl::ContentIterator::~ContentIterator() {
for (size_t i = 0; i < m_depth; i++) {
fs::CloseDirectory(m_handles[i]);
}
}
Result ContentStorageImpl::ContentIterator::Initialize(const char *root_path, size_t max_depth) {
/* Initialize tracking variables. */
m_depth = 0;
m_max_depth = max_depth;
m_entry_count = 0;
/* Create the base content directory path. */
MakeBaseContentDirectoryPath(std::addressof(m_path), root_path);
/* Open the base directory. */
R_TRY(this->OpenCurrentDirectory());
R_SUCCEED();
}
Result ContentStorageImpl::ContentIterator::OpenCurrentDirectory() {
/* Determine valid directory mode (prior to 2.0.0, NotRequireFileSize was not valid). */
const auto open_mode = hos::GetVersion() >= hos::Version_2_0_0 ? (fs::OpenDirectoryMode_All | fs::OpenDirectoryMode_NotRequireFileSize) : (fs::OpenDirectoryMode_All);
/* Open the directory for our current path. */
R_TRY(fs::OpenDirectory(std::addressof(m_handles[m_depth]), m_path, open_mode));
/* Increase our depth. */
++m_depth;
R_SUCCEED();
}
Result ContentStorageImpl::ContentIterator::OpenDirectory(const char *dir) {
/* Set our current path. */
m_path.Assign(dir);
/* Open the directory. */
R_RETURN(this->OpenCurrentDirectory());
}
Result ContentStorageImpl::ContentIterator::GetNext(util::optional<fs::DirectoryEntry> *out) {
/* Iterate until we get the next entry. */
while (true) {
/* Ensure that we have entries loaded. */
R_TRY(this->LoadEntries());
/* If we failed to load any entries, there's nothing to get. */
if (m_entry_count <= 0) {
*out = util::nullopt;
R_SUCCEED();
}
/* Get the next entry. */
const auto &entry = m_entries[--m_entry_count];
/* Process the current entry. */
switch (entry.type) {
case fs::DirectoryEntryType_Directory:
/* If the entry if a directory, we want to recurse into it if we can. */
if (m_depth < m_max_depth) {
/* Construct the full path for the subdirectory. */
PathString entry_path;
entry_path.AssignFormat("%s/%s", m_path.Get(), entry.name);
/* Open the subdirectory. */
R_TRY(this->OpenDirectory(entry_path.Get()));
}
break;
case fs::DirectoryEntryType_File:
/* Otherwise, if the entry is a file, return it. */
*out = entry;
R_SUCCEED();
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
R_SUCCEED();
}
Result ContentStorageImpl::ContentIterator::LoadEntries() {
/* If we already have entries loaded, we don't need to do anything. */
R_SUCCEED_IF(m_entry_count != 0);
/* If we have no directories open, there's nothing for us to load. */
if (m_depth == 0) {
m_entry_count = 0;
R_SUCCEED();
}
/* Determine the maximum entries that we can load. */
const s64 max_entries = m_depth == m_max_depth ? MaxDirectoryEntries : 1;
/* Read entries from the current directory. */
s64 num_entries;
R_TRY(fs::ReadDirectory(std::addressof(num_entries), m_entries, m_handles[m_depth - 1], max_entries));
/* If we successfully read entries, load them. */
if (num_entries > 0) {
/* Reverse the order of the loaded entries, for our future convenience. */
for (fs::DirectoryEntry *start_entry = m_entries, *end_entry = m_entries + num_entries - 1; start_entry < end_entry; ++start_entry, --end_entry) {
std::swap(*start_entry, *end_entry);
}
/* Set our entry count. */
m_entry_count = num_entries;
R_SUCCEED();
}
/* We didn't read any entries, so we need to advance to the next directory. */
fs::CloseDirectory(m_handles[--m_depth]);
/* Find the index of the parent directory's substring. */
size_t i = m_path.GetLength() - 1;
while (m_path.Get()[i--] != '/') {
AMS_ABORT_UNLESS(i > 0);
}
/* Set the path to the parent directory. */
m_path = m_path.MakeSubString(0, i + 1);
/* Try to load again from the parent directory. */
R_RETURN(this->LoadEntries());
}
ContentStorageImpl::~ContentStorageImpl() {
this->InvalidateFileCache();
}
Result ContentStorageImpl::InitializeBase(const char *root_path) {
PathString path;
/* Create the content directory. */
MakeBaseContentDirectoryPath(std::addressof(path), root_path);
R_TRY(fs::EnsureDirectory(path));
/* Create the placeholder directory. */
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(path), root_path);
R_RETURN(fs::EnsureDirectory(path));
}
Result ContentStorageImpl::CleanupBase(const char *root_path) {
PathString path;
/* Create the content directory. */
MakeBaseContentDirectoryPath(std::addressof(path), root_path);
R_TRY(CleanDirectoryRecursively(path));
/* Create the placeholder directory. */
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(path), root_path);
R_RETURN(CleanDirectoryRecursively(path));
}
Result ContentStorageImpl::VerifyBase(const char *root_path) {
PathString path;
/* Check if root directory exists. */
bool has_dir;
R_TRY(fs::HasDirectory(std::addressof(has_dir), root_path));
R_UNLESS(has_dir, ncm::ResultContentStorageBaseNotFound());
/* Check if content directory exists. */
bool has_registered;
MakeBaseContentDirectoryPath(std::addressof(path), root_path);
R_TRY(fs::HasDirectory(std::addressof(has_registered), path));
/* Check if placeholder directory exists. */
bool has_placeholder;
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(path), root_path);
R_TRY(fs::HasDirectory(std::addressof(has_placeholder), path));
/* Convert findings to results. */
R_UNLESS(has_registered || has_placeholder, ncm::ResultContentStorageBaseNotFound());
R_UNLESS(has_registered, ncm::ResultInvalidContentStorageBase());
R_UNLESS(has_placeholder, ncm::ResultInvalidContentStorageBase());
R_SUCCEED();
}
void ContentStorageImpl::InvalidateFileCache() {
if (m_cached_content_id != InvalidContentId) {
fs::CloseFile(m_cached_file_handle);
m_cached_content_id = InvalidContentId;
}
m_content_iterator = util::nullopt;
}
Result ContentStorageImpl::OpenContentIdFile(ContentId content_id) {
/* If the file is the currently cached one, we've nothing to do. */
R_SUCCEED_IF(m_cached_content_id == content_id);
/* Close any cached file. */
this->InvalidateFileCache();
/* Create the content path. */
PathString path;
MakeContentPath(std::addressof(path), content_id, m_make_content_path_func, m_root_path);
/* Open the content file and store to the cache. */
R_TRY_CATCH(fs::OpenFile(std::addressof(m_cached_file_handle), path, fs::OpenMode_Read)) {
R_CONVERT(ams::fs::ResultPathNotFound, ncm::ResultContentNotFound())
} R_END_TRY_CATCH;
m_cached_content_id = content_id;
R_SUCCEED();
}
Result ContentStorageImpl::Initialize(const char *path, MakeContentPathFunction content_path_func, MakePlaceHolderPathFunction placeholder_path_func, bool delay_flush, RightsIdCache *rights_id_cache) {
R_TRY(this->EnsureEnabled());
/* Check paths exists for this content storage. */
R_TRY(VerifyBase(path));
/* Initialize members. */
m_root_path = PathString(path);
m_make_content_path_func = content_path_func;
m_placeholder_accessor.Initialize(std::addressof(m_root_path), placeholder_path_func, delay_flush);
m_rights_id_cache = rights_id_cache;
R_SUCCEED();
}
Result ContentStorageImpl::GeneratePlaceHolderId(sf::Out<PlaceHolderId> out) {
R_TRY(this->EnsureEnabled());
out.SetValue({util::GenerateUuid()});
R_SUCCEED();
}
Result ContentStorageImpl::CreatePlaceHolder(PlaceHolderId placeholder_id, ContentId content_id, s64 size) {
R_TRY(this->EnsureEnabled());
R_TRY(EnsureContentDirectory(content_id, m_make_content_path_func, m_root_path));
R_RETURN(m_placeholder_accessor.CreatePlaceHolderFile(placeholder_id, size));
}
Result ContentStorageImpl::DeletePlaceHolder(PlaceHolderId placeholder_id) {
R_TRY(this->EnsureEnabled());
R_RETURN(m_placeholder_accessor.DeletePlaceHolderFile(placeholder_id));
}
Result ContentStorageImpl::HasPlaceHolder(sf::Out<bool> out, PlaceHolderId placeholder_id) {
R_TRY(this->EnsureEnabled());
/* Create the placeholder path. */
PathString placeholder_path;
m_placeholder_accessor.MakePath(std::addressof(placeholder_path), placeholder_id);
/* Check if placeholder file exists. */
bool has = false;
R_TRY(fs::HasFile(std::addressof(has), placeholder_path));
out.SetValue(has);
R_SUCCEED();
}
Result ContentStorageImpl::WritePlaceHolder(PlaceHolderId placeholder_id, s64 offset, const sf::InBuffer &data) {
/* Ensure offset is valid. */
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
R_RETURN(m_placeholder_accessor.WritePlaceHolderFile(placeholder_id, offset, data.GetPointer(), data.GetSize()));
}
Result ContentStorageImpl::Register(PlaceHolderId placeholder_id, ContentId content_id) {
this->InvalidateFileCache();
R_TRY(this->EnsureEnabled());
/* Create the placeholder path. */
PathString placeholder_path;
m_placeholder_accessor.GetPath(std::addressof(placeholder_path), placeholder_id);
/* Create the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Move the placeholder to the content path. */
R_TRY_CATCH(fs::RenameFile(placeholder_path, content_path)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultPlaceHolderNotFound())
R_CONVERT(fs::ResultPathAlreadyExists, ncm::ResultContentAlreadyExists())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result ContentStorageImpl::Delete(ContentId content_id) {
R_TRY(this->EnsureEnabled());
this->InvalidateFileCache();
R_RETURN(DeleteContentFile(content_id, m_make_content_path_func, m_root_path));
}
Result ContentStorageImpl::Has(sf::Out<bool> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Create the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Check if the content file exists. */
bool has = false;
R_TRY(fs::HasFile(std::addressof(has), content_path));
out.SetValue(has);
R_SUCCEED();
}
Result ContentStorageImpl::GetPath(sf::Out<Path> out, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Create the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Substitute our mount name for the common mount name. */
Path common_path;
R_TRY(fs::ConvertToFsCommonPath(common_path.str, sizeof(common_path.str), content_path));
out.SetValue(common_path);
R_SUCCEED();
}
Result ContentStorageImpl::GetPlaceHolderPath(sf::Out<Path> out, PlaceHolderId placeholder_id) {
R_TRY(this->EnsureEnabled());
/* Obtain the placeholder path. */
PathString placeholder_path;
m_placeholder_accessor.GetPath(std::addressof(placeholder_path), placeholder_id);
/* Substitute our mount name for the common mount name. */
Path common_path;
R_TRY(fs::ConvertToFsCommonPath(common_path.str, sizeof(common_path.str), placeholder_path));
out.SetValue(common_path);
R_SUCCEED();
}
Result ContentStorageImpl::CleanupAllPlaceHolder() {
R_TRY(this->EnsureEnabled());
/* Clear the cache. */
m_placeholder_accessor.InvalidateAll();
/* Obtain the placeholder base directory path. */
PathString placeholder_dir;
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(placeholder_dir), m_root_path);
/* Cleanup the placeholder base directory. */
CleanDirectoryRecursively(placeholder_dir);
R_SUCCEED();
}
Result ContentStorageImpl::ListPlaceHolder(sf::Out<s32> out_count, const sf::OutArray<PlaceHolderId> &out_buf) {
R_TRY(this->EnsureEnabled());
/* Obtain the placeholder base directory path. */
PathString placeholder_dir;
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(placeholder_dir), m_root_path);
const size_t max_entries = out_buf.GetSize();
size_t entry_count = 0;
/* Traverse the placeholder base directory finding valid placeholder files. */
R_TRY(TraverseDirectory(placeholder_dir, m_placeholder_accessor.GetHierarchicalDirectoryDepth(), [&](bool *should_continue, bool *should_retry_dir_read, const char *current_path, const fs::DirectoryEntry &entry) -> Result {
AMS_UNUSED(current_path);
*should_continue = true;
*should_retry_dir_read = false;
/* We are only looking for files. */
if (entry.type == fs::DirectoryEntryType_File) {
R_UNLESS(entry_count <= max_entries, ncm::ResultBufferInsufficient());
/* Get the placeholder id from the filename. */
PlaceHolderId placeholder_id;
R_TRY(PlaceHolderAccessor::GetPlaceHolderIdFromFileName(std::addressof(placeholder_id), entry.name));
out_buf[entry_count++] = placeholder_id;
}
R_SUCCEED();
}));
out_count.SetValue(static_cast<s32>(entry_count));
R_SUCCEED();
}
Result ContentStorageImpl::GetContentCount(sf::Out<s32> out_count) {
R_TRY(this->EnsureEnabled());
/* Obtain the content base directory path. */
PathString path;
MakeBaseContentDirectoryPath(std::addressof(path), m_root_path);
const auto depth = GetHierarchicalContentDirectoryDepth(m_make_content_path_func);
size_t count = 0;
/* Traverse the content base directory finding all files. */
R_TRY(TraverseDirectory(path, depth, [&](bool *should_continue, bool *should_retry_dir_read, const char *current_path, const fs::DirectoryEntry &entry) -> Result {
AMS_UNUSED(current_path);
*should_continue = true;
*should_retry_dir_read = false;
/* Increment the count for each file found. */
if (entry.type == fs::DirectoryEntryType_File) {
count++;
}
R_SUCCEED();
}));
out_count.SetValue(static_cast<s32>(count));
R_SUCCEED();
}
Result ContentStorageImpl::ListContentId(sf::Out<s32> out_count, const sf::OutArray<ContentId> &out, s32 offset) {
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
if (!m_content_iterator.has_value() || !m_last_content_offset.has_value() || m_last_content_offset != offset) {
/* Create and initialize the content cache. */
m_content_iterator.emplace();
R_TRY(m_content_iterator->Initialize(m_root_path, GetHierarchicalContentDirectoryDepth(m_make_content_path_func)));
/* Advance to the desired offset. */
for (auto current_offset = 0; current_offset < offset; /* ... */) {
/* Get the next directory entry. */
util::optional<fs::DirectoryEntry> dir_entry;
R_TRY(m_content_iterator->GetNext(std::addressof(dir_entry)));
/* If we run out of entries before reaching the desired offset, we're done. */
if (!dir_entry) {
out_count.SetValue(0);
R_SUCCEED();
}
/* If the current entry is a valid content id, advance. */
if (GetContentIdFromString(dir_entry->name, std::strlen(dir_entry->name))) {
++current_offset;
}
}
}
/* Iterate, reading as many entries as we can. */
s32 count = 0;
while (count < static_cast<s32>(out.GetSize())) {
/* Get the next directory entry. */
util::optional<fs::DirectoryEntry> dir_entry;
R_TRY(m_content_iterator->GetNext(std::addressof(dir_entry)));
/* Don't continue if the directory entry is absent. */
if (!dir_entry) {
break;
}
/* Process the entry, if it's a valid content id. */
if (auto content_id = GetContentIdFromString(dir_entry->name, std::strlen(dir_entry->name)); content_id.has_value()) {
/* Output the content id. */
out[count++] = *content_id;
/* Update our last content offset. */
m_last_content_offset = offset + count;
}
}
/* Set the output count. */
*out_count = count;
R_SUCCEED();
}
Result ContentStorageImpl::GetSizeFromContentId(sf::Out<s64> out_size, ContentId content_id) {
R_TRY(this->EnsureEnabled());
/* Create the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Open the content file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), content_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Obtain the size of the content. */
s64 file_size;
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
out_size.SetValue(file_size);
R_SUCCEED();
}
Result ContentStorageImpl::DisableForcibly() {
m_disabled = true;
this->InvalidateFileCache();
m_placeholder_accessor.InvalidateAll();
R_SUCCEED();
}
Result ContentStorageImpl::RevertToPlaceHolder(PlaceHolderId placeholder_id, ContentId old_content_id, ContentId new_content_id) {
R_TRY(this->EnsureEnabled());
/* Close any cached file. */
this->InvalidateFileCache();
/* Ensure the future content directory exists. */
R_TRY(EnsureContentDirectory(new_content_id, m_make_content_path_func, m_root_path));
/* Ensure the destination placeholder directory exists. */
R_TRY(m_placeholder_accessor.EnsurePlaceHolderDirectory(placeholder_id));
/* Obtain the placeholder path. */
PathString placeholder_path;
m_placeholder_accessor.GetPath(std::addressof(placeholder_path), placeholder_id);
/* Make the old content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), old_content_id, m_make_content_path_func, m_root_path);
/* Move the content to the placeholder path. */
R_TRY_CATCH(fs::RenameFile(content_path, placeholder_path)) {
R_CONVERT(fs::ResultPathNotFound, ncm::ResultPlaceHolderNotFound())
R_CONVERT(fs::ResultPathAlreadyExists, ncm::ResultContentAlreadyExists())
} R_END_TRY_CATCH;
R_SUCCEED();
}
Result ContentStorageImpl::SetPlaceHolderSize(PlaceHolderId placeholder_id, s64 size) {
R_TRY(this->EnsureEnabled());
R_RETURN(m_placeholder_accessor.SetPlaceHolderFileSize(placeholder_id, size));
}
Result ContentStorageImpl::ReadContentIdFile(const sf::OutBuffer &buf, ContentId content_id, s64 offset) {
/* Ensure offset is valid. */
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
/* Create the content path. */
PathString content_path;
MakeContentPath(std::addressof(content_path), content_id, m_make_content_path_func, m_root_path);
/* Open the content file. */
R_TRY(this->OpenContentIdFile(content_id));
/* Read from the requested offset up to the requested size. */
R_RETURN(fs::ReadFile(m_cached_file_handle, offset, buf.GetPointer(), buf.GetSize()));
}
Result ContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
/* Obtain the regular rights id for the placeholder id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromPlaceHolderIdDeprecated2(std::addressof(rights_id), placeholder_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result ContentStorageImpl::GetRightsIdFromPlaceHolderIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id) {
R_RETURN(this->GetRightsIdFromPlaceHolderId(out_rights_id, placeholder_id, fs::ContentAttributes_None));
}
Result ContentStorageImpl::GetRightsIdFromPlaceHolderId(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the placeholder path. */
Path path;
R_TRY(this->GetPlaceHolderPath(std::addressof(path), placeholder_id));
/* Get the rights id for the placeholder id. */
R_RETURN(GetRightsId(out_rights_id.GetPointer(), path, attr));
}
Result ContentStorageImpl::GetRightsIdFromContentIdDeprecated(sf::Out<ams::fs::RightsId> out_rights_id, ContentId content_id) {
/* Obtain the regular rights id for the content id. */
ncm::RightsId rights_id;
R_TRY(this->GetRightsIdFromContentIdDeprecated2(std::addressof(rights_id), content_id));
/* Output the fs rights id. */
out_rights_id.SetValue(rights_id.id);
R_SUCCEED();
}
Result ContentStorageImpl::GetRightsIdFromContentIdDeprecated2(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id) {
R_RETURN(this->GetRightsIdFromContentId(out_rights_id, content_id, fs::ContentAttributes_None));
}
Result ContentStorageImpl::GetRightsIdFromContentId(sf::Out<ncm::RightsId> out_rights_id, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Attempt to obtain the rights id from the cache. */
if (m_rights_id_cache->Find(out_rights_id.GetPointer(), content_id)) {
R_SUCCEED();
}
/* Get the path of the content. */
Path path;
R_TRY(this->GetPath(std::addressof(path), content_id));
/* Obtain the rights id for the content. */
ncm::RightsId rights_id;
R_TRY(GetRightsId(std::addressof(rights_id), path, attr));
/* Store the rights id to the cache. */
m_rights_id_cache->Store(content_id, rights_id);
out_rights_id.SetValue(rights_id);
R_SUCCEED();
}
Result ContentStorageImpl::WriteContentForDebug(ContentId content_id, s64 offset, const sf::InBuffer &data) {
/* Ensure offset is valid. */
R_UNLESS(offset >= 0, ncm::ResultInvalidOffset());
R_TRY(this->EnsureEnabled());
/* This command is for development hardware only. */
AMS_ABORT_UNLESS(spl::IsDevelopment());
/* Close any cached file. */
this->InvalidateFileCache();
/* Make the content path. */
PathString path;
MakeContentPath(std::addressof(path), content_id, m_make_content_path_func, m_root_path);
/* Open the content file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), path.Get(), fs::OpenMode_Write));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Write the provided data to the file. */
R_RETURN(fs::WriteFile(file, offset, data.GetPointer(), data.GetSize(), fs::WriteOption::Flush));
}
Result ContentStorageImpl::GetFreeSpaceSize(sf::Out<s64> out_size) {
R_RETURN(fs::GetFreeSpaceSize(out_size.GetPointer(), m_root_path));
}
Result ContentStorageImpl::GetTotalSpaceSize(sf::Out<s64> out_size) {
R_RETURN(fs::GetTotalSpaceSize(out_size.GetPointer(), m_root_path));
}
Result ContentStorageImpl::FlushPlaceHolder() {
m_placeholder_accessor.InvalidateAll();
R_SUCCEED();
}
Result ContentStorageImpl::GetSizeFromPlaceHolderId(sf::Out<s64> out_size, PlaceHolderId placeholder_id) {
R_TRY(this->EnsureEnabled());
/* Attempt to get the placeholder file size. */
bool found = false;
s64 file_size = 0;
R_TRY(m_placeholder_accessor.TryGetPlaceHolderFileSize(std::addressof(found), std::addressof(file_size), placeholder_id));
/* Set the output if placeholder file is found. */
if (found) {
out_size.SetValue(file_size);
R_SUCCEED();
}
/* Get the path of the placeholder. */
PathString placeholder_path;
m_placeholder_accessor.GetPath(std::addressof(placeholder_path), placeholder_id);
/* Open the placeholder file. */
fs::FileHandle file;
R_TRY(fs::OpenFile(std::addressof(file), placeholder_path, fs::OpenMode_Read));
ON_SCOPE_EXIT { fs::CloseFile(file); };
/* Get the size of the placeholder file. */
R_TRY(fs::GetFileSize(std::addressof(file_size), file));
out_size.SetValue(file_size);
R_SUCCEED();
}
Result ContentStorageImpl::RepairInvalidFileAttribute() {
/* Callback for TraverseDirectory */
using PathChecker = bool (*)(const char *);
PathChecker path_checker = nullptr;
/* Set the archive bit appropriately for content/placeholders. */
auto fix_file_attributes = [&](bool *should_continue, bool *should_retry_dir_read, const char *current_path, const fs::DirectoryEntry &entry) {
*should_retry_dir_read = false;
*should_continue = true;
if (entry.type == fs::DirectoryEntryType_Directory) {
if (path_checker(current_path)) {
if (R_SUCCEEDED(fs::SetConcatenationFileAttribute(current_path))) {
*should_retry_dir_read = true;
}
}
}
R_SUCCEED();
};
/* Fix content. */
{
path_checker = IsContentPath;
PathString path;
MakeBaseContentDirectoryPath(std::addressof(path), m_root_path);
R_TRY(TraverseDirectory(path, GetHierarchicalContentDirectoryDepth(m_make_content_path_func), fix_file_attributes));
}
/* Fix placeholders. */
m_placeholder_accessor.InvalidateAll();
{
path_checker = IsPlaceHolderPath;
PathString path;
PlaceHolderAccessor::MakeBaseDirectoryPath(std::addressof(path), m_root_path);
R_TRY(TraverseDirectory(path, GetHierarchicalContentDirectoryDepth(m_make_content_path_func), fix_file_attributes));
}
R_SUCCEED();
}
Result ContentStorageImpl::GetRightsIdFromPlaceHolderIdWithCache(sf::Out<ncm::RightsId> out_rights_id, PlaceHolderId placeholder_id, ContentId cache_content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Attempt to find the rights id in the cache. */
if (m_rights_id_cache->Find(out_rights_id.GetPointer(), cache_content_id)) {
R_SUCCEED();
}
/* Get the placeholder path. */
PathString placeholder_path;
m_placeholder_accessor.GetPath(std::addressof(placeholder_path), placeholder_id);
/* Substitute mount name with the common mount name. */
Path common_path;
R_TRY(fs::ConvertToFsCommonPath(common_path.str, sizeof(common_path.str), placeholder_path));
/* Get the rights id. */
ncm::RightsId rights_id;
R_TRY(GetRightsId(std::addressof(rights_id), common_path, attr));
m_rights_id_cache->Store(cache_content_id, rights_id);
/* Set output. */
out_rights_id.SetValue(rights_id);
R_SUCCEED();
}
Result ContentStorageImpl::RegisterPath(const ContentId &content_id, const Path &path) {
AMS_UNUSED(content_id, path);
R_THROW(ncm::ResultInvalidOperation());
}
Result ContentStorageImpl::ClearRegisteredPath() {
R_THROW(ncm::ResultInvalidOperation());
}
Result ContentStorageImpl::GetProgramId(sf::Out<ncm::ProgramId> out, ContentId content_id, fs::ContentAttributes attr) {
R_TRY(this->EnsureEnabled());
/* Get the path of the content. */
Path path;
R_TRY(this->GetPath(std::addressof(path), content_id));
/* Obtain the program id for the content. */
ncm::ProgramId program_id;
R_TRY(fs::GetProgramId(std::addressof(program_id), path.str, attr));
out.SetValue(program_id);
R_SUCCEED();
}
}
| 36,549
|
C++
|
.cpp
| 724
| 39.838398
| 231
| 0.617555
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,865
|
gc_embedded_data_holder.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gc/impl/gc_embedded_data_holder.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::gc::impl {
namespace {
constexpr const u8 LibraryEmbeddedCa1Modulus[GcCrypto::GcRsaKeyLength] = {
0xAF, 0xB6, 0xA0, 0x1F, 0x7F, 0x8C, 0xEC, 0xD6, 0x62, 0xC9, 0xF9, 0x83, 0x69, 0x4F, 0x0E, 0x8E,
0xC3, 0x71, 0x70, 0x60, 0x63, 0xEB, 0x90, 0x2F, 0x1E, 0x3B, 0xA2, 0xCD, 0xD5, 0x7A, 0xAA, 0x45,
0x27, 0x61, 0xF9, 0x10, 0xC0, 0x0C, 0x72, 0xE7, 0xBD, 0x70, 0x2E, 0x32, 0xA0, 0xD0, 0x8A, 0x29,
0x43, 0x19, 0x12, 0x8C, 0x8D, 0x10, 0xE4, 0x04, 0xE0, 0x13, 0x7F, 0x26, 0x02, 0x1B, 0xFD, 0x44,
0xAF, 0x70, 0xD7, 0xBF, 0xDF, 0x97, 0xD2, 0x34, 0xFD, 0xBB, 0x51, 0x8D, 0x7C, 0x04, 0x9D, 0x30,
0xFF, 0xB1, 0xB4, 0xD3, 0xEF, 0x2C, 0xEE, 0xAD, 0x4C, 0x4A, 0x26, 0x94, 0x15, 0x13, 0xA9, 0xDA,
0xF4, 0xA4, 0x22, 0xE7, 0x11, 0x8A, 0xE4, 0xB0, 0xE9, 0x66, 0x23, 0xA7, 0xED, 0x7D, 0x73, 0x8B,
0x32, 0xE5, 0xE1, 0x19, 0x34, 0x15, 0x06, 0x5D, 0xA6, 0xCD, 0x80, 0xA5, 0xC0, 0xD0, 0xCE, 0x7C,
0x3E, 0x3D, 0x1F, 0x2B, 0x65, 0x26, 0xBE, 0xAE, 0x55, 0xC7, 0x03, 0xCF, 0x4A, 0xD3, 0xDA, 0x54,
0x13, 0x1F, 0x20, 0x05, 0xE9, 0x9B, 0x3F, 0xDE, 0x73, 0xD3, 0xA0, 0xFF, 0xA0, 0x7E, 0xA9, 0x6A,
0xBC, 0xF8, 0x6C, 0xF1, 0x3C, 0x72, 0x4E, 0x6F, 0xA1, 0x3C, 0x20, 0xCD, 0x3A, 0x1A, 0x65, 0xE0,
0xF0, 0xF8, 0x84, 0xEB, 0x6B, 0x38, 0x49, 0xB6, 0xF2, 0x5B, 0x81, 0x16, 0x8B, 0x1A, 0xE0, 0x4F,
0x18, 0x88, 0xF1, 0xAD, 0x66, 0xA9, 0xC8, 0xE0, 0x9D, 0xD0, 0x9B, 0xFA, 0xAD, 0xBE, 0xC9, 0x5C,
0xE5, 0x54, 0x2A, 0xF4, 0x59, 0xE2, 0xFA, 0xD4, 0xC9, 0x58, 0x1C, 0x83, 0xD9, 0x23, 0x77, 0xDC,
0x78, 0xBE, 0xCA, 0x7B, 0xC1, 0x69, 0xF3, 0x9C, 0xFE, 0xF7, 0xB9, 0x9E, 0xD6, 0x44, 0x70, 0x1C,
0x8B, 0x08, 0xB0, 0x44, 0xE5, 0x63, 0xFB, 0xB8, 0x45, 0x40, 0xDA, 0xA2, 0x3C, 0xB9, 0xFB, 0x75,
};
constexpr const u8 LibraryEmbeddedCa9Modulus[GcCrypto::GcRsaKeyLength] = {
0xCD, 0xF3, 0x2C, 0xB0, 0xF5, 0x14, 0x78, 0x34, 0xE5, 0x02, 0xD0, 0x29, 0x6A, 0xA5, 0xFD, 0x97,
0x6A, 0xE0, 0xB0, 0xBB, 0xB0, 0x3B, 0x1A, 0x80, 0xB7, 0xD7, 0x58, 0x92, 0x79, 0x84, 0xC0, 0x36,
0xB1, 0x55, 0x23, 0xD8, 0xA5, 0x60, 0x91, 0x26, 0x48, 0x1A, 0x80, 0x4A, 0xEA, 0x00, 0x98, 0x2A,
0xEC, 0x52, 0x17, 0x72, 0x92, 0x4D, 0xF5, 0x42, 0xA7, 0x8A, 0x6F, 0x7F, 0xD2, 0x48, 0x51, 0x8E,
0xDF, 0xCB, 0xBF, 0x77, 0xF6, 0x18, 0xBD, 0xE5, 0x00, 0xD9, 0x70, 0x8C, 0xEF, 0x57, 0xB2, 0x96,
0xD0, 0x36, 0x83, 0x88, 0x9C, 0xC5, 0xFB, 0xA0, 0x33, 0x81, 0xA2, 0x12, 0x23, 0xC6, 0xC7, 0x86,
0x0A, 0x98, 0x57, 0x4D, 0x2E, 0xB5, 0xAE, 0x64, 0xE4, 0x6F, 0xC2, 0xC5, 0xAC, 0x6A, 0x1D, 0xDB,
0xA5, 0xAF, 0x12, 0x22, 0xAB, 0x1F, 0x51, 0xC8, 0x0E, 0x0D, 0xC9, 0xF5, 0x03, 0xE8, 0xD2, 0xFC,
0x84, 0x62, 0x26, 0x55, 0xA4, 0xC3, 0xE2, 0xA8, 0x98, 0x05, 0x67, 0x23, 0xFD, 0xA5, 0x46, 0x40,
0x78, 0x51, 0x09, 0x3D, 0x91, 0x74, 0xD6, 0xD0, 0x54, 0x23, 0x0D, 0xA0, 0xFB, 0x07, 0xD0, 0xAA,
0x9D, 0x50, 0x4E, 0x2B, 0x26, 0x9A, 0x14, 0xE5, 0x6C, 0x73, 0x66, 0x24, 0x18, 0xA1, 0x93, 0x9C,
0x2A, 0x40, 0x40, 0x05, 0x6B, 0xF1, 0x45, 0xDF, 0x22, 0x8B, 0x40, 0x61, 0xA4, 0x11, 0x06, 0x03,
0xA5, 0x53, 0x84, 0xC0, 0x12, 0xE1, 0x88, 0x9D, 0x55, 0x55, 0x07, 0x40, 0x88, 0x01, 0x8C, 0xAB,
0xA2, 0xFD, 0xFD, 0x19, 0x48, 0x25, 0xAB, 0x59, 0x59, 0x28, 0x63, 0x68, 0x69, 0x1B, 0x99, 0x73,
0x8D, 0xAB, 0x5A, 0xFA, 0x71, 0x60, 0x1B, 0x12, 0xE7, 0x99, 0x70, 0xF1, 0x99, 0x2A, 0x50, 0x18,
0x8B, 0x6B, 0x61, 0x90, 0xE2, 0x7E, 0x8B, 0x90, 0xD4, 0xD5, 0xC0, 0xCB, 0x7C, 0x08, 0x06, 0xD9,
};
constexpr const u8 LibraryEmbeddedCaPublicExponent[GcCrypto::GcRsaPublicExponentLength] = {
0x01, 0x00, 0x01
};
constexpr const u8 LibraryEmbeddedCa10Modulus[2][GcCrypto::GcRsaKeyLength] = {
{
0x98, 0xC7, 0x26, 0xB6, 0x0D, 0x0A, 0x50, 0xA7, 0x39, 0x21, 0x0A, 0xE3, 0x2F, 0xE4, 0x3E, 0x2E,
0x5B, 0xA2, 0x86, 0x75, 0xAA, 0x5C, 0xEE, 0x34, 0xF1, 0xA3, 0x3A, 0x7E, 0xBD, 0x90, 0x4E, 0xF7,
0x8D, 0xFA, 0x17, 0xAA, 0x6B, 0xC6, 0x36, 0x6D, 0x4C, 0x9A, 0x6D, 0x57, 0x2F, 0x80, 0xA2, 0xBC,
0x38, 0x4D, 0xDA, 0x99, 0xA1, 0xD8, 0xC3, 0xE2, 0x99, 0x79, 0x36, 0x71, 0x90, 0x20, 0x25, 0x9D,
0x4D, 0x11, 0xB8, 0x2E, 0x63, 0x6B, 0x5A, 0xFA, 0x1E, 0x9C, 0x04, 0xD1, 0xC5, 0xF0, 0x9C, 0xB1,
0x0F, 0xB8, 0xC1, 0x7B, 0xBF, 0xE8, 0xB0, 0xD2, 0x2B, 0x47, 0x01, 0x22, 0x6B, 0x23, 0xC9, 0xD0,
0xBC, 0xEB, 0x75, 0x6E, 0x41, 0x7D, 0x4C, 0x26, 0xA4, 0x73, 0x21, 0xB4, 0xF0, 0x14, 0xE5, 0xD9,
0x8D, 0xB3, 0x64, 0xEE, 0xA8, 0xFA, 0x84, 0x1B, 0xB8, 0xB8, 0x7C, 0x88, 0x6B, 0xEF, 0xCC, 0x97,
0x04, 0x04, 0x9A, 0x67, 0x2F, 0xDF, 0xEC, 0x0D, 0xB2, 0x5F, 0xB5, 0xB2, 0xBD, 0xB5, 0x4B, 0xDE,
0x0E, 0x88, 0xA3, 0xBA, 0xD1, 0xB4, 0xE0, 0x91, 0x81, 0xA7, 0x84, 0xEB, 0x77, 0x85, 0x8B, 0xEF,
0xA5, 0xE3, 0x27, 0xB2, 0xF2, 0x82, 0x2B, 0x29, 0xF1, 0x75, 0x2D, 0xCE, 0xCC, 0xAE, 0x9B, 0x8D,
0xED, 0x5C, 0xF1, 0x8E, 0xDB, 0x9A, 0xD7, 0xAF, 0x42, 0x14, 0x52, 0xCD, 0xE3, 0xC5, 0xDD, 0xCE,
0x08, 0x12, 0x17, 0xD0, 0x7F, 0x1A, 0xAA, 0x1F, 0x7D, 0xE0, 0x93, 0x54, 0xC8, 0xBC, 0x73, 0x8A,
0xCB, 0xAD, 0x6E, 0x93, 0xE2, 0x19, 0x72, 0x6B, 0xD3, 0x45, 0xF8, 0x73, 0x3D, 0x2B, 0x6A, 0x55,
0xD2, 0x3A, 0x8B, 0xB0, 0x8A, 0x42, 0xE3, 0x3D, 0xF1, 0x92, 0x23, 0x42, 0x2E, 0xBA, 0xCC, 0x9C,
0x9A, 0xC1, 0xDD, 0x62, 0x86, 0x9C, 0x2E, 0xE1, 0x2D, 0x6F, 0x62, 0x67, 0x51, 0x08, 0x0E, 0xCF,
},
{
0xC8, 0x65, 0x8D, 0x9D, 0x15, 0xF4, 0xCC, 0x35, 0x7D, 0x3C, 0x7B, 0xBF, 0xA3, 0x7D, 0xA9, 0xFE,
0x93, 0xD9, 0x3A, 0x64, 0x7C, 0x12, 0x81, 0xB8, 0xA7, 0x6D, 0xE6, 0x76, 0xA5, 0x9F, 0x95, 0xB1,
0x0B, 0xC5, 0x93, 0x9F, 0x48, 0xE9, 0x4F, 0x3D, 0xD1, 0x94, 0x0F, 0x78, 0x70, 0x5A, 0x2C, 0x82,
0x6C, 0xE9, 0xB0, 0xA7, 0x6C, 0xEA, 0xB5, 0xC1, 0x20, 0xD0, 0x2A, 0x29, 0x42, 0xA6, 0x33, 0x70,
0x75, 0x53, 0x3E, 0x88, 0x4A, 0xEF, 0x35, 0x0E, 0x79, 0xE4, 0xB0, 0x0F, 0x90, 0xA2, 0xAC, 0xF8,
0x31, 0x02, 0xA3, 0x8E, 0x99, 0x7E, 0xF4, 0x72, 0x5A, 0x0B, 0xE8, 0x23, 0x4E, 0x87, 0xFB, 0x2F,
0x22, 0x22, 0x57, 0xF6, 0xE1, 0x43, 0xFD, 0x11, 0xDA, 0x2D, 0xE6, 0x25, 0x96, 0x4C, 0x6B, 0x3B,
0x54, 0x0C, 0x22, 0x8C, 0xB5, 0x82, 0xDB, 0x49, 0x5C, 0xB0, 0x36, 0x13, 0x31, 0x6F, 0x1A, 0xFF,
0xA5, 0x1F, 0x70, 0x15, 0xAC, 0xDA, 0xF5, 0xD6, 0xE5, 0x71, 0x2F, 0x47, 0x43, 0xAB, 0x00, 0x03,
0xCE, 0x9C, 0x70, 0xEB, 0x58, 0x6C, 0xE1, 0x3F, 0xC8, 0xD7, 0x43, 0xDA, 0x34, 0xDD, 0x23, 0x76,
0xE3, 0x39, 0xB6, 0x8E, 0x5D, 0x63, 0xD6, 0xDD, 0x42, 0x5B, 0xB4, 0x58, 0xCF, 0x2D, 0x47, 0x61,
0x2F, 0x3F, 0xC3, 0x20, 0xF5, 0xD6, 0xDB, 0xFD, 0x75, 0xCB, 0x06, 0xBC, 0x94, 0x4E, 0xE5, 0x3D,
0xC8, 0x70, 0xC6, 0xCB, 0xB9, 0xE0, 0x9B, 0x0F, 0x32, 0xA4, 0xC3, 0xCA, 0x46, 0x8C, 0x44, 0x2D,
0x2E, 0x71, 0xC8, 0xF0, 0x51, 0x17, 0x94, 0x5D, 0x40, 0xE2, 0x31, 0x9A, 0x24, 0x9F, 0x7C, 0xC5,
0xDC, 0xB9, 0xB4, 0x43, 0x23, 0x70, 0xF7, 0x73, 0x0A, 0x5A, 0x6B, 0x8D, 0x9C, 0x76, 0xB1, 0x23,
0x49, 0x35, 0x4E, 0x3E, 0x92, 0x22, 0xDF, 0xBB, 0x5E, 0xF4, 0x9E, 0x98, 0xCF, 0x51, 0xBE, 0xDF,
},
};
constexpr const u8 LibraryEmbeddedCa10CertificateModulus[2][GcCrypto::GcRsaKeyLength] = {
{
0xAA, 0x9B, 0x6C, 0xE2, 0x50, 0xE5, 0xEC, 0x25, 0xEE, 0x2D, 0x21, 0x9C, 0xB7, 0x4F, 0xA2, 0x72,
0x1E, 0x44, 0xB7, 0xFC, 0x65, 0x86, 0xAC, 0x81, 0xCC, 0x09, 0xDC, 0xAD, 0xB7, 0x68, 0x37, 0x52,
0x72, 0x81, 0xD5, 0xBA, 0x72, 0x11, 0x41, 0x71, 0x98, 0x46, 0xA9, 0x47, 0xF6, 0x95, 0x9D, 0x9B,
0x5E, 0xCA, 0x07, 0x5A, 0x57, 0xE0, 0xAB, 0x2E, 0xDB, 0xE5, 0xF3, 0x01, 0x3B, 0xBB, 0x2B, 0x2E,
0x44, 0x31, 0xA3, 0x0B, 0x2F, 0x3A, 0x51, 0xC4, 0x6B, 0x64, 0xD8, 0xF1, 0x01, 0x2D, 0xE9, 0xE8,
0x86, 0x30, 0xAC, 0xF8, 0x02, 0xA3, 0x5A, 0xBE, 0x60, 0xFB, 0x5C, 0x1C, 0x39, 0x7C, 0x8B, 0x4F,
0xBF, 0xE2, 0xDF, 0x1E, 0xF2, 0x69, 0x4E, 0xA3, 0x6A, 0x6C, 0x69, 0x97, 0xDD, 0xF1, 0xB2, 0x14,
0x63, 0x8F, 0xDD, 0x94, 0xC5, 0x7D, 0x73, 0xF6, 0xE1, 0xDA, 0x0C, 0xD5, 0x8B, 0x69, 0x76, 0x06,
0xC1, 0xE7, 0x61, 0x1C, 0x4B, 0xF2, 0x5B, 0x18, 0x6B, 0xB0, 0x05, 0x34, 0x2C, 0x4C, 0xAB, 0x45,
0xF3, 0x88, 0x2E, 0x71, 0xFD, 0x7A, 0x7F, 0xC3, 0x0D, 0xB4, 0xB4, 0x71, 0xDF, 0xEE, 0x9A, 0xAA,
0x1E, 0x26, 0xD5, 0x17, 0x43, 0x6A, 0x6B, 0x4E, 0x93, 0xA2, 0xEE, 0x88, 0xAB, 0x5E, 0xFB, 0x68,
0x32, 0x78, 0xB3, 0xF7, 0xA5, 0x16, 0x1C, 0x19, 0x6A, 0x66, 0xA4, 0xE3, 0x97, 0x8F, 0x7B, 0x19,
0x1D, 0xE4, 0x2D, 0x50, 0x09, 0x41, 0x4A, 0x77, 0xF7, 0xA0, 0xBD, 0xEE, 0x99, 0x18, 0x9B, 0xA7,
0x67, 0xFF, 0x67, 0xF6, 0xDA, 0xD0, 0x31, 0xEF, 0x8E, 0x4F, 0x1C, 0xC6, 0xBA, 0xC6, 0xC4, 0x3D,
0x81, 0xB9, 0xFD, 0x9F, 0x2E, 0xF0, 0x4C, 0x50, 0x05, 0x9D, 0x08, 0x45, 0xA2, 0x15, 0x35, 0xE9,
0xC2, 0xED, 0xFD, 0x2F, 0xF7, 0xD3, 0xA8, 0x39, 0xD5, 0xD2, 0xF4, 0x79, 0x58, 0x76, 0x43, 0xCB,
},
{
0xC5, 0x42, 0x7B, 0x81, 0x51, 0x70, 0x8B, 0x84, 0xBD, 0x16, 0x21, 0x37, 0x9E, 0xBC, 0x54, 0xEC,
0x97, 0xFB, 0x16, 0x81, 0x77, 0x5B, 0x67, 0x02, 0xE5, 0x7E, 0x06, 0x60, 0xC9, 0x3B, 0x4B, 0x98,
0xB1, 0xEB, 0xE2, 0xA6, 0x46, 0xA5, 0xBB, 0xD1, 0x8A, 0xF4, 0xAB, 0x6D, 0x60, 0xD0, 0xC3, 0xFD,
0xE5, 0x9F, 0x80, 0xA4, 0xA5, 0xDF, 0xD2, 0xAD, 0x64, 0x8E, 0xB4, 0x72, 0x22, 0x95, 0xDB, 0x5F,
0xB1, 0x38, 0x43, 0x1C, 0x25, 0xFE, 0x73, 0x10, 0xF4, 0xB8, 0xBD, 0xAA, 0xCF, 0x1A, 0x12, 0x1F,
0x7C, 0xED, 0x72, 0x3E, 0xCC, 0xF9, 0x75, 0x28, 0x21, 0x83, 0x74, 0x92, 0x72, 0xD4, 0xD5, 0x01,
0x59, 0x2A, 0x7A, 0x6F, 0x80, 0xA3, 0xA5, 0x63, 0xD5, 0x09, 0x36, 0xCE, 0x0C, 0x3F, 0xCF, 0x08,
0x10, 0x29, 0xEE, 0xB9, 0xB1, 0xE2, 0x79, 0x02, 0xEC, 0xE8, 0x51, 0x72, 0x4D, 0x60, 0xE4, 0xAC,
0x76, 0x23, 0x06, 0x45, 0x6F, 0x02, 0xDB, 0x7A, 0xBC, 0x46, 0xC4, 0xF8, 0x3E, 0xC2, 0x1B, 0x9C,
0x6A, 0xC3, 0x37, 0xE7, 0xC2, 0x85, 0x80, 0xA6, 0xB1, 0x41, 0xC6, 0x43, 0x2A, 0xD9, 0x45, 0x63,
0x4D, 0x8E, 0xCB, 0xA2, 0x79, 0x54, 0x94, 0x54, 0xE7, 0x34, 0xEA, 0xAD, 0xE9, 0x47, 0x52, 0x6C,
0x96, 0x22, 0xF2, 0xD6, 0xDC, 0xB7, 0x45, 0x03, 0xB6, 0xC8, 0x36, 0x92, 0x10, 0x4A, 0x40, 0x2B,
0x05, 0x34, 0x78, 0x2A, 0xAD, 0x6A, 0x8E, 0x7F, 0xA1, 0x22, 0x3A, 0xC5, 0xD1, 0x0A, 0x4D, 0xD8,
0x7A, 0x9A, 0x53, 0x9A, 0x00, 0xAF, 0x70, 0x76, 0xC1, 0xF9, 0x9C, 0x98, 0x02, 0xCB, 0x4C, 0xF5,
0x9E, 0x51, 0x29, 0x72, 0x4C, 0x13, 0x45, 0xCA, 0xB1, 0xA4, 0x4A, 0x4E, 0x32, 0xCC, 0x23, 0xA8,
0x69, 0xBE, 0x82, 0xD5, 0x86, 0x22, 0xA5, 0xEE, 0x97, 0x1A, 0xFF, 0x11, 0xF0, 0xE7, 0x66, 0x0B,
},
};
constexpr const u8 LibraryEmbeddedCardHeaderKey[2][GcCrypto::GcAesKeyLength] = {
{ 0x01, 0xC5, 0x8F, 0xE7, 0x00, 0x2D, 0x13, 0x5A, 0xB2, 0x9A, 0x3F, 0x69, 0x33, 0x95, 0x74, 0xB1, },
{ 0xCB, 0xA7, 0xB8, 0x75, 0xEB, 0x67, 0x05, 0xFB, 0x46, 0x0A, 0x33, 0xFD, 0x34, 0x09, 0x13, 0xB4, },
};
constexpr const u8 LibraryEmbeddedConcatenatedGcKeys[2][0x70] = {
{
0x98, 0x42, 0xD1, 0x45, 0x92, 0xEE, 0x79, 0xAE, 0xE3, 0xAA, 0xC9, 0xEA, 0x6A, 0x67, 0xC4, 0xB4,
0x5E, 0x18, 0x1E, 0x0C, 0xC0, 0xA2, 0x1C, 0x0E, 0x05, 0xA4, 0x49, 0x30, 0x53, 0x7F, 0xC8, 0xE2,
0xB9, 0xFB, 0x97, 0x31, 0x0A, 0x4E, 0x28, 0xE7, 0x1E, 0x69, 0x8C, 0xEE, 0xED, 0x26, 0x20, 0x14,
0x63, 0x76, 0xBC, 0x1D, 0x86, 0xED, 0x11, 0x01, 0x4D, 0xB0, 0xFC, 0x88, 0xD4, 0x64, 0x15, 0x03,
0x68, 0x95, 0x4D, 0x5A, 0x87, 0x57, 0x81, 0xB6, 0x6C, 0xD1, 0xEF, 0x40, 0x9D, 0x74, 0xF1, 0xA5,
0xDA, 0xCA, 0x1F, 0x3E, 0x78, 0x96, 0xCA, 0x2F, 0x1A, 0x47, 0xA3, 0x19, 0x47, 0x47, 0xC4, 0x54,
0x5C, 0x97, 0x02, 0x74, 0xF2, 0x69, 0xA2, 0x14, 0x46, 0xFC, 0x5B, 0x21, 0x85, 0x29, 0xCB, 0x16,
},
{
0xE8, 0x17, 0xE6, 0x0B, 0xE2, 0x6C, 0x32, 0x30, 0x45, 0xF7, 0xBA, 0x8D, 0xBD, 0x99, 0x15, 0x62,
0xD1, 0x1C, 0x1C, 0x2C, 0x42, 0xC1, 0x2E, 0x1B, 0x4A, 0xF1, 0x65, 0x3B, 0x0D, 0x37, 0xF3, 0xC6,
0x91, 0xB2, 0x5C, 0x22, 0xB9, 0x47, 0xF1, 0x15, 0xB0, 0xEE, 0x16, 0xC5, 0x3F, 0xCC, 0x58, 0xD6,
0xA6, 0xAC, 0x06, 0x47, 0x3A, 0xA0, 0x9B, 0x12, 0xE2, 0x50, 0x80, 0x13, 0x49, 0x2C, 0x3C, 0xED,
0x35, 0x5B, 0xA3, 0x6D, 0x26, 0x1E, 0xF6, 0xC9, 0xFA, 0xD2, 0x43, 0x81, 0x5A, 0xD0, 0x22, 0x75,
0x78, 0x5A, 0x92, 0xE4, 0x91, 0x49, 0xD8, 0x28, 0x57, 0x57, 0x49, 0x68, 0x01, 0x0E, 0xA4, 0x10,
0x5B, 0x05, 0x47, 0x03, 0xD1, 0x1B, 0xA7, 0xCA, 0xD9, 0x06, 0x10, 0x02, 0x85, 0xA3, 0x99, 0x26,
},
};
constexpr const u8 LibraryEmbeddedSplEncryptedKek[GcCrypto::GcAesKeyLength] = {
0x42, 0xF1, 0xEB, 0xCB, 0xDD, 0xED, 0x82, 0xAF, 0x32, 0x4E, 0x0D, 0xF4, 0x84, 0xF2, 0xAB, 0x57,
};
constexpr const u8 LibraryEmbeddedIvForKek[2][GcCrypto::GcAesCbcIvLength] = {
{ 0xC6, 0x09, 0x0A, 0x32, 0x51, 0xA5, 0x26, 0xEC, 0x8F, 0x2B, 0xA9, 0x3E, 0xCC, 0x62, 0xF0, 0x92 },
{ 0x23, 0xA6, 0xFE, 0x53, 0xE7, 0x16, 0x86, 0xFB, 0x9B, 0xB5, 0x72, 0x32, 0x42, 0x01, 0xA3, 0xC7 },
};
}
constinit bool EmbeddedDataHolder::s_is_dev = false;
constinit const void *EmbeddedDataHolder::s_ca_public_exponent = LibraryEmbeddedCaPublicExponent;
constinit const void *EmbeddedDataHolder::s_ca1_modulus = LibraryEmbeddedCa1Modulus;
constinit const void *EmbeddedDataHolder::s_ca9_modulus = LibraryEmbeddedCa9Modulus;
constinit const void *EmbeddedDataHolder::s_ca10_modulus = LibraryEmbeddedCa10Modulus[0];
constinit const void *EmbeddedDataHolder::s_ca10_certificate_modulus = LibraryEmbeddedCa10CertificateModulus[0];
constinit const void *EmbeddedDataHolder::s_card_header_key = LibraryEmbeddedCardHeaderKey[0];
Result EmbeddedDataHolder::SetLibraryEmbeddedKeys(bool is_dev) {
ConcatenatedGcLibraryEmbeddedKeys embedded_keys;
R_TRY(DecryptoEmbeddedKeys(std::addressof(embedded_keys), sizeof(embedded_keys), is_dev));
{
/* TODO: Set hmac/cv keys. */
AMS_UNUSED(embedded_keys);
}
R_SUCCEED();
}
Result EmbeddedDataHolder::DecryptoEmbeddedKeys(ConcatenatedGcLibraryEmbeddedKeys *out, size_t out_size, bool is_dev) {
/* Determine key index. */
const auto key_idx = is_dev ? 1 : 0;
/* Set global pointers. */
s_is_dev = is_dev;
s_ca10_modulus = LibraryEmbeddedCa10Modulus[key_idx];
s_ca10_certificate_modulus = LibraryEmbeddedCa10CertificateModulus[key_idx];
s_card_header_key = LibraryEmbeddedCardHeaderKey[key_idx];
/* Get the keys/iv. */
ConcatenatedGcLibraryEmbeddedKeys keys;
std::memcpy(std::addressof(keys), LibraryEmbeddedConcatenatedGcKeys[key_idx], sizeof(keys));
static_assert(sizeof(LibraryEmbeddedConcatenatedGcKeys[0]) == sizeof(*out));
const void *iv_for_kek = LibraryEmbeddedIvForKek[key_idx];
/* Generate the kek. */
u8 kek[GcCrypto::GcAesKeyLength] = {};
crypto::Aes128CtrDecryptor aes_ctr;
ON_SCOPE_EXIT {
crypto::ClearMemory(kek, sizeof(kek));
aes_ctr.Initialize(kek, sizeof(kek), iv_for_kek, GcCrypto::GcAesCbcIvLength);
};
constexpr const auto KeyGeneration = 4;
R_TRY(GcCrypto::DecryptAesKeySpl(kek, sizeof(kek), LibraryEmbeddedSplEncryptedKek, sizeof(LibraryEmbeddedSplEncryptedKek), KeyGeneration, 0));
/* Decrypt the embedded keys. */
aes_ctr.Initialize(kek, sizeof(kek), iv_for_kek, GcCrypto::GcAesCbcIvLength);
aes_ctr.Update(out, out_size, std::addressof(keys), sizeof(keys));
R_SUCCEED();
}
}
| 17,210
|
C++
|
.cpp
| 209
| 70.07177
| 150
| 0.603535
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,866
|
gc_gc_crypto.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/gc/impl/gc_gc_crypto.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::gc::impl {
bool GcCrypto::CheckDevelopmentSpl() {
return spl::IsDevelopment();
}
Result GcCrypto::DecryptAesKeySpl(void *dst, size_t dst_size, const void *src, size_t src_size, s32 generation, u32 option) {
R_UNLESS(R_SUCCEEDED(spl::DecryptAesKey(dst, dst_size, src, src_size, generation, option)), fs::ResultGameCardSplDecryptAesKeyFailure());
R_SUCCEED();
}
Result GcCrypto::VerifyCardHeader(const void *header_buffer, size_t header_size, const void *modulus, size_t modulus_size) {
/* Check pre-conditions. */
AMS_ABORT_UNLESS(header_size == sizeof(CardHeaderWithSignature));
AMS_ABORT_UNLESS(modulus_size == GcRsaKeyLength);
/* Get cert buffer as type. */
const auto * const header = static_cast<const CardHeaderWithSignature *>(header_buffer);
/* Verify the signature. */
const void *mod = modulus != nullptr ? modulus : EmbeddedDataHolder::s_ca10_modulus;
const size_t mod_size = GcRsaKeyLength;
const void *exp = EmbeddedDataHolder::s_ca_public_exponent;
const size_t exp_size = GcRsaPublicExponentLength;
const void *sig = header->signature;
const size_t sig_size = sizeof(header->signature);
const void *msg = std::addressof(header->data);
const size_t msg_size = sizeof(header->data);
const bool is_signature_valid = crypto::VerifyRsa2048Pkcs1Sha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size);
R_UNLESS(is_signature_valid, fs::ResultGameCardInvalidCardHeader());
R_SUCCEED();
}
Result GcCrypto::VerifyT1CardCertificate(const void *cert_buffer, size_t cert_size) {
/* Check pre-conditions. */
R_UNLESS(cert_size == sizeof(T1CardCertificate), fs::ResultGameCardPreconditionViolation());
/* Get cert buffer as type. */
const auto * const cert = static_cast<const T1CardCertificate *>(cert_buffer);
/* Verify the signature. */
const void *mod = EmbeddedDataHolder::s_ca9_modulus;
const size_t mod_size = GcRsaKeyLength;
const void *exp = EmbeddedDataHolder::s_ca_public_exponent;
const size_t exp_size = GcRsaPublicExponentLength;
const void *sig = cert->signature;
const size_t sig_size = sizeof(cert->signature);
const void *msg = reinterpret_cast<const u8 *>(cert) + sig_size;
const size_t msg_size = sizeof(*cert) - (sig_size + sizeof(cert->padding));
const bool is_signature_valid = crypto::VerifyRsa2048Pkcs1Sha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size);
R_UNLESS(is_signature_valid, fs::ResultGameCardInvalidT1CardCertificate());
R_SUCCEED();
}
Result GcCrypto::VerifyCa10Certificate(const void *cert_buffer, size_t cert_size) {
/* Check pre-conditions. */
R_UNLESS(cert_size == sizeof(Ca10Certificate), fs::ResultGameCardPreconditionViolation());
/* Get header buffer as type. */
const auto * const cert = static_cast<const Ca10Certificate *>(cert_buffer);
/* Verify the signature. */
const void *mod = EmbeddedDataHolder::s_ca10_certificate_modulus;
const size_t mod_size = GcRsaKeyLength;
const void *exp = EmbeddedDataHolder::s_ca_public_exponent;
const size_t exp_size = GcRsaPublicExponentLength;
const void *sig = cert->signature;
const size_t sig_size = sizeof(cert->signature);
const void *msg = reinterpret_cast<const u8 *>(cert) + sig_size;
const size_t msg_size = sizeof(*cert) - sig_size;
const bool is_signature_valid = crypto::VerifyRsa2048Pkcs1Sha256(sig, sig_size, mod, mod_size, exp, exp_size, msg, msg_size);
R_UNLESS(is_signature_valid, fs::ResultGameCardInvalidCa10Certificate());
R_SUCCEED();
}
Result GcCrypto::EncryptCardHeader(void *header_buffer, size_t header_size) {
/* Check pre-conditions. */
R_UNLESS(header_size == sizeof(CardHeader), fs::ResultGameCardPreconditionViolation());
/* Get header buffer as type. */
auto * const header = static_cast<CardHeader *>(header_buffer);
/* Construct iv. */
u8 iv[GcAesCbcIvLength];
for (size_t i = 0; i < GcAesCbcIvLength; ++i) {
iv[i] = header->iv[GcAesCbcIvLength - 1 - i];
}
/* Encrypt. */
crypto::EncryptAes128Cbc(std::addressof(header->encrypted_data), sizeof(header->encrypted_data), EmbeddedDataHolder::s_card_header_key, GcAesKeyLength, iv, GcAesCbcIvLength, std::addressof(header->encrypted_data), sizeof(header->encrypted_data));
R_SUCCEED();
}
Result GcCrypto::DecryptCardHeader(void *header_buffer, size_t header_size) {
/* Check pre-conditions. */
R_UNLESS(header_size == sizeof(CardHeader), fs::ResultGameCardPreconditionViolation());
/* Get header buffer as type. */
auto * const header = static_cast<CardHeader *>(header_buffer);
/* Construct iv. */
u8 iv[GcAesCbcIvLength];
for (size_t i = 0; i < GcAesCbcIvLength; ++i) {
iv[i] = header->iv[GcAesCbcIvLength - 1 - i];
}
/* Decrypt. */
crypto::DecryptAes128Cbc(std::addressof(header->encrypted_data), sizeof(header->encrypted_data), EmbeddedDataHolder::s_card_header_key, GcAesKeyLength, iv, GcAesCbcIvLength, std::addressof(header->encrypted_data), sizeof(header->encrypted_data));
R_SUCCEED();
}
Result GcCrypto::DecryptCardInitialData(void *dst, size_t dst_size, const void *initial_data, size_t data_size, size_t kek_index) {
/* Check pre-conditions. */
R_UNLESS(data_size == sizeof(CardInitialData), fs::ResultGameCardPreconditionViolation());
R_UNLESS(kek_index < GcTitleKeyKekIndexMax, fs::ResultGameCardPreconditionViolation());
/* Verify the kek is preset. */
const void * const kek = EmbeddedDataHolder::s_titlekey_keks[kek_index];
{
u8 zeros[GcAesKeyLength] = {};
R_UNLESS(!crypto::IsSameBytes(kek, zeros, sizeof(zeros)), fs::ResultGameCardPreconditionViolation());
}
/*Generate the key. */
u8 key[GcAesKeyLength];
{
crypto::AesDecryptor128 aes;
aes.Initialize(kek, GcAesKeyLength);
aes.DecryptBlock(key, sizeof(key), initial_data, 0x10);
}
/* Get data buffer as type. */
const auto * const data = static_cast<const CardInitialData *>(initial_data);
R_UNLESS(dst_size == sizeof(data->payload.auth_data), fs::ResultGameCardPreconditionViolation());
/* Verify padding is all-zero. */
bool any_nonzero = false;
for (size_t i = 0; i < util::size(data->padding); ++i) {
any_nonzero |= data->padding[i] != 0;
}
R_UNLESS(!any_nonzero, fs::ResultGameCardInitialNotFilledWithZero());
/* Decrypt the auth data. */
u8 mac[sizeof(data->payload.auth_mac)];
crypto::DecryptAes128Ccm(dst, dst_size, mac, sizeof(mac), key, GcAesKeyLength, data->payload.auth_nonce, sizeof(data->payload.auth_nonce), data->payload.auth_data, sizeof(data->payload.auth_data), nullptr, 0, sizeof(mac));
/* Check the mac. */
R_UNLESS(crypto::IsSameBytes(mac, data->payload.auth_mac, sizeof(mac)), fs::ResultGameCardKekIndexMismatch());
R_SUCCEED();
}
}
| 8,155
|
C++
|
.cpp
| 141
| 49.737589
| 254
| 0.660734
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,867
|
diag_log_observer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_log_observer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_log_impl.hpp"
#include "impl/diag_observer_manager.hpp"
#include "impl/diag_print_debug_string.hpp"
namespace ams::diag {
namespace impl {
namespace {
constexpr inline size_t DecorationStringLengthMax = 0x61;
constexpr inline const char *EscapeSequencesForSeverity[] = {
"\x1B[90m", /* Dark Gray (Trace) */
nullptr, /* None (Info) */
"\x1B[33m", /* Yellow (Warn) */
"\x1B[31m", /* Red (Error) */
"\x1B[41m\x1B[37m", /* White-on-red (Fatal) */
};
constexpr inline const char EscapeSequenceReset[] = "\x1B[0m";
constexpr inline size_t PrintBufferLength = DecorationStringLengthMax + impl::DebugPrintBufferLength + 1;
constinit os::SdkMutex g_print_buffer_mutex;
constinit char g_print_buffer[PrintBufferLength];
inline void GetCurrentTime(int *h, int *m, int *s, int *ms) {
/* Get the current time. */
const auto cur_time = os::GetSystemTick().ToTimeSpan();
/* Extract fields. */
const s64 hours = cur_time.GetHours();
const s64 minutes = cur_time.GetMinutes();
const s64 seconds = cur_time.GetSeconds();
const s64 milliseconds = cur_time.GetMilliSeconds();
/* Set out fields. */
*h = static_cast<int>(hours);
*m = static_cast<int>(minutes - hours * 60);
*s = static_cast<int>(seconds - minutes * 60);
*ms = static_cast<int>(milliseconds - seconds * 1000);
}
void TentativeDefaultLogObserver(const LogMetaData &meta, const LogBody &body, void *) {
/* Acquire access to the print buffer */
std::scoped_lock lk(g_print_buffer_mutex);
/* Get the escape sequence. */
const char *escape = nullptr;
if (LogSeverity_Trace <= meta.severity && meta.severity <= LogSeverity_Fatal) {
escape = EscapeSequencesForSeverity[meta.severity];
}
/* Declare message variables. */
const char *msg = nullptr;
size_t msg_size = 0;
/* Handle structured logs. */
const bool structured = meta.module_name != nullptr && std::strlen(meta.module_name) >= 2;
if (escape || structured) {
/* Insert timestamp, if head. */
if (structured && body.is_head) {
/* Get current timestamp. */
int hours, minutes, seconds, milliseconds;
GetCurrentTime(std::addressof(hours), std::addressof(minutes), std::addressof(seconds), std::addressof(milliseconds));
/* Print the timestamp/header. */
msg_size += util::SNPrintf(g_print_buffer + msg_size, PrintBufferLength - msg_size, "%s%d:%02d:%02d.%03d [%-5.63s] ", escape ? escape : "", hours, minutes, seconds, milliseconds, meta.module_name[0] == '$' ? meta.module_name + 1 : meta.module_name + 0);
AMS_AUDIT(msg_size <= DecorationStringLengthMax);
} else if (escape) {
msg_size += util::SNPrintf(g_print_buffer + msg_size, PrintBufferLength - msg_size, "%s", escape);
}
/* Determine maximum remaining size. */
const size_t max_msg_size = PrintBufferLength - msg_size - (escape ? sizeof(EscapeSequenceReset) - 1 : 0);
/* Determine printable size. */
size_t printable_size = std::min<size_t>(body.message_size, max_msg_size);
/* Determine newline status. */
bool new_line = false;
if (body.message_size > 0 && body.message[body.message_size - 1] == '\n') {
--printable_size;
new_line = true;
}
/* Print the messsage. */
msg_size += util::SNPrintf(g_print_buffer + msg_size, PrintBufferLength - msg_size, "%.*s%s%s", static_cast<int>(printable_size), body.message, escape ? EscapeSequenceReset : "", new_line ? "\n" : "");
/* Set the message. */
msg = g_print_buffer;
} else {
/* Use the body's message directly. */
msg = body.message;
msg_size = body.message_size;
}
/* Print the string. */
impl::PrintDebugString(msg, msg_size);
}
struct LogObserverContext {
const LogMetaData &meta;
const LogBody &body;
};
using LogObserverManager = ObserverManagerWithDefaultHolder<LogObserverHolder, LogObserverContext>;
constinit LogObserverManager g_log_observer_manager(::ams::diag::InitializeLogObserverHolder, TentativeDefaultLogObserver, nullptr);
}
void CallAllLogObserver(const LogMetaData &meta, const LogBody &body) {
/* Create context. */
const LogObserverContext context = { .meta = meta, .body = body };
/* Invoke the log observer. */
g_log_observer_manager.InvokeAllObserver(context, [] (const LogObserverHolder &holder, const LogObserverContext &context) {
holder.log_observer(context.meta, context.body, holder.arg);
});
}
void ReplaceDefaultLogObserver(LogObserver observer) {
/* Get the default observer. */
auto *default_holder = std::addressof(g_log_observer_manager.GetDefaultObserverHolder());
/* Unregister, replace, and re-register. */
UnregisterLogObserver(default_holder);
InitializeLogObserverHolder(default_holder, observer, nullptr);
RegisterLogObserver(default_holder);
}
void ResetDefaultLogObserver() {
/* Restore the default observer. */
ReplaceDefaultLogObserver(TentativeDefaultLogObserver);
}
}
void RegisterLogObserver(LogObserverHolder *holder) {
impl::g_log_observer_manager.RegisterObserver(holder);
}
void UnregisterLogObserver(LogObserverHolder *holder) {
impl::g_log_observer_manager.UnregisterObserver(holder);
}
}
| 7,254
|
C++
|
.cpp
| 130
| 41.861538
| 277
| 0.569554
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,868
|
diag_backtrace.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_backtrace.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/diag_get_all_backtrace.hpp"
namespace ams::diag {
size_t GetBacktrace(uintptr_t *out, size_t out_size) {
/* Validate pre-conditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(out_size > 0);
/* Create the backtrace object. */
::ams::diag::Backtrace bt{};
bt.Step();
/* Get the backtrace. */
return ::ams::diag::impl::GetAllBacktrace(out, out_size, bt);
}
#if defined(ATMOSPHERE_OS_HORIZON)
size_t GetBacktrace(uintptr_t *out, size_t out_size, uintptr_t fp, uintptr_t sp, uintptr_t pc) {
/* Validate pre-conditions. */
AMS_ASSERT(out != nullptr);
AMS_ASSERT(out_size > 0);
/* Create the backtrace object. */
::ams::diag::Backtrace bt{fp, sp, pc};
bt.Step();
/* Get the backtrace. */
return ::ams::diag::impl::GetAllBacktrace(out, out_size, bt);
}
#endif
}
| 1,593
|
C++
|
.cpp
| 41
| 33.585366
| 100
| 0.659106
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,869
|
diag_log.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_log.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_log_impl.hpp"
namespace ams::diag::impl {
void CallAllLogObserver(const LogMetaData &meta, const LogBody &body);
namespace {
struct CallPrintDebugString {
void operator()(const LogMetaData &meta, const char *msg, size_t size, bool head, bool tail) {
const LogBody body = {
.message = msg,
.message_size = size,
.is_head = head,
.is_tail = tail
};
CallAllLogObserver(meta, body);
}
};
}
void LogImpl(const LogMetaData &meta, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
VLogImpl(meta, fmt, vl);
va_end(vl);
}
void VLogImpl(const LogMetaData &meta, const char *fmt, std::va_list vl) {
#if defined(ATMOSPHERE_OS_HORIZON)
/* Print to stack buffer. */
char msg_buffer[DebugPrintBufferLength];
/* TODO: VFormatString using utf-8 printer. */
const size_t len = util::VSNPrintf(msg_buffer, sizeof(msg_buffer), fmt, vl);
#else
/* Print to allocated buffer. */
std::va_list cvl;
va_copy(cvl, vl);
const auto out_len = util::TVSNPrintf(nullptr, 0, fmt, cvl) + 1;
va_end(cvl);
char *msg_buffer = static_cast<char *>(std::malloc(out_len));
AMS_ABORT_UNLESS(msg_buffer != nullptr);
ON_SCOPE_EXIT { std::free(msg_buffer); };
/* TODO: VFormatString using utf-8 printer. */
const size_t len = util::TVSNPrintf(msg_buffer, out_len, fmt, vl);
#endif
/* Call log observer. */
CallPrintDebugString()(meta, msg_buffer, len, true, true);
}
void PutImpl(const LogMetaData &meta, const char *msg, size_t msg_size) {
CallPrintDebugString()(meta, msg, msg_size, true, true);
}
}
| 2,557
|
C++
|
.cpp
| 63
| 32.857143
| 106
| 0.619355
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,870
|
diag_symbol.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_symbol.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/diag_symbol_impl.hpp"
namespace ams::diag {
uintptr_t GetSymbolName(char *dst, size_t dst_size, uintptr_t address) {
AMS_ASSERT(dst != nullptr);
AMS_ASSERT(dst_size > 0);
AMS_ASSERT(address > 0);
return ::ams::diag::impl::GetSymbolNameImpl(dst, dst_size, address);
}
size_t GetSymbolSize(uintptr_t address) {
AMS_ASSERT(address > 0);
return ::ams::diag::impl::GetSymbolSizeImpl(address);
}
}
| 1,140
|
C++
|
.cpp
| 29
| 35.413793
| 76
| 0.710407
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,871
|
diag_assertion_impl.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_assertion_impl.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/diag_get_all_backtrace.hpp"
#include "impl/diag_invoke_abort.hpp"
namespace ams::diag {
namespace {
inline NORETURN void AbortWithValue(u64 debug) {
#if defined(ATMOSPHERE_BOARD_NINTENDO_NX)
/* Just perform a data abort. */
register u64 addr __asm__("x27") = FatalErrorContext::StdAbortMagicAddress;
register u64 val __asm__("x28") = FatalErrorContext::StdAbortMagicValue;
while (true) {
__asm__ __volatile__ (
"mov x0, %[debug]\n"
"str %[val], [%[addr]]\n"
:
: [debug]"r"(debug), [val]"r"(val), [addr]"r"(addr)
: "x0"
);
}
#else
AMS_UNUSED(debug);
std::abort();
#endif
__builtin_unreachable();
}
constinit os::SdkMutex g_assert_mutex;
constinit os::SdkMutex g_abort_mutex;
void PrepareAbort() {
#if defined(ATMOSPHERE_OS_HORIZON)
{
/* Get the thread local region. */
auto * const tlr = svc::GetThreadLocalRegion();
/* Clear disable count. */
tlr->disable_count = 0;
/* If we need to, unpin. */
if (tlr->interrupt_flag) {
svc::SynchronizePreemptionState();
}
}
#endif
}
AbortReason ToAbortReason(AssertionType type) {
switch (type) {
case AssertionType_Audit: return AbortReason_Audit;
case AssertionType_Assert: return AbortReason_Assert;
default:
return AbortReason_Abort;
}
}
AssertionFailureOperation DefaultAssertionFailureHandler(const AssertionInfo &) {
return AssertionFailureOperation_Abort;
}
constinit AssertionFailureHandler g_assertion_failure_handler = &DefaultAssertionFailureHandler;
void ExecuteAssertionFailureOperation(AssertionFailureOperation operation, const AssertionInfo &info) {
switch (operation) {
case AssertionFailureOperation_Continue:
break;
case AssertionFailureOperation_Abort:
{
const AbortInfo abort_info = {
ToAbortReason(info.type),
info.message,
info.expr,
info.func,
info.file,
info.line,
};
::ams::diag::impl::InvokeAbortObserver(abort_info);
AbortWithValue(0);
}
break;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void InvokeAssertionFailureHandler(const AssertionInfo &info) {
const auto operation = g_assertion_failure_handler(info);
ExecuteAssertionFailureOperation(operation, info);
}
}
NOINLINE void OnAssertionFailure(AssertionType type, const char *expr, const char *func, const char *file, int line, const char *format, ...) {
/* Prepare to abort. */
PrepareAbort();
/* Acquire exclusive assert rights. */
if (g_assert_mutex.IsLockedByCurrentThread()) {
AbortWithValue(0);
}
std::scoped_lock lk(g_assert_mutex);
/* Create the assertion info. */
std::va_list vl;
va_start(vl, format);
const ::ams::diag::LogMessage message = { format, std::addressof(vl) };
const AssertionInfo info = {
type,
std::addressof(message),
expr,
func,
file,
line,
};
InvokeAssertionFailureHandler(info);
va_end(vl);
}
void OnAssertionFailure(AssertionType type, const char *expr, const char *func, const char *file, int line) {
return OnAssertionFailure(type, expr, func, file, line, "");
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line) {
const Result res = ResultSuccess();
std::va_list vl{};
VAbortImpl(expr, func, file, line, std::addressof(res), nullptr, "", vl);
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const char *fmt, ...) {
const Result res = ResultSuccess();
std::va_list vl;
va_start(vl, fmt);
VAbortImpl(expr, func, file, line, std::addressof(res), nullptr, fmt, vl);
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const ::ams::Result *result, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
VAbortImpl(expr, func, file, line, result, nullptr, fmt, vl);
}
NORETURN void AbortImpl(const char *expr, const char *func, const char *file, int line, const ::ams::Result *result, const ::ams::os::UserExceptionInfo *exc_info, const char *fmt, ...) {
std::va_list vl;
va_start(vl, fmt);
VAbortImpl(expr, func, file, line, result, exc_info, fmt, vl);
}
NORETURN NOINLINE void VAbortImpl(const char *expr, const char *func, const char *file, int line, const ::ams::Result *result, const ::ams::os::UserExceptionInfo *exc_info, const char *fmt, std::va_list vl) {
/* Prepare to abort. */
PrepareAbort();
/* Acquire exclusive abort rights. */
if (g_abort_mutex.IsLockedByCurrentThread()) {
AbortWithValue(result->GetValue());
}
std::scoped_lock lk(g_abort_mutex);
/* Set the abort impl return address. */
impl::SetAbortImplReturnAddress(reinterpret_cast<uintptr_t>(__builtin_return_address(0)));
/* Create abort info. */
std::va_list cvl;
va_copy(cvl, vl);
const diag::LogMessage message = { fmt, std::addressof(cvl) };
const AbortInfo abort_info = {
AbortReason_Abort,
std::addressof(message),
expr,
func,
file,
line,
};
const SdkAbortInfo sdk_abort_info = {
abort_info,
*result,
exc_info
};
/* Invoke observers. */
::ams::diag::impl::InvokeAbortObserver(abort_info);
::ams::diag::impl::InvokeSdkAbortObserver(sdk_abort_info);
/* Abort. */
AbortWithValue(result->GetValue());
}
}
namespace ams::impl {
NORETURN NOINLINE void UnexpectedDefaultImpl(const char *func, const char *file, int line) {
/* Create abort info. */
std::va_list vl{};
const ::ams::diag::LogMessage message = { "" , std::addressof(vl) };
const ::ams::diag::AbortInfo abort_info = {
::ams::diag::AbortReason_UnexpectedDefault,
std::addressof(message),
"",
func,
file,
line,
};
/* Invoke observers. */
::ams::diag::impl::InvokeAbortObserver(abort_info);
/* Abort. */
::ams::diag::AbortWithValue(0);
}
}
| 7,979
|
C++
|
.cpp
| 194
| 29.938144
| 212
| 0.565358
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,872
|
diag_abort_observer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/diag_abort_observer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "impl/diag_abort_observer_manager.hpp"
namespace ams::diag {
namespace impl {
constinit bool g_enable_default_abort_observer = true;
}
namespace {
template<typename Holder, typename Observer>
void InitializeAbortObserverHolderImpl(Holder *holder, Observer observer) {
holder->observer = observer;
holder->next = nullptr;
holder->is_registered = false;
}
}
void InitializeAbortObserverHolder(AbortObserverHolder *holder, AbortObserver observer) {
InitializeAbortObserverHolderImpl(holder, observer);
}
void RegisterAbortObserver(AbortObserverHolder *holder) {
impl::GetAbortObserverManager()->RegisterObserver(holder);
}
void UnregisterAbortObserver(AbortObserverHolder *holder) {
impl::GetAbortObserverManager()->UnregisterObserver(holder);
}
void EnableDefaultAbortObserver(bool en) {
::ams::diag::impl::g_enable_default_abort_observer = en;
}
void InitializeSdkAbortObserverHolder(SdkAbortObserverHolder *holder, SdkAbortObserver observer) {
InitializeAbortObserverHolderImpl(holder, observer);
}
void RegisterSdkAbortObserver(SdkAbortObserverHolder *holder) {
impl::GetSdkAbortObserverManager()->RegisterObserver(holder);
}
void UnregisterSdkAbortObserver(SdkAbortObserverHolder *holder) {
impl::GetSdkAbortObserverManager()->UnregisterObserver(holder);
}
}
| 2,158
|
C++
|
.cpp
| 51
| 36.901961
| 102
| 0.733748
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,873
|
diag_symbol_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_symbol_impl.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_symbol_impl.hpp"
namespace ams::diag::impl {
uintptr_t GetSymbolNameImpl(char *dst, size_t dst_size, uintptr_t address) {
AMS_UNUSED(dst, dst_size, address);
AMS_ABORT("TODO");
}
size_t GetSymbolSizeImpl(uintptr_t address) {
AMS_UNUSED(address);
AMS_ABORT("TODO");
}
}
| 999
|
C++
|
.cpp
| 27
| 33.555556
| 80
| 0.720041
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,874
|
diag_symbol_impl.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_symbol_impl.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_symbol_impl.hpp"
#include <unistd.h>
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <mach-o/stab.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <cxxabi.h>
extern "C" {
void __module_offset_helper() { /* ... */ }
}
namespace ams::diag::impl {
namespace {
class CurrentExecutableHelper {
private:
struct SymbolInfo {
uintptr_t address;
const char *name;
};
private:
os::NativeHandle m_fd;
void *m_file_map;
size_t m_file_size;
SymbolInfo *m_symbols;
size_t m_num_symbol;
const char *m_module_name;
uintptr_t m_module_address;
size_t m_module_size;
uintptr_t m_module_displacement;
private:
CurrentExecutableHelper() : m_fd(-1), m_file_map(nullptr), m_file_size(0), m_symbols(nullptr), m_num_symbol(0), m_module_name(nullptr), m_module_address(0), m_module_size(0), m_module_displacement(0) {
/* Get the current executable name. */
char exe_path[4_KB] = {};
GetExecutablePath(exe_path, sizeof(exe_path));
/* Open the current executable. */
os::NativeHandle fd;
do {
fd = ::open(exe_path, O_RDONLY);
} while (fd < 0 && errno == EINTR);
if (fd < 0) {
return;
}
ON_SCOPE_EXIT { if (fd >= 0) { s32 ret; do { ret = ::close(fd); } while (ret < 0 && errno == EINTR); } };
/* Get the file size. */
struct stat st;
if (fstat(fd, std::addressof(st)) < 0) {
return;
}
/* Check that the file can be mapped. */
const size_t exe_size = st.st_size;
if (exe_size == 0) {
return;
}
/* Map the executable. */
void *exe_map = mmap(nullptr, exe_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (exe_map == MAP_FAILED) {
return;
}
ON_SCOPE_EXIT { if (exe_map != nullptr) { munmap(exe_map, exe_size); } };
/* Get the file's u32 magic. */
const uintptr_t exe_start = reinterpret_cast<uintptr_t>(exe_map);
const u32 magic = *reinterpret_cast<const u32 *>(exe_start);
/* Get/parse the mach header. */
u32 ncmds;
bool is_64;
if (magic == MH_MAGIC) {
const auto *header = reinterpret_cast<const struct mach_header *>(exe_start);
ncmds = header->ncmds;
is_64 = false;
} else if (magic == MH_MAGIC_64) {
const auto *header = reinterpret_cast<const struct mach_header_64 *>(exe_start);
ncmds = header->ncmds;
is_64 = true;
} else {
return;
}
/* Find the symbol load command. */
const auto *lc = reinterpret_cast<const struct load_command *>(exe_start + (is_64 ? sizeof(struct mach_header_64) : sizeof(struct mach_header)));
for (u32 i = 0; i < ncmds; ++i) {
/* If we encounter the symbol table, parse it. */
if (lc->cmd == LC_SYMTAB) {
if (is_64) {
this->ParseSymbolTable<struct nlist_64>(exe_start, reinterpret_cast<const struct symtab_command *>(lc));
} else {
this->ParseSymbolTable<struct nlist>(exe_start, reinterpret_cast<const struct symtab_command *>(lc));
}
break;
} else if (lc->cmd == LC_SEGMENT) {
const auto *sc = reinterpret_cast<const struct segment_command *>(lc);
if (std::strcmp(sc->segname, "__TEXT") == 0) {
AMS_ASSERT(m_module_address == 0);
m_module_address = sc->vmaddr;
m_module_size = sc->vmsize;
AMS_ASSERT(m_module_address != 0);
}
} else if (lc->cmd == LC_SEGMENT_64) {
const auto *sc = reinterpret_cast<const struct segment_command_64 *>(lc);
if (std::strcmp(sc->segname, "__TEXT") == 0) {
AMS_ASSERT(m_module_address == 0);
m_module_address = sc->vmaddr;
m_module_size = sc->vmsize;
AMS_ASSERT(m_module_address != 0);
}
}
/* Advance to the next load command. */
lc = reinterpret_cast<const struct load_command *>(reinterpret_cast<uintptr_t>(lc) + lc->cmdsize);
}
for (size_t i = 0; i < m_num_symbol; ++i) {
if (std::strcmp(m_symbols[i].name, "___module_offset_helper") == 0) {
m_module_displacement = reinterpret_cast<uintptr_t>(&__module_offset_helper) - m_symbols[i].address;
break;
}
}
if (m_module_address > 0 && m_module_size > 0 && m_num_symbol > 0) {
std::swap(m_fd, fd);
std::swap(m_file_map, exe_map);
m_file_size = exe_size;
}
}
~CurrentExecutableHelper() {
if (m_file_map != nullptr) {
munmap(m_file_map, m_file_size);
}
if (m_fd >= 0) {
s32 ret;
do { ret = ::close(m_fd); } while (ret < 0 && errno == EINTR);
}
}
public:
static CurrentExecutableHelper &GetInstance() {
AMS_FUNCTION_LOCAL_STATIC(CurrentExecutableHelper, s_current_executable_helper_instance);
return s_current_executable_helper_instance;
}
private:
template<typename NlistType>
void ParseSymbolTable(uintptr_t exe_start, const struct symtab_command *c) {
/* Check pre-conditions. */
AMS_ASSERT(m_fd == -1);
AMS_ASSERT(m_file_map == nullptr);
AMS_ASSERT(m_symbols == nullptr);
/* Get the strtab/symtab. */
const auto *symtab = reinterpret_cast<const NlistType *>(exe_start + c->symoff);
const char *strtab = reinterpret_cast<const char *>(exe_start + c->stroff);
/* Determine the number of functions. */
size_t funcs = 0;
for (size_t i = 0; i < c->nsyms; ++i) {
if (symtab[i].n_type != N_FUN || symtab[i].n_sect == NO_SECT) {
continue;
}
++funcs;
}
/* Allocate functions. */
m_symbols = reinterpret_cast<SymbolInfo *>(std::malloc(sizeof(SymbolInfo) * funcs));
if (m_symbols == nullptr) {
return;
}
/* Set all symbols. */
m_num_symbol = 0;
for (size_t i = 0; i < c->nsyms; ++i) {
if (symtab[i].n_type != N_FUN || symtab[i].n_sect == NO_SECT) {
continue;
}
m_symbols[m_num_symbol].address = symtab[i].n_value;
m_symbols[m_num_symbol].name = strtab + symtab[i].n_un.n_strx;
++m_num_symbol;
}
AMS_ASSERT(m_num_symbol == funcs);
/* Sort the symbols. */
std::sort(m_symbols + 0, m_symbols + m_num_symbol, [] (const SymbolInfo &lhs, const SymbolInfo &rhs) {
return lhs.address < rhs.address;
});
}
size_t GetSymbolSizeImpl(const SymbolInfo *symbol) const {
/* Do our best to guess. */
if (symbol != m_symbols + m_num_symbol - 1) {
return (symbol + 1)->address - symbol->address;
} else if (m_module_address + m_module_size >= symbol->address) {
return m_module_address + m_module_size - symbol->address;
} else {
return 0;
}
}
const SymbolInfo *GetBestSymbol(uintptr_t address) const {
address -= m_module_displacement;
const SymbolInfo *best_symbol = std::lower_bound(m_symbols + 0, m_symbols + m_num_symbol, address, [](const SymbolInfo &lhs, uintptr_t rhs) {
return lhs.address < rhs;
});
if (best_symbol == m_symbols + m_num_symbol) {
return nullptr;
}
if (best_symbol->address != address && best_symbol > m_symbols) {
--best_symbol;
}
const auto vma = best_symbol->address;
const auto end = vma + this->GetSymbolSizeImpl(best_symbol);
if (vma <= address && address < end) {
return best_symbol;
} else {
return nullptr;
}
}
public:
uintptr_t GetSymbolName(char *dst, size_t dst_size, uintptr_t address) const {
if (m_fd < 0) {
return 0;
}
/* Get the symbol. */
const auto *symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
/* Print the symbol. */
const char *name = symbol->name;
int cpp_name_status = 0;
if (char *demangled = abi::__cxa_demangle(name, nullptr, 0, std::addressof(cpp_name_status)); cpp_name_status == 0) {
AMS_ASSERT(demangled != nullptr);
util::TSNPrintf(dst, dst_size, "%s", demangled);
std::free(demangled);
} else {
util::TSNPrintf(dst, dst_size, "%s", name);
}
return symbol->address + m_module_displacement;
}
size_t GetSymbolSize(uintptr_t address) const {
if (m_fd < 0) {
return 0;
}
/* Get the symbol. */
const auto *symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
return this->GetSymbolSizeImpl(symbol);
}
private:
static void GetExecutablePath(char *dst, size_t dst_size) {
u32 len = dst_size;
if (_NSGetExecutablePath(dst, std::addressof(len)) != 0) {
dst[0] = 0;
return;
}
}
};
}
uintptr_t GetSymbolNameImpl(char *dst, size_t dst_size, uintptr_t address) {
return CurrentExecutableHelper::GetInstance().GetSymbolName(dst, dst_size, address);
}
size_t GetSymbolSizeImpl(uintptr_t address) {
return CurrentExecutableHelper::GetInstance().GetSymbolSize(address);
}
}
| 13,379
|
C++
|
.cpp
| 271
| 30.077491
| 217
| 0.43917
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,875
|
diag_invoke_abort.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_invoke_abort.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_abort_observer_manager.hpp"
#include "diag_invoke_abort.hpp"
namespace ams::diag::impl {
extern bool g_enable_default_abort_observer;
void DefaultAbortObserver(const AbortInfo &info);
void InvokeAbortObserver(const AbortInfo &info) {
if (g_enable_default_abort_observer) {
DefaultAbortObserver(info);
}
GetAbortObserverManager()->InvokeAllObserver(info);
}
void InvokeSdkAbortObserver(const SdkAbortInfo &info) {
GetSdkAbortObserverManager()->InvokeAllObserver(info);
}
}
| 1,225
|
C++
|
.cpp
| 31
| 35.645161
| 76
| 0.742207
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,876
|
diag_utf8_util.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_utf8_util.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::diag::impl {
namespace {
bool IsHeadOfCharacter(u8 c) {
return (c & 0xC0) != 0x80;
}
size_t GetCharacterSize(u8 c) {
if ((c & 0x80) == 0) {
return 1;
} else if ((c & 0xE0) == 0xC0) {
return 2;
} else if ((c & 0xF0) == 0xE0) {
return 3;
} else if ((c & 0xF8) == 0xF0) {
return 4;
}
return 0;
}
const char *FindLastCharacterPointer(const char *str, size_t len) {
/* Find the head of the last character. */
const char *cur;
for (cur = str + len - 1; cur >= str && !IsHeadOfCharacter(*reinterpret_cast<const u8 *>(cur)); --cur) {
/* ... */
}
/* Return the last character. */
if (AMS_LIKELY(cur >= str)) {
return cur;
} else {
return nullptr;
}
}
}
int GetValidSizeAsUtf8String(const char *str, size_t len) {
/* Check pre-condition. */
AMS_ASSERT(str != nullptr);
/* Check if we have no data. */
if (len == 0) {
return 0;
}
/* Get the last character pointer. */
const auto *last_char_ptr = FindLastCharacterPointer(str, len);
if (last_char_ptr == nullptr) {
return -1;
}
/* Get sizes. */
const size_t actual_size = (str + len) - last_char_ptr;
const size_t last_char_size = GetCharacterSize(*reinterpret_cast<const u8 *>(last_char_ptr));
if (last_char_size == 0) {
return -1;
} else if (actual_size >= last_char_size) {
if (actual_size == last_char_size) {
return len;
} else {
return -1;
}
} else if (actual_size >= len) {
AMS_ASSERT(actual_size == len);
return -1;
} else {
return static_cast<int>(len - actual_size);
}
}
}
| 2,747
|
C++
|
.cpp
| 78
| 25.769231
| 116
| 0.529367
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,877
|
diag_symbol_impl.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_symbol_impl.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_symbol_impl.hpp"
#define PACKAGE "stratosphere"
#define PACKAGE_VERSION STRINGIFY(ATMOSPHERE_RELEASE_VERSION_MAJOR.ATMOSPHERE_RELEASE_VERSION_MINOR.ATMOSPHERE_RELEASE_VERSION_MICRO)
#if defined(ATMOSPHERE_OS_LINUX)
#include <bfd.h>
#include <unistd.h>
#include <dlfcn.h>
#include <link.h>
extern "C" char __init_array_start;
#endif
#include <cxxabi.h>
namespace ams::diag::impl {
namespace {
class BfdHelper {
private:
bfd *m_handle;
asymbol **m_symbol;
size_t m_num_symbol;
size_t m_num_func_symbol;
const char *m_module_name;
uintptr_t m_module_address;
size_t m_module_size;
private:
BfdHelper() : m_handle(nullptr), m_symbol(nullptr), m_module_name(nullptr) {
/* Get the current executable name. */
char exe_path[4_KB] = {};
GetExecutablePath(exe_path, sizeof(exe_path));
/* Open bfd. */
bfd *b = ::bfd_openr(exe_path, 0);
if (b == nullptr) {
return;
}
auto bfd_guard = SCOPE_GUARD { ::bfd_close(b); };
/* Check the format. */
if (!::bfd_check_format(b, bfd_object)) {
return;
}
/* Verify the file has symbols. */
if ((bfd_get_file_flags(b) & HAS_SYMS) == 0) {
return;
}
/* Read the symbols. */
unsigned int _;
void *symbol_table;
s64 num_symbols = bfd_read_minisymbols(b, false, std::addressof(symbol_table), std::addressof(_));
if (num_symbols == 0) {
num_symbols = bfd_read_minisymbols(b, true, std::addressof(symbol_table), std::addressof(_));
if (num_symbols < 0) {
return;
}
}
/* We successfully got the symbol table. */
bfd_guard.Cancel();
m_handle = b;
m_symbol = reinterpret_cast<asymbol **>(symbol_table);
m_num_symbol = static_cast<size_t>(num_symbols);
/* Sort the symbol table. */
std::sort(m_symbol + 0, m_symbol + m_num_symbol, [] (asymbol *lhs, asymbol *rhs) {
const bool l_func = (lhs->flags & BSF_FUNCTION);
const bool r_func = (rhs->flags & BSF_FUNCTION);
if (l_func == r_func) {
return bfd_asymbol_value(lhs) < bfd_asymbol_value(rhs);
} else {
return l_func;
}
});
/* Determine number of function symbols. */
m_num_func_symbol = 0;
for (size_t i = 0; i < m_num_symbol; ++i) {
if ((m_symbol[i]->flags & BSF_FUNCTION) == 0) {
m_num_func_symbol = i;
break;
}
}
for (int i = std::strlen(exe_path) - 1; i >= 0; --i) {
if (exe_path[i] == '/' || exe_path[i] == '\\') {
m_module_name = strdup(exe_path + i + 1);
break;
}
}
/* Get our module base/size. */
#if defined(ATMOSPHERE_OS_LINUX)
{
m_module_address = _r_debug.r_map->l_addr;
m_module_size = reinterpret_cast<uintptr_t>(std::addressof(__init_array_start)) - m_module_address;
}
#endif
}
~BfdHelper() {
if (m_symbol != nullptr) {
std::free(m_symbol);
}
if (m_handle != nullptr) {
::bfd_close(m_handle);
}
}
public:
static BfdHelper &GetInstance() {
AMS_FUNCTION_LOCAL_STATIC(BfdHelper, s_bfd_helper_instance);
return s_bfd_helper_instance;
}
private:
size_t GetSymbolSizeImpl(asymbol **symbol) const {
/* Do our best to guess. */
const auto vma = bfd_asymbol_value(*symbol);
if (symbol != m_symbol + m_num_func_symbol - 1) {
return bfd_asymbol_value(*(symbol + 1)) - vma;
} else {
const auto *sec = (*symbol)->section;
return (sec->vma + sec->size) - vma;
}
}
std::ptrdiff_t GetSymbolAddressDisplacement(uintptr_t address) const {
std::ptrdiff_t displacement = 0;
if (m_module_address <= address && address < m_module_address + m_module_size) {
displacement = m_module_address;
}
return displacement;
}
asymbol **GetBestSymbol(uintptr_t address) const {
/* Adjust the symbol address. */
address -= this->GetSymbolAddressDisplacement(address);
asymbol **best_symbol = std::lower_bound(m_symbol + 0, m_symbol + m_num_func_symbol, address, [](asymbol *lhs, uintptr_t rhs) {
return bfd_asymbol_value(lhs) < rhs;
});
if (best_symbol == m_symbol + m_num_func_symbol) {
return nullptr;
}
if (bfd_asymbol_value(*best_symbol) != address && best_symbol > m_symbol) {
--best_symbol;
}
const auto vma = bfd_asymbol_value(*best_symbol);
const auto end = vma + this->GetSymbolSizeImpl(best_symbol);
if (vma <= address && address < end) {
return best_symbol;
} else {
return nullptr;
}
}
public:
uintptr_t GetSymbolName(char *dst, size_t dst_size, uintptr_t address) const {
/* Get the symbol. */
auto **symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
/* Print the symbol. */
const char *name = bfd_asymbol_name(*symbol);
int cpp_name_status = 0;
if (char *demangled = abi::__cxa_demangle(name, nullptr, 0, std::addressof(cpp_name_status)); cpp_name_status == 0) {
AMS_ASSERT(demangled != nullptr);
util::TSNPrintf(dst, dst_size, "%s", demangled);
std::free(demangled);
} else {
util::TSNPrintf(dst, dst_size, "%s", name);
}
return bfd_asymbol_value(*symbol) + this->GetSymbolAddressDisplacement(address);
}
size_t GetSymbolSize(uintptr_t address) const {
/* Get the symbol. */
auto **symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
return this->GetSymbolSizeImpl(symbol);
}
private:
static void GetExecutablePath(char *dst, size_t dst_size) {
#if defined(ATMOSPHERE_OS_LINUX)
{
if (::readlink("/proc/self/exe", dst, dst_size) == -1) {
dst[0] = 0;
return;
}
}
#else
#error "Unknown OS for BfdHelper GetExecutablePath"
#endif
}
};
}
uintptr_t GetSymbolNameImpl(char *dst, size_t dst_size, uintptr_t address) {
return BfdHelper::GetInstance().GetSymbolName(dst, dst_size, address);
}
size_t GetSymbolSizeImpl(uintptr_t address) {
return BfdHelper::GetInstance().GetSymbolSize(address);
}
}
| 9,447
|
C++
|
.cpp
| 204
| 28.279412
| 147
| 0.449815
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,878
|
diag_dump_stack_trace.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_dump_stack_trace.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_dump_stack_trace.hpp"
namespace ams::diag::impl {
void TentativeDumpStackTrace() {
AMS_SDK_LOG("----------------Stack Trace----------------\n");
{
/* Get the backtrace. */
constexpr size_t MaxBackTraceSize = 0x40;
uintptr_t backtrace[MaxBackTraceSize];
const size_t num_items = ::ams::diag::GetBacktrace(backtrace, MaxBackTraceSize);
/* Print each item. */
for (size_t i = 0; i < num_items; ++i) {
char symbol_name[0x200];
if (const uintptr_t symbol_base = ::ams::diag::GetSymbolName(symbol_name, sizeof(symbol_name), backtrace[i] - 1); symbol_base != 0) {
AMS_SDK_LOG("0x%016" PRIX64 " [ %s+0x%" PRIX64 " ]\n", static_cast<u64>(backtrace[i]), symbol_name, static_cast<u64>(backtrace[i] - symbol_base));
} else {
AMS_SDK_LOG("0x%016" PRIX64 " [ unknown ]\n", static_cast<u64>(backtrace[i]));
}
}
}
AMS_SDK_LOG("-------------------------------------------\n");
}
}
| 1,774
|
C++
|
.cpp
| 38
| 39.210526
| 166
| 0.598152
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,879
|
diag_symbol_impl.os.windows.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_symbol_impl.os.windows.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include <stratosphere/windows.hpp>
#include "diag_symbol_impl.hpp"
#include <cxxabi.h>
extern "C" {
void __module_offset_helper() { /* ... */ }
}
namespace ams::diag::impl {
namespace {
class CurrentExecutableHelper {
private:
struct SymbolInfo {
uintptr_t address;
const char *name;
};
private:
os::NativeHandle m_file_handle;
os::NativeHandle m_map_handle;
void *m_file_map;
size_t m_file_size;
SymbolInfo *m_symbols;
size_t m_num_symbol;
uintptr_t m_module_address;
size_t m_module_size;
uintptr_t m_module_displacement;
private:
CurrentExecutableHelper() : m_file_handle(INVALID_HANDLE_VALUE), m_map_handle(INVALID_HANDLE_VALUE), m_file_map(nullptr), m_file_size(0), m_symbols(nullptr), m_num_symbol(0), m_module_address(0), m_module_size(0), m_module_displacement(0) {
/* Open the current executable. */
auto exe_handle = OpenExecutableFile();
if (exe_handle == INVALID_HANDLE_VALUE) {
return;
}
ON_SCOPE_EXIT { if (exe_handle != INVALID_HANDLE_VALUE) { ::CloseHandle(exe_handle); } };
/* Get the exe size. */
LARGE_INTEGER exe_size_li;
if (::GetFileSizeEx(exe_handle, std::addressof(exe_size_li)) == 0) {
return;
}
/* Check the exe size. */
s64 exe_size = exe_size_li.QuadPart;
if (exe_size == 0) {
return;
}
/* Create a file mapping. */
auto map_handle = ::CreateFileMappingW(exe_handle, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (map_handle == INVALID_HANDLE_VALUE) {
return;
}
ON_SCOPE_EXIT { if (map_handle != INVALID_HANDLE_VALUE) { ::CloseHandle(map_handle); } };
/* Map the file. */
void *exe_map = ::MapViewOfFile(map_handle, FILE_MAP_READ, 0, 0, 0);
if (exe_map == nullptr) {
return;
}
ON_SCOPE_EXIT { if (exe_map != nullptr) { ::UnmapViewOfFile(exe_map); } };
/* Get/parse the DOS header. */
const uintptr_t exe_start = reinterpret_cast<uintptr_t>(exe_map);
const auto *dos_header = reinterpret_cast<const IMAGE_DOS_HEADER *>(exe_start);
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
return;
}
/* Set up the nt headers. */
const auto *nt32 = reinterpret_cast<const IMAGE_NT_HEADERS32 *>(exe_start + dos_header->e_lfanew);
const auto *nt64 = reinterpret_cast<const IMAGE_NT_HEADERS64 *>(exe_start + dos_header->e_lfanew);
if (nt32->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 || nt32->FileHeader.Machine == IMAGE_FILE_MACHINE_IA64) {
nt32 = nullptr;
} else {
nt64 = nullptr;
}
#define EXE_NT_HEADER(x) ((nt64 != nullptr) ? nt64->x : nt32->x)
if (EXE_NT_HEADER(Signature) != IMAGE_NT_SIGNATURE) {
return;
}
/* Check that the optional header is really present. */
if (EXE_NT_HEADER(FileHeader.SizeOfOptionalHeader) < sizeof(IMAGE_OPTIONAL_HEADER32)) {
return;
}
/* Get sections. */
const auto *sec = nt64 != nullptr ? IMAGE_FIRST_SECTION(nt64) : IMAGE_FIRST_SECTION(nt32);
/* Get the symbol table. */
const auto *symtab = reinterpret_cast<const IMAGE_SYMBOL *>(exe_start + EXE_NT_HEADER(FileHeader.PointerToSymbolTable));
const size_t nsym = EXE_NT_HEADER(FileHeader.NumberOfSymbols);
const char *strtab = reinterpret_cast<const char *>(symtab + nsym);
/* Find the section containing our code. */
int text_section = -1;
for (size_t i = 0; i < nsym; ++i) {
if (ISFCN(symtab[i].Type)) {
const char *name = symtab[i].N.Name.Short == 0 ? strtab + symtab[i].N.Name.Long : reinterpret_cast<const char *>(symtab[i].N.ShortName);
if (std::strcmp(name, "__module_offset_helper") == 0) {
AMS_ASSERT(text_section == -1);
AMS_ASSERT(m_module_displacement == 0);
m_module_displacement = reinterpret_cast<uintptr_t>(&__module_offset_helper) - symtab[i].Value;
text_section = symtab[i].SectionNumber;
AMS_ASSERT(m_module_displacement != 0);
AMS_ASSERT(text_section != -1);
break;
}
}
}
/* Determine the number of functions. */
size_t funcs = 0;
for (size_t i = 0; i < nsym; ++i) {
if (ISFCN(symtab[i].Type) && symtab[i].SectionNumber == text_section) {
++funcs;
}
}
/* Allocate functions. */
m_symbols = reinterpret_cast<SymbolInfo *>(std::malloc(sizeof(SymbolInfo) * funcs));
if (m_symbols == nullptr) {
return;
}
/* Set all symbols. */
m_num_symbol = 0;
for (size_t i = 0; i < nsym; ++i) {
if (ISFCN(symtab[i].Type) && symtab[i].SectionNumber == text_section) {
m_symbols[m_num_symbol].address = symtab[i].Value;
m_symbols[m_num_symbol].name = symtab[i].N.Name.Short == 0 ? strtab + symtab[i].N.Name.Long : reinterpret_cast<const char *>(symtab[i].N.ShortName);
++m_num_symbol;
}
}
AMS_ASSERT(m_num_symbol == funcs);
/* Sort the symbols. */
std::sort(m_symbols + 0, m_symbols + m_num_symbol, [] (const SymbolInfo &lhs, const SymbolInfo &rhs) {
return lhs.address < rhs.address;
});
m_module_address = 0;
m_module_size = sec[text_section - 1].Misc.VirtualSize;
if (m_module_displacement != 0 && m_module_size > 0 && m_num_symbol > 0) {
std::swap(m_file_handle, exe_handle);
std::swap(m_map_handle, map_handle);
std::swap(m_file_map, exe_map);
m_file_size = exe_size;
}
}
~CurrentExecutableHelper() {
if (m_file_map != nullptr) {
::UnmapViewOfFile(m_file_map);
}
if (m_map_handle != nullptr) {
::CloseHandle(m_map_handle);
}
if (m_file_handle != nullptr) {
::CloseHandle(m_file_handle);
}
}
public:
static CurrentExecutableHelper &GetInstance() {
AMS_FUNCTION_LOCAL_STATIC(CurrentExecutableHelper, s_current_executable_helper_instance);
return s_current_executable_helper_instance;
}
private:
size_t GetSymbolSizeImpl(const SymbolInfo *symbol) const {
/* Do our best to guess. */
if (symbol != m_symbols + m_num_symbol - 1) {
return (symbol + 1)->address - symbol->address;
} else if (m_module_address + m_module_size >= symbol->address) {
return m_module_address + m_module_size - symbol->address;
} else {
return 0;
}
}
const SymbolInfo *GetBestSymbol(uintptr_t address) const {
address -= m_module_displacement;
const SymbolInfo *best_symbol = std::lower_bound(m_symbols + 0, m_symbols + m_num_symbol, address, [](const SymbolInfo &lhs, uintptr_t rhs) {
return lhs.address < rhs;
});
if (best_symbol == m_symbols + m_num_symbol) {
return nullptr;
}
if (best_symbol->address != address && best_symbol > m_symbols) {
--best_symbol;
}
const auto vma = best_symbol->address;
const auto end = vma + this->GetSymbolSizeImpl(best_symbol);
if (vma <= address && address < end) {
return best_symbol;
} else {
return nullptr;
}
}
public:
uintptr_t GetSymbolName(char *dst, size_t dst_size, uintptr_t address) const {
if (m_file_handle == INVALID_HANDLE_VALUE) {
return 0;
}
/* Get the symbol. */
const auto *symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
/* Print the symbol. */
const char *name = symbol->name;
int cpp_name_status = 0;
if (char *demangled = abi::__cxa_demangle(name, nullptr, 0, std::addressof(cpp_name_status)); cpp_name_status == 0) {
AMS_ASSERT(demangled != nullptr);
util::TSNPrintf(dst, dst_size, "%s", demangled);
std::free(demangled);
} else {
util::TSNPrintf(dst, dst_size, "%s", name);
}
return symbol->address + m_module_displacement;
}
size_t GetSymbolSize(uintptr_t address) const {
if (m_file_handle == INVALID_HANDLE_VALUE) {
return 0;
}
/* Get the symbol. */
const auto *symbol = this->GetBestSymbol(address);
if (symbol == nullptr) {
return 0;
}
return this->GetSymbolSizeImpl(symbol);
}
private:
static os::NativeHandle OpenExecutableFile() {
/* Get the module file name. */
wchar_t module_file_name[0x1000];
if (::GetModuleFileNameW(0, module_file_name, util::size(module_file_name)) == 0) {
return INVALID_HANDLE_VALUE;
}
return ::CreateFileW(module_file_name, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
}
};
}
uintptr_t GetSymbolNameImpl(char *dst, size_t dst_size, uintptr_t address) {
return CurrentExecutableHelper::GetInstance().GetSymbolName(dst, dst_size, address);
}
size_t GetSymbolSizeImpl(uintptr_t address) {
return CurrentExecutableHelper::GetInstance().GetSymbolSize(address);
}
}
| 12,877
|
C++
|
.cpp
| 246
| 33.036585
| 256
| 0.466905
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,880
|
diag_abort_observer_manager.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_abort_observer_manager.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_abort_observer_manager.hpp"
namespace ams::diag::impl {
AbortObserverManager *GetAbortObserverManager() {
AMS_FUNCTION_LOCAL_STATIC(AbortObserverManager, s_manager);
return std::addressof(s_manager);
}
SdkAbortObserverManager *GetSdkAbortObserverManager() {
AMS_FUNCTION_LOCAL_STATIC(SdkAbortObserverManager, s_manager);
return std::addressof(s_manager);
}
}
| 1,091
|
C++
|
.cpp
| 27
| 36.888889
| 76
| 0.748582
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,881
|
diag_print_debug_string.os.macos.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_print_debug_string.os.macos.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_print_debug_string.hpp"
namespace ams::diag::impl {
NOINLINE void PrintDebugString(const char *msg, size_t size) {
AMS_AUDIT(msg != nullptr || size == 0);
if (size == 0) {
return;
}
/* TODO: Printf? */
printf("%s", msg);
}
}
| 968
|
C++
|
.cpp
| 27
| 31.925926
| 76
| 0.690171
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,882
|
diag_default_abort_observer.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_default_abort_observer.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_dump_stack_trace.hpp"
#if defined(ATMOSPHERE_OS_WINDOWS)
#include <stratosphere/windows.hpp>
#endif
namespace ams::diag::impl {
#if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_DEBUGGING)
namespace {
constexpr const char *ToString(AbortReason reason) {
switch (reason) {
case AbortReason_Audit:
return "Auditing Assertion Failure";
case AbortReason_Assert:
return "Assertion Failure";
case AbortReason_UnexpectedDefault:
return "Unexpected Default";
case AbortReason_Abort:
default:
return "Abort";
}
}
void DefaultPrinter(const AbortInfo &info) {
/* Get the thread name. */
const char *thread_name;
if (auto *cur_thread = os::GetCurrentThread(); cur_thread != nullptr) {
thread_name = os::GetThreadNamePointer(cur_thread);
} else {
thread_name = "unknown";
}
#if defined(ATMOSPHERE_OS_HORIZON)
{
u64 process_id = 0;
u64 thread_id = 0;
svc::GetProcessId(std::addressof(process_id), svc::PseudoHandle::CurrentProcess);
svc::GetThreadId(std::addressof(thread_id), svc::PseudoHandle::CurrentThread);
AMS_SDK_LOG("%s: '%s' in %s, process=0x%02" PRIX64 ", thread=%" PRIu64 " (%s)\n%s:%d\n", ToString(info.reason), info.expr, info.func, process_id, thread_id, thread_name, info.file, info.line);
}
#elif defined(ATMOSPHERE_OS_WINDOWS)
{
DWORD process_id = ::GetCurrentProcessId();
DWORD thread_id = ::GetCurrentThreadId();
AMS_SDK_LOG("%s: '%s' in %s, process=0x%" PRIX64 ", thread=%" PRIu64 " (%s)\n%s:%d\n", ToString(info.reason), info.expr, info.func, static_cast<u64>(process_id), static_cast<u64>(thread_id), thread_name, info.file, info.line);
}
#else
{
AMS_SDK_LOG("%s: '%s' in %s, thread=%s\n%s:%d\n", ToString(info.reason), info.expr, info.func, thread_name, info.file, info.line);
}
#endif
AMS_SDK_VLOG(info.message->fmt, *(info.message->vl));
AMS_SDK_LOG("\n");
TentativeDumpStackTrace();
}
}
#endif
void DefaultAbortObserver(const AbortInfo &info) {
#if defined(AMS_BUILD_FOR_DEBUGGING) || defined(AMS_BUILD_FOR_AUDITING)
DefaultPrinter(info);
#else
AMS_UNUSED(info);
#endif
}
}
| 3,361
|
C++
|
.cpp
| 77
| 33.597403
| 242
| 0.593645
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,883
|
diag_dump_stack_trace.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_dump_stack_trace.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_dump_stack_trace.hpp"
namespace ams::diag::impl {
void TentativeDumpStackTrace() {
/* TODO */
}
}
| 795
|
C++
|
.cpp
| 22
| 33.636364
| 76
| 0.74026
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,884
|
diag_get_all_backtrace.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_get_all_backtrace.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::diag::impl {
namespace {
constinit uintptr_t g_abort_impl_return_address = std::numeric_limits<uintptr_t>::max();
}
void SetAbortImplReturnAddress(uintptr_t address) {
g_abort_impl_return_address = address;
}
size_t GetAllBacktrace(uintptr_t *out, size_t out_size, ::ams::diag::Backtrace &bt) {
size_t count = 0;
do {
/* Check that we can write another return address. */
if (count >= out_size) {
break;
}
/* Get the current return address. */
const uintptr_t ret_addr = bt.GetReturnAddress();
/* If it's abort impl, reset the trace we're writing. */
if (ret_addr == g_abort_impl_return_address) {
count = 0;
}
/* Set the output pointer. */
out[count++] = ret_addr;
} while (bt.Step());
/* Return the number of addresses written. */
return count;
}
}
| 1,672
|
C++
|
.cpp
| 43
| 31.906977
| 96
| 0.631644
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,885
|
diag_print_debug_string.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_print_debug_string.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "diag_print_debug_string.hpp"
namespace ams::diag::impl {
void PrintDebugString(const char *msg, size_t size) {
AMS_AUDIT(msg != nullptr || size == 0);
if (size != 0) {
svc::OutputDebugString(msg, size);
}
}
}
| 930
|
C++
|
.cpp
| 25
| 33.72
| 76
| 0.709212
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,886
|
diag_process.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_process.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
/* TODO: Rename, if we change to e.g. use amsMain? */
extern "C" int main(int argc, char **argv);
namespace ams::diag::impl {
uintptr_t GetModuleInfoForHorizon(const char **out_path, size_t *out_path_length, size_t *out_module_size, uintptr_t address);
namespace {
const char *GetLastCharacterPointer(const char *str, size_t len, char c) {
for (const char *last = str + len - 1; last >= str; --last) {
if (*last == c) {
return last;
}
}
return nullptr;
}
void GetFileNameWithoutExtension(const char **out, size_t *out_size, const char *path, size_t path_length) {
const auto last_sep1 = GetLastCharacterPointer(path, path_length, '\\');
const auto last_sep2 = GetLastCharacterPointer(path, path_length, '/');
const auto ext = GetLastCharacterPointer(path, path_length, '.');
/* Handle last-separator. */
if (last_sep1 && last_sep2) {
if (last_sep1 > last_sep2) {
*out = last_sep1 + 1;
} else {
*out = last_sep2 + 1;
}
} else if (last_sep1) {
*out = last_sep1 + 1;
} else if (last_sep2) {
*out = last_sep2 + 1;
} else {
*out = path;
}
/* Handle extension. */
if (ext && ext >= *out) {
*out_size = ext - *out;
} else {
*out_size = (path + path_length) - *out;
}
}
constinit const char *g_process_name = nullptr;
constinit size_t g_process_name_size = 0;
constinit os::SdkMutex g_process_name_lock;
constinit bool g_got_process_name = false;
void EnsureProcessNameCached() {
/* Ensure process name. */
if (AMS_UNLIKELY(!g_got_process_name)) {
std::scoped_lock lk(g_process_name_lock);
if (AMS_LIKELY(!g_got_process_name)) {
const char *path;
size_t path_length;
size_t module_size;
if (GetModuleInfoForHorizon(std::addressof(path), std::addressof(path_length), std::addressof(module_size), reinterpret_cast<uintptr_t>(main)) != 0) {
GetFileNameWithoutExtension(std::addressof(g_process_name), std::addressof(g_process_name_size), path, path_length);
AMS_ASSERT(g_process_name_size == 0 || util::VerifyUtf8String(g_process_name, g_process_name_size));
} else {
g_process_name = "";
g_process_name_size = 0;
}
g_got_process_name = true;
}
}
}
}
void GetProcessNamePointer(const char **out, size_t *out_size) {
/* Ensure process name is cached. */
EnsureProcessNameCached();
/* Get cached process name. */
*out = g_process_name;
*out_size = g_process_name_size;
}
}
| 3,822
|
C++
|
.cpp
| 86
| 32.953488
| 170
| 0.551075
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,887
|
diag_backtrace_impl.os.generic.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_backtrace_impl.os.generic.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#if defined(ATMOSPHERE_OS_WINDOWS)
#include <stratosphere/windows.hpp>
#elif defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS)
#include <fcntl.h>
#include <unistd.h>
#endif
namespace ams::diag::impl {
namespace {
#if defined(ATMOSPHERE_ARCH_X64)
struct StackFrame {
u64 fp; /* rbp */
u64 lr; /* rip */
};
#elif defined(ATMOSPHERE_ARCH_X86)
struct StackFrame {
u32 fp; /* ebp */
u32 lr; /* eip */
}
#elif defined(ATMOSPHERE_ARCH_ARM64)
struct StackFrame {
u64 fp;
u64 lr;
};
#elif defined(ATMOSPHERE_ARCH_ARM)
struct StackFrame {
u32 fp;
u32 lr;
}
#else
#error "Unknown architecture for generic backtrace."
#endif
bool TryRead(os::NativeHandle native_handle, void *dst, size_t size, const void *address) {
#if defined(ATMOSPHERE_OS_WINDOWS)
return ::ReadProcessMemory(native_handle, address, dst, size, nullptr);
#elif defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS)
s32 ret;
do {
ret = ::write(native_handle, address, size);
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
return false;
}
std::memcpy(dst, address, size);
return true;
#else
#error "Unknown OS for Backtrace native handle"
#endif
}
}
NOINLINE void Backtrace::Initialize() {
/* Clear our size. */
m_index = 0;
m_size = 0;
/* Get the base frame pointer. */
const void *cur_fp = __builtin_frame_address(0);
/* Try to read stack frames, until we run out. */
#if defined(ATMOSPHERE_OS_WINDOWS)
const os::NativeHandle native_handle = ::GetCurrentProcess();
#elif defined(ATMOSPHERE_OS_LINUX) || defined(ATMOSPHERE_OS_MACOS)
os::NativeHandle pipe_handles[2];
s32 nret;
do { nret = ::pipe(pipe_handles); } while (nret < 0 && errno == EINTR);
if (nret < 0) { return; }
do { nret = ::fcntl(pipe_handles[0], F_SETFL, O_NONBLOCK); } while (nret < 0 && errno == EINTR);
if (nret < 0) { return; }
do { nret = ::fcntl(pipe_handles[1], F_SETFL, O_NONBLOCK); } while (nret < 0 && errno == EINTR);
if (nret < 0) { return; }
ON_SCOPE_EXIT {
do { nret = ::close(pipe_handles[0]); } while (nret < 0 && errno == EINTR);
do { nret = ::close(pipe_handles[1]); } while (nret < 0 && errno == EINTR);
};
const os::NativeHandle native_handle = pipe_handles[1];
if (native_handle < 0) { return; }
#else
#error "Unknown OS for Backtrace native handle"
#endif
StackFrame frame;
while (m_size < BacktraceEntryCountMax) {
/* Clear the frame. */
frame = {};
/* Read the next frame. */
if (!TryRead(native_handle, std::addressof(frame), sizeof(frame), cur_fp)) {
break;
}
/* Add the return address. */
m_backtrace_addresses[m_size++] = reinterpret_cast<void *>(frame.lr);
/* Set the next fp. */
cur_fp = reinterpret_cast<const void *>(frame.fp);
}
}
bool Backtrace::Step() {
return (++m_index) < m_size;
}
uintptr_t Backtrace::GetStackPointer() const {
return 0;
}
uintptr_t Backtrace::GetReturnAddress() const {
return reinterpret_cast<uintptr_t>(m_backtrace_addresses[m_index]);
}
}
| 4,387
|
C++
|
.cpp
| 116
| 29.12069
| 104
| 0.573377
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,888
|
diag_backtrace_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_backtrace_impl.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::diag::impl {
namespace {
uintptr_t GetAddressValue(uintptr_t address) {
if (address == 0) {
return 0;
}
if (!util::IsAligned(address, alignof(uintptr_t))) {
return 0;
}
return *reinterpret_cast<uintptr_t *>(address);
}
template<typename T, size_t N>
svc::MemoryInfo *GetMemoryInfoPointer(T (&arr)[N]) {
/* Check that there's enough space. */
static_assert(sizeof(T) * N <= sizeof(svc::MemoryInfo));
static_assert(alignof(T) >= alignof(svc::MemoryInfo));
return reinterpret_cast<svc::MemoryInfo *>(std::addressof(arr[0]));
}
bool IsValidLinkRegisterValue(uintptr_t lr, svc::MemoryInfo *info) {
/* Ensure the memory info is valid. */
Result query_res;
if (!(info->base_address <= lr && lr < info->base_address + info->size) && ({ svc::PageInfo page_info; query_res = svc::QueryMemory(info, std::addressof(page_info), lr); R_FAILED(query_res); })) {
AMS_SDK_LOG("Failed to get backtrace. Query memory failed. (lr: %p, result: %03d-%04d)\n", reinterpret_cast<void *>(lr), query_res.GetModule(), query_res.GetDescription());
return false;
}
/* Check that lr is valid. */
if (lr == 0) {
return false;
}
if (!util::IsAligned(lr, sizeof(u32))) {
AMS_SDK_LOG("Failed to get backtrace. The link register alignment is invalid. (lr: %p)\n", reinterpret_cast<void *>(lr));
return false;
}
/* Check that the lr points to code. */
if (info->permission != svc::MemoryPermission_ReadExecute) {
AMS_SDK_LOG("Failed to get backtrace. The link register points out of the code. (lr: %p)\n", reinterpret_cast<void *>(lr));
return false;
}
return true;
}
void GetNormalStackInfo(Backtrace::StackInfo *out) {
if (void * const fiber = nullptr /* TODO: os::GetCurrentFiber() */; fiber == nullptr) {
/* Get thread. */
auto * const thread = os::GetCurrentThread();
out->stack_top = reinterpret_cast<uintptr_t>(thread->stack);
out->stack_bottom = reinterpret_cast<uintptr_t>(thread->stack) + thread->stack_size;
} else {
/* TODO: Fiber. */
}
}
bool GetExceptionStackInfo(Backtrace::StackInfo *out, uintptr_t sp) {
/* Get the current stack info. */
uintptr_t cur_stack = 0;
size_t cur_stack_size = 0;
os::GetCurrentStackInfo(std::addressof(cur_stack), std::addressof(cur_stack_size));
/* Get the thread's stack info. */
uintptr_t thread_stack = 0;
size_t thread_stack_size = 0;
os::GetThreadStackInfo(std::addressof(thread_stack), std::addressof(thread_stack_size), os::GetCurrentThread());
/* If the current stack is the thread stack, exception stack isn't being used. */
if (cur_stack == thread_stack) {
AMS_ASSERT(cur_stack_size == thread_stack_size);
return false;
}
/* Check if the stack pointer is contained in the current stack. */
if (!(cur_stack <= sp && sp < cur_stack + cur_stack_size)) {
return false;
}
/* Set the output. */
out->stack_top = cur_stack;
out->stack_bottom = cur_stack + cur_stack_size;
return true;
}
}
NOINLINE void Backtrace::Initialize() {
/* Get the stack pointer/frame pointer. */
uintptr_t fp, sp;
__asm__ __volatile__(
#if defined(ATMOSPHERE_ARCH_ARM64)
"mov %[fp], fp\n"
"mov %[sp], sp\n"
#elif defined(ATMOSPHERE_ARCH_ARM)
"mov %[fp], x29\n"
"mov %[sp], sp\n"
#else
#error "Unknown architecture for Horizon fp/sp retrieval."
#endif
: [fp]"=&r"(fp), [sp]"=&r"(sp)
:
: "memory"
);
/* Set our stack info. */
this->SetStackInfo(fp, sp);
/* Step, to get our first lr. */
this->Step();
}
void Backtrace::Initialize(uintptr_t fp, uintptr_t sp, uintptr_t pc) {
/* Set our initial lr. */
m_lr = pc;
/* Set our stack info. */
this->SetStackInfo(fp, sp);
}
bool Backtrace::Step() {
/* We can't step without a frame pointer. */
if (m_fp == 0) {
if (m_current_stack_info != std::addressof(m_normal_stack_info)) {
AMS_SDK_LOG("Failed to get backtrace. The frame pointer is null.\n");
}
return false;
}
/* The frame pointer needs to be aligned. */
if (!util::IsAligned(m_fp, sizeof(uintptr_t))) {
AMS_SDK_LOG("Failed to get backtrace. The frame pointer alignment is invalid. (fp: %p)\n", reinterpret_cast<void *>(m_fp));
return false;
}
/* Ensure our current stack info is good. */
if (!(m_current_stack_info->stack_top <= m_fp && m_fp < m_current_stack_info->stack_bottom)) {
if (m_current_stack_info != std::addressof(m_exception_stack_info) || !(m_normal_stack_info.stack_top <= m_fp && m_fp < m_normal_stack_info.stack_bottom)) {
AMS_SDK_LOG("Failed to get backtrace. The frame pointer points out of the stack. (fp: %p, stack: %p-%p)\n", reinterpret_cast<void *>(m_fp), reinterpret_cast<void *>(m_current_stack_info->stack_top), reinterpret_cast<void *>(m_current_stack_info->stack_bottom));
return false;
}
m_current_stack_info = std::addressof(m_normal_stack_info);
} else if (m_fp <= m_prev_fp) {
AMS_SDK_LOG("Failed to get backtrace. The frame pointer is rewinding. (fp: %p, prev fp: %p, stack: %p-%p)\n", reinterpret_cast<void *>(m_fp), reinterpret_cast<void *>(m_prev_fp), reinterpret_cast<void *>(m_current_stack_info->stack_top), reinterpret_cast<void *>(m_current_stack_info->stack_bottom));
return false;
}
/* Update our previous fp. */
m_prev_fp = m_fp;
/* Read lr/fp. */
m_lr = GetAddressValue(m_fp + sizeof(m_fp));
m_fp = GetAddressValue(m_fp);
/* Check that lr is valid. */
if (IsValidLinkRegisterValue(m_lr, GetMemoryInfoPointer(m_memory_info_buffer))) {
return true;
} else {
m_lr = 0;
return false;
}
}
uintptr_t Backtrace::GetStackPointer() const {
if (m_fp != 0) {
return m_fp - sizeof(m_fp);
} else {
return m_current_stack_info->stack_bottom - sizeof(m_fp);
}
}
uintptr_t Backtrace::GetReturnAddress() const {
return m_lr;
}
void Backtrace::SetStackInfo(uintptr_t fp, uintptr_t sp) {
/* Get the normal stack info. */
GetNormalStackInfo(std::addressof(m_normal_stack_info));
/* Get the exception stack info. */
if (GetExceptionStackInfo(std::addressof(m_exception_stack_info), sp)) {
m_current_stack_info = std::addressof(m_exception_stack_info);
} else {
m_current_stack_info = std::addressof(m_normal_stack_info);
}
/* Set our frame pointer. */
m_fp = fp;
}
}
| 8,297
|
C++
|
.cpp
| 178
| 35.808989
| 312
| 0.561881
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,889
|
diag_module_impl.os.horizon.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/diag/impl/diag_module_impl.os.horizon.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::diag::impl {
namespace {
constexpr inline uintptr_t ModulePathLengthOffset = 4;
constexpr inline uintptr_t ModulePathOffset = 8;
}
uintptr_t GetModuleInfoForHorizon(const char **out_path, size_t *out_path_length, size_t *out_module_size, uintptr_t address) {
/* Check for null address. */
if (address == 0) {
return 0;
}
/* Get module info. */
ro::impl::ExceptionInfo exception_info;
if (!ro::impl::GetExceptionInfo(std::addressof(exception_info), address)) {
return 0;
}
/* Locate the path in the first non-read-execute segment. */
svc::MemoryInfo mem_info;
svc::PageInfo page_info;
auto cur_address = exception_info.module_address;
while (cur_address < exception_info.module_address + exception_info.module_size) {
if (R_FAILED(svc::QueryMemory(std::addressof(mem_info), std::addressof(page_info), cur_address))) {
return 0;
}
if (mem_info.permission != svc::MemoryPermission_ReadExecute) {
break;
}
cur_address += mem_info.size;
}
/* Set output info. */
*out_path = reinterpret_cast<const char *>(cur_address + ModulePathOffset);
*out_path_length = *reinterpret_cast<const u32 *>(cur_address + ModulePathLengthOffset);
*out_module_size = exception_info.module_size;
return exception_info.module_address;
}
}
| 2,204
|
C++
|
.cpp
| 51
| 36.019608
| 131
| 0.650957
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,890
|
pm_dmnt_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pm/pm_dmnt_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_ams.os.horizon.h"
namespace ams::pm::dmnt {
/* Debug Monitor API. */
#if defined(ATMOSPHERE_OS_HORIZON)
Result StartProcess(os::ProcessId process_id) {
R_RETURN(pmdmntStartProcess(static_cast<u64>(process_id)));
}
Result GetProgramId(ncm::ProgramId *out_program_id, os::ProcessId process_id) {
R_RETURN(pmdmntGetProgramId(reinterpret_cast<u64 *>(out_program_id), static_cast<u64>(process_id)));
}
Result GetProcessId(os::ProcessId *out_process_id, const ncm::ProgramId program_id) {
R_RETURN(pmdmntGetProcessId(reinterpret_cast<u64 *>(out_process_id), static_cast<u64>(program_id)));
}
Result GetApplicationProcessId(os::ProcessId *out_process_id) {
R_RETURN(pmdmntGetApplicationProcessId(reinterpret_cast<u64 *>(out_process_id)));
}
Result HookToCreateApplicationProcess(os::NativeHandle *out_handle) {
Event evt;
R_TRY(pmdmntHookToCreateApplicationProcess(std::addressof(evt)));
*out_handle = evt.revent;
R_SUCCEED();
}
Result HookToCreateProcess(os::NativeHandle *out_handle, const ncm::ProgramId program_id) {
Event evt;
R_TRY(pmdmntHookToCreateProcess(std::addressof(evt), static_cast<u64>(program_id)));
*out_handle = evt.revent;
R_SUCCEED();
}
Result AtmosphereGetProcessInfo(os::NativeHandle *out_handle, ncm::ProgramLocation *out_loc, cfg::OverrideStatus *out_status, os::ProcessId process_id) {
*out_handle = os::InvalidNativeHandle;
*out_loc = {};
*out_status = {};
static_assert(sizeof(*out_status) == sizeof(CfgOverrideStatus));
R_RETURN(pmdmntAtmosphereGetProcessInfo(out_handle, reinterpret_cast<NcmProgramLocation *>(out_loc), reinterpret_cast<CfgOverrideStatus *>(out_status), static_cast<u64>(process_id)));
}
Result AtmosphereGetCurrentLimitInfo(u64 *out_current_value, u64 *out_limit_value, ResourceLimitGroup group, svc::LimitableResource resource) {
*out_current_value = 0;
*out_limit_value = 0;
R_RETURN(pmdmntAtmosphereGetCurrentLimitInfo(out_current_value, out_limit_value, group, resource));
}
#endif
}
| 2,854
|
C++
|
.cpp
| 58
| 43.706897
| 191
| 0.713106
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,891
|
pm_info_api_weak.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pm/pm_info_api_weak.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_ams.os.horizon.h"
namespace ams::pm::info {
/* Information API. */
#if defined(ATMOSPHERE_OS_HORIZON)
Result WEAK_SYMBOL HasLaunchedBootProgram(bool *out, ncm::ProgramId program_id) {
bool has_launched = false;
R_TRY(pminfoAtmosphereHasLaunchedBootProgram(std::addressof(has_launched), static_cast<u64>(program_id)));
*out = has_launched;
R_SUCCEED();
}
#endif
}
| 1,094
|
C++
|
.cpp
| 28
| 35.607143
| 114
| 0.727187
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,892
|
pm_boot_mode_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pm/pm_boot_mode_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
namespace ams::pm::bm {
/* Boot Mode API. */
/* Both functions should be weakly linked, so that they can be overridden by ams::boot2 as needed. */
#if defined(ATMOSPHERE_OS_HORIZON)
BootMode WEAK_SYMBOL GetBootMode() {
PmBootMode boot_mode = PmBootMode_Normal;
R_ABORT_UNLESS(pmbmGetBootMode(std::addressof(boot_mode)));
return static_cast<BootMode>(boot_mode);
}
void WEAK_SYMBOL SetMaintenanceBoot() {
R_ABORT_UNLESS(pmbmSetMaintenanceBoot());
}
#else
BootMode WEAK_SYMBOL GetBootMode() {
AMS_ABORT("TODO");
}
void WEAK_SYMBOL SetMaintenanceBoot() {
AMS_ABORT("TODO");
}
#endif
}
| 1,350
|
C++
|
.cpp
| 37
| 32.27027
| 105
| 0.706422
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,893
|
pm_info_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pm/pm_info_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_ams.os.horizon.h"
namespace ams::pm::info {
/* Information API. */
#if defined(ATMOSPHERE_OS_HORIZON)
Result GetProgramId(ncm::ProgramId *out_program_id, os::ProcessId process_id) {
R_RETURN(pminfoGetProgramId(reinterpret_cast<u64 *>(out_program_id), static_cast<u64>(process_id)));
}
Result GetProcessId(os::ProcessId *out_process_id, ncm::ProgramId program_id) {
R_RETURN(pminfoAtmosphereGetProcessId(reinterpret_cast<u64 *>(out_process_id), static_cast<u64>(program_id)));
}
Result GetAppletResourceLimitCurrentValue(pm::ResourceLimitValue *out) {
static_assert(sizeof(pm::ResourceLimitValue) == sizeof(::PmResourceLimitValues));
R_RETURN(pminfoGetAppletCurrentResourceLimitValues(reinterpret_cast<PmResourceLimitValues *>(out)));
}
Result GetAppletResourceLimitPeakValue(pm::ResourceLimitValue *out) {
static_assert(sizeof(pm::ResourceLimitValue) == sizeof(::PmResourceLimitValues));
R_RETURN(pminfoGetAppletPeakResourceLimitValues(reinterpret_cast<PmResourceLimitValues *>(out)));
}
Result GetProcessInfo(ncm::ProgramLocation *out_loc, cfg::OverrideStatus *out_status, os::ProcessId process_id) {
*out_loc = {};
*out_status = {};
static_assert(sizeof(*out_status) == sizeof(CfgOverrideStatus));
R_RETURN(pminfoAtmosphereGetProcessInfo(reinterpret_cast<NcmProgramLocation *>(out_loc), reinterpret_cast<CfgOverrideStatus *>(out_status), static_cast<u64>(process_id)));
}
bool HasLaunchedBootProgram(ncm::ProgramId program_id) {
bool has_launched = false;
R_ABORT_UNLESS(HasLaunchedBootProgram(std::addressof(has_launched), program_id));
return has_launched;
}
Result IsHblProcessId(bool *out, os::ProcessId process_id) {
ncm::ProgramLocation loc;
cfg::OverrideStatus override_status;
R_TRY(GetProcessInfo(std::addressof(loc), std::addressof(override_status), process_id));
*out = override_status.IsHbl();
R_SUCCEED();
}
Result IsHblProgramId(bool *out, ncm::ProgramId program_id) {
os::ProcessId process_id;
R_TRY(GetProcessId(std::addressof(process_id), program_id));
R_RETURN(IsHblProcessId(out, process_id));
}
#endif
}
| 2,959
|
C++
|
.cpp
| 59
| 44.559322
| 179
| 0.719778
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,894
|
pm_shell_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libstratosphere/source/pm/pm_shell_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stratosphere.hpp>
#include "pm_ams.os.horizon.h"
namespace ams::pm::shell {
/* Shell API. */
#if defined(ATMOSPHERE_OS_HORIZON)
Result WEAK_SYMBOL LaunchProgram(os::ProcessId *out, const ncm::ProgramLocation &loc, u32 launch_flags) {
static_assert(sizeof(ncm::ProgramLocation) == sizeof(NcmProgramLocation));
static_assert(alignof(ncm::ProgramLocation) == alignof(NcmProgramLocation));
R_RETURN(pmshellLaunchProgram(launch_flags, reinterpret_cast<const NcmProgramLocation *>(std::addressof(loc)), reinterpret_cast<u64 *>(out)));
}
Result TerminateProcess(os::ProcessId process_id) {
R_RETURN(::pmshellTerminateProcess(static_cast<u64>(process_id)));
}
Result GetProcessEventEvent(os::SystemEvent *out) {
::Event evt;
R_TRY(::pmshellGetProcessEventHandle(std::addressof(evt)));
out->Attach(evt.revent, true, svc::InvalidHandle, false, os::EventClearMode_ManualClear);
R_SUCCEED();
}
Result GetProcessEventInfo(ProcessEventInfo *out) {
static_assert(sizeof(*out) == sizeof(::PmProcessEventInfo));
R_RETURN(::pmshellGetProcessEventInfo(reinterpret_cast<::PmProcessEventInfo *>(out)));
}
Result GetApplicationProcessIdForShell(os::ProcessId *out) {
static_assert(sizeof(*out) == sizeof(u64));
R_RETURN(::pmshellGetApplicationProcessIdForShell(reinterpret_cast<u64 *>(out)));
}
Result BoostSystemMemoryResourceLimit(u64 size) {
R_RETURN(::pmshellBoostSystemMemoryResourceLimit(size));
}
Result BoostApplicationThreadResourceLimit() {
R_RETURN(::pmshellBoostApplicationThreadResourceLimit());
}
Result BoostSystemThreadResourceLimit() {
R_RETURN(::pmshellBoostSystemThreadResourceLimit());
}
#endif
}
| 2,446
|
C++
|
.cpp
| 53
| 41
| 150
| 0.723877
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,895
|
util_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/util/util_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::util {
namespace {
constinit uintptr_t g_timer_register_address = secmon::MemoryRegionPhysicalDeviceTimer.GetAddress();
ALWAYS_INLINE uintptr_t GetCurrentTimeRegisterAddress() {
return g_timer_register_address + 0x10;
}
}
void SetRegisterAddress(uintptr_t address) {
g_timer_register_address = address;
}
u32 GetMicroSeconds() {
return reg::Read(GetCurrentTimeRegisterAddress());
}
void WaitMicroSeconds(int us) {
const u32 start = reg::Read(GetCurrentTimeRegisterAddress());
u32 cur = start;
while ((cur - start) <= static_cast<u32>(us)) {
cur = reg::Read(GetCurrentTimeRegisterAddress());
}
}
void ClearMemory(void *ptr, size_t size) {
std::memset(ptr, 0, size);
}
}
| 1,497
|
C++
|
.cpp
| 40
| 32.25
| 108
| 0.69268
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,896
|
ams_impl_unexpected_default.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/impl/ams_impl_unexpected_default.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::impl {
NORETURN void UnexpectedDefaultImpl(const char *func, const char *file, int line) {
::ams::diag::AbortImpl("", func, file, line);
}
}
| 833
|
C++
|
.cpp
| 21
| 37.190476
| 86
| 0.738272
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,897
|
hw_cache.arch.arm.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/hw/hw_cache.arch.arm.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::hw::arch::arm {
#ifdef __BPMP__
namespace {
constexpr inline uintptr_t AVP_CACHE = AVP_CACHE_ADDR(0);
ALWAYS_INLINE bool IsLargeBuffer(size_t size) {
/* From TRM: For very large physical buffers or when the full cache needs to be cleared, */
/* software should simply loop over all lines in all ways and run the *_LINE command on each of them. */
return size >= DataCacheSize / 4;
}
ALWAYS_INLINE bool IsCacheEnabled() {
return reg::HasValue(AVP_CACHE + AVP_CACHE_CONFIG, AVP_CACHE_REG_BITS_ENUM(CONFIG_ENABLE_CACHE, TRUE));
}
void DoPhyCacheOperation(AVP_CACHE_MAINT_OPCODE op, uintptr_t addr) {
/* Clear maintenance done. */
reg::Write(AVP_CACHE + AVP_CACHE_INT_CLEAR, AVP_CACHE_REG_BITS_ENUM(INT_CLEAR_MAINTENANCE_DONE, TRUE));
/* Write maintenance address. */
reg::Write(AVP_CACHE + AVP_CACHE_MAINT_0, addr);
/* Write maintenance request. */
reg::Write(AVP_CACHE + AVP_CACHE_MAINT_2, AVP_CACHE_REG_BITS_VALUE(MAINT_2_WAY_BITMAP, 0x0),
AVP_CACHE_REG_BITS_VALUE(MAINT_2_OPCODE, op));
/* Wait for maintenance to be done. */
while (!reg::HasValue(AVP_CACHE + AVP_CACHE_INT_RAW_EVENT, AVP_CACHE_REG_BITS_ENUM(INT_RAW_EVENT_MAINTENANCE_DONE, TRUE))) {
/* ... */
}
/* Clear raw event. */
reg::Write(AVP_CACHE + AVP_CACHE_INT_CLEAR, reg::Read(AVP_CACHE + AVP_CACHE_INT_RAW_EVENT));
}
void DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE op) {
/* Clear maintenance done. */
reg::Write(AVP_CACHE + AVP_CACHE_INT_CLEAR, AVP_CACHE_REG_BITS_ENUM(INT_CLEAR_MAINTENANCE_DONE, TRUE));
/* Write maintenance request. */
reg::Write(AVP_CACHE + AVP_CACHE_MAINT_2, AVP_CACHE_REG_BITS_VALUE(MAINT_2_WAY_BITMAP, 0xF),
AVP_CACHE_REG_BITS_VALUE(MAINT_2_OPCODE, op));
/* Wait for maintenance to be done. */
while (!reg::HasValue(AVP_CACHE + AVP_CACHE_INT_RAW_EVENT, AVP_CACHE_REG_BITS_ENUM(INT_RAW_EVENT_MAINTENANCE_DONE, TRUE))) {
/* ... */
}
/* Clear raw event. */
reg::Write(AVP_CACHE + AVP_CACHE_INT_CLEAR, reg::Read(AVP_CACHE + AVP_CACHE_INT_RAW_EVENT));
}
}
#define REQUIRE_CACHE_ENABLED() \
do { \
if (AMS_UNLIKELY(!IsCacheEnabled())) { \
return; \
} \
} while (false) \
#define REQUIRE_CACHE_DISABLED() \
do { \
if (AMS_UNLIKELY(IsCacheEnabled())) { \
return; \
} \
} while (false) \
void InitializeDataCache() {
REQUIRE_CACHE_DISABLED();
/* Issue init mmu command. */
reg::Write(AVP_CACHE + AVP_CACHE_MMU_CMD, AVP_CACHE_REG_BITS_ENUM(MMU_CMD_CMD, INIT));
/* Set mmu fallback entry as RWX, uncached. */
reg::Write(AVP_CACHE + AVP_CACHE_MMU_FALLBACK_ENTRY, AVP_CACHE_REG_BITS_ENUM(MMU_FALLBACK_ENTRY_WR_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_FALLBACK_ENTRY_RD_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_FALLBACK_ENTRY_EXE_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_FALLBACK_ENTRY_CACHED, DISABLE));
/* Set mmu cfg. */
reg::Write(AVP_CACHE + AVP_CACHE_MMU_CFG, AVP_CACHE_REG_BITS_ENUM(MMU_CFG_CLR_ABORT, NOP),
AVP_CACHE_REG_BITS_ENUM(MMU_CFG_ABORT_MODE, STORE_LAST),
AVP_CACHE_REG_BITS_ENUM(MMU_CFG_SEQ_CHECK_ALL_ENTRIES, DISABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_CFG_TLB_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_CFG_SEQ_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(MMU_CFG_BLOCK_MAIN_ENTRY_WR, DISABLE));
/* Initialize mmu entries. */
{
/* Clear shadow copy mask. */
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_COPY_MASK_0, 0);
/* Add DRAM as index 0, RWX/Cached. */
{
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_0_MIN_ADDR, 0x80000000);
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_0_MAX_ADDR, util::AlignDown(0xFFFFFFFF, DataCacheLineSize));
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_0_CFG, AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_WR_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_RD_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_EXE_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_CACHED, ENABLE));
reg::SetBits(AVP_CACHE + AVP_CACHE_MMU_SHADOW_COPY_MASK_0, (1 << 0));
}
/* Add IRAM as index 1, RWX/Cached. */
{
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_1_MIN_ADDR, 0x40000000);
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_1_MAX_ADDR, util::AlignDown(0x4003FFFF, DataCacheLineSize));
reg::Write(AVP_CACHE + AVP_CACHE_MMU_SHADOW_ENTRY_1_CFG, AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_WR_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_RD_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_EXE_ENA, ENABLE),
AVP_CACHE_REG_BITS_ENUM(SHADOW_ENTRY_CFG_CACHED, ENABLE));
reg::SetBits(AVP_CACHE + AVP_CACHE_MMU_SHADOW_COPY_MASK_0, (1 << 1));
}
/* Issue copy shadow mmu command. */
reg::Write(AVP_CACHE + AVP_CACHE_MMU_CMD, AVP_CACHE_REG_BITS_ENUM(MMU_CMD_CMD, COPY_SHADOW));
}
/* Invalidate entire cache. */
DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE_INVALID_WAY);
/* Enable the cache. */
reg::Write(AVP_CACHE + AVP_CACHE_CONFIG, AVP_CACHE_REG_BITS_ENUM(CONFIG_ENABLE_CACHE, TRUE),
AVP_CACHE_REG_BITS_ENUM(CONFIG_FORCE_WRITE_THROUGH, TRUE),
AVP_CACHE_REG_BITS_ENUM(CONFIG_MMU_TAG_MODE, PARALLEL),
AVP_CACHE_REG_BITS_ENUM(CONFIG_TAG_CHECK_ABORT_ON_ERROR, TRUE));
/* Invalidate entire cache again (WAR for hardware bug). */
DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE_INVALID_WAY);
}
void FinalizeDataCache() {
REQUIRE_CACHE_ENABLED();
/* Flush entire data cache. */
FlushEntireDataCache();
/* Disable cache. */
reg::Write(AVP_CACHE + AVP_CACHE_CONFIG, AVP_CACHE_REG_BITS_ENUM(CONFIG_ENABLE_CACHE, FALSE));
}
void InvalidateEntireDataCache() {
REQUIRE_CACHE_ENABLED();
DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE_INVALID_WAY);
}
void StoreEntireDataCache() {
REQUIRE_CACHE_ENABLED();
DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE_CLEAN_WAY);
}
void FlushEntireDataCache() {
REQUIRE_CACHE_ENABLED();
DoEntireCacheOperation(AVP_CACHE_MAINT_OPCODE_CLEAN_INVALID_WAY);
}
void InvalidateDataCacheLine(void *ptr) {
/* NOTE: Don't check cache enabled as an optimization, as only direct caller will be InvalidateDataCache(). */
/* REQUIRE_CACHE_ENABLED(); */
DoPhyCacheOperation(AVP_CACHE_MAINT_OPCODE_INVALID_PHY, reinterpret_cast<uintptr_t>(ptr));
}
void StoreDataCacheLine(void *ptr) {
/* NOTE: Don't check cache enabled as an optimization, as only direct caller will be FlushDataCache(). */
/* REQUIRE_CACHE_ENABLED(); */
DoPhyCacheOperation(AVP_CACHE_MAINT_OPCODE_CLEAN_PHY, reinterpret_cast<uintptr_t>(ptr));
}
void FlushDataCacheLine(void *ptr) {
/* NOTE: Don't check cache enabled as an optimization, as only direct caller will be FlushDataCache(). */
/* REQUIRE_CACHE_ENABLED(); */
DoPhyCacheOperation(AVP_CACHE_MAINT_OPCODE_CLEAN_INVALID_PHY, reinterpret_cast<uintptr_t>(ptr));
}
void InvalidateDataCache(void *ptr, size_t size) {
REQUIRE_CACHE_ENABLED();
if (IsLargeBuffer(size)) {
InvalidateEntireDataCache();
} else {
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
const uintptr_t end = util::AlignUp(start + size, hw::DataCacheLineSize);
for (uintptr_t cur = start; cur < end; cur += hw::DataCacheLineSize) {
InvalidateDataCacheLine(reinterpret_cast<void *>(cur));
}
}
}
void StoreDataCache(const void *ptr, size_t size) {
REQUIRE_CACHE_ENABLED();
if (IsLargeBuffer(size)) {
StoreEntireDataCache();
} else {
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
const uintptr_t end = util::AlignUp(start + size, hw::DataCacheLineSize);
for (uintptr_t cur = start; cur < end; cur += hw::DataCacheLineSize) {
StoreDataCacheLine(reinterpret_cast<void *>(cur));
}
}
}
void FlushDataCache(const void *ptr, size_t size) {
REQUIRE_CACHE_ENABLED();
if (IsLargeBuffer(size)) {
FlushEntireDataCache();
} else {
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
const uintptr_t end = util::AlignUp(start + size, hw::DataCacheLineSize);
for (uintptr_t cur = start; cur < end; cur += hw::DataCacheLineSize) {
FlushDataCacheLine(reinterpret_cast<void *>(cur));
}
}
}
#endif
}
| 11,396
|
C++
|
.cpp
| 194
| 44
| 136
| 0.544957
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,898
|
hw_cache.arch.arm64.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/hw/hw_cache.arch.arm64.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::hw::arch::arm64 {
void FlushDataCache(const void *ptr, size_t size) {
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
const uintptr_t end = util::AlignUp(start + size, hw::DataCacheLineSize);
for (uintptr_t cur = start; cur < end; cur += hw::DataCacheLineSize) {
FlushDataCacheLine(reinterpret_cast<void *>(cur));
}
}
void InvalidateDataCache(const void *ptr, size_t size) {
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
const uintptr_t end = util::AlignUp(start + size, hw::DataCacheLineSize);
for (uintptr_t cur = start; cur < end; cur += hw::DataCacheLineSize) {
InvalidateDataCacheLine(reinterpret_cast<void *>(cur));
}
}
}
| 1,440
|
C++
|
.cpp
| 32
| 40.09375
| 83
| 0.693076
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,899
|
wdt_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/wdt/wdt_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::wdt {
namespace {
volatile uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceTimer.GetAddress();
#if defined(ATMOSPHERE_ARCH_ARM64)
NOINLINE void Reboot(uintptr_t registers) {
__asm__ __volatile__(
/* Get the current core. */
"mrs x12, mpidr_el1\n"
"and x12, x12, #0xFF\n"
/* Get the offsets of the registers we want to write */
"mov x10, #0x8\n"
"mov x11, #0x20\n"
"madd x10, x10, x12, %[registers]\n"
"madd x11, x11, x12, %[registers]\n"
"add x10, x10, #0x60\n"
"add x11, x11, #0x100\n"
/* Write the magic unlock pattern. */
"mov w9, #0xC45A\n"
"str w9, [x11, #0xC]\n"
/* Disable the counters. */
"mov w9, #0x2\n"
"str w9, [x11, #0x8]\n"
/* Start periodic timer. */
"mov w9, #0xC0000000\n"
"str w9, [x10]\n"
/* Set reboot source to the timer we started. */
"mov w9, #0x8015\n"
"add w9, w9, w12\n"
"str w9, [x11]\n"
/* Enable the counters. */
"mov w9, #0x1\n"
"str w9, [x11, #0x8]\n"
/* Wait forever. */
"1: b 1b"
: [registers]"=&r"(registers)
:
: "x9", "x10", "x11", "x12", "memory"
);
}
#elif defined(ATMOSPHERE_ARCH_ARM)
NOINLINE void Reboot(uintptr_t registers) {
/* Write the magic unlock pattern. */
reg::Write(registers + 0x18C, 0xC45A);
/* Disable the counters. */
reg::Write(registers + 0x188, 0x2);
/* Start periodic timer. */
reg::Write(registers + 0x080, 0xC0000000);
/* Set reboot source to the timer we started. */
reg::Write(registers + 0x180, 0x8019);
/* Enable the counters. */
reg::Write(registers + 0x188, 0x1);
/* Wait forever until the reboot takes. */
AMS_INFINITE_LOOP();
}
#endif
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
NOINLINE void Reboot() {
const uintptr_t registers = g_register_address;
Reboot(registers);
}
}
| 3,378
|
C++
|
.cpp
| 80
| 28.6625
| 101
| 0.496798
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,900
|
crypto_aes_impl_security_engine.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/crypto/crypto_aes_impl_security_engine.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::crypto::impl {
namespace {
constexpr bool IsSupportedKeySize(size_t size) {
return size == 16 || size == 24 || size == 32;
}
}
template<size_t KeySize>
AesImpl<KeySize>::~AesImpl() {
ClearMemory(this, sizeof(*this));
}
template<size_t KeySize>
void AesImpl<KeySize>::Initialize(const void *key, size_t key_size, bool is_encrypt) {
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(key_size == sizeof(int));
AMS_UNUSED(key_size, is_encrypt);
/* Set the security engine keyslot. */
m_slot = *static_cast<const int *>(key);
}
template<size_t KeySize>
void AesImpl<KeySize>::EncryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(src_size >= BlockSize);
AMS_ASSERT(dst_size >= BlockSize);
if constexpr (KeySize == 16) {
/* Aes 128. */
se::EncryptAes128(dst, dst_size, m_slot, src, src_size);
} else if constexpr (KeySize == 24) {
/* Aes 192. */
/* TODO: se::EncryptAes192(dst, dst_size, m_slot, src, src_size); */
AMS_UNUSED(dst, dst_size, src, src_size);
} else if constexpr (KeySize == 32) {
/* Aes 256. */
/* TODO: se::EncryptAes256(dst, dst_size, m_slot, src, src_size); */
AMS_UNUSED(dst, dst_size, src, src_size);
} else {
/* Invalid key size. */
static_assert(!std::is_same<AesImpl<KeySize>, AesImpl<KeySize>>::value);
}
}
template<size_t KeySize>
void AesImpl<KeySize>::DecryptBlock(void *dst, size_t dst_size, const void *src, size_t src_size) const {
static_assert(IsSupportedKeySize(KeySize));
AMS_ASSERT(src_size >= BlockSize);
AMS_ASSERT(dst_size >= BlockSize);
if constexpr (KeySize == 16) {
/* Aes 128. */
se::DecryptAes128(dst, dst_size, m_slot, src, src_size);
} else if constexpr (KeySize == 24) {
/* Aes 192. */
/* TODO: se::DecryptAes192(dst, dst_size, m_slot, src, src_size); */
AMS_UNUSED(dst, dst_size, src, src_size);
} else if constexpr (KeySize == 32) {
/* Aes 256. */
/* TODO: se::DecryptAes256(dst, dst_size, m_slot, src, src_size); */
AMS_UNUSED(dst, dst_size, src, src_size);
} else {
/* Invalid key size. */
static_assert(!std::is_same<AesImpl<KeySize>, AesImpl<KeySize>>::value);
}
}
/* Explicitly instantiate the three supported key sizes. */
template class AesImpl<16>;
template class AesImpl<24>;
template class AesImpl<32>;
}
| 3,451
|
C++
|
.cpp
| 81
| 34.888889
| 109
| 0.609058
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,901
|
uart_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/uart/uart_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "uart_registers.hpp"
namespace ams::uart {
namespace {
constexpr inline const u16 UartRegisterOffsets[Port_Count] = {
secmon::MemoryRegionPhysicalDeviceUartA.GetAddress() - secmon::MemoryRegionPhysicalDeviceUart.GetAddress(),
secmon::MemoryRegionPhysicalDeviceUartB.GetAddress() - secmon::MemoryRegionPhysicalDeviceUart.GetAddress(),
secmon::MemoryRegionPhysicalDeviceUartC.GetAddress() - secmon::MemoryRegionPhysicalDeviceUart.GetAddress(),
};
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceUart.GetAddress();
volatile UartRegisters *GetRegisters(Port port) {
return reinterpret_cast<volatile UartRegisters *>(g_register_address + UartRegisterOffsets[port]);
}
void WaitSymbols(int baud, u32 num) {
util::WaitMicroSeconds(util::DivideUp(num * 1'000'000, baud));
}
void WaitCycles(int baud, u32 num) {
util::WaitMicroSeconds(util::DivideUp(num * 1'000'000, 16 * baud));
}
ALWAYS_INLINE void WaitFifoNotFull(volatile UartRegisters *uart) {
while ((uart->lsr & UART_LSR_TX_FIFO_FULL) != 0) { /* ... */ }
}
ALWAYS_INLINE void WaitFifoNotEmpty(volatile UartRegisters *uart) {
while ((uart->lsr & UART_LSR_RX_FIFO_EMPTY) != 0) { /* ... */ }
}
void WaitIdle(volatile UartRegisters *uart, u32 vendor_state) {
if (vendor_state & UART_VENDOR_STATE_TX_IDLE) {
while ((uart->lsr & UART_LSR_TMTY) == 0) { /* ... */ }
}
if (vendor_state & UART_VENDOR_STATE_RX_IDLE) {
while ((uart->lsr & UART_LSR_RDR) != 0) { /* ... */ }
}
}
constexpr inline u32 LockBit = (1 << 6);
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
void Initialize(Port port, int baud_rate, u32 flags) {
/* Get the registers. */
auto *uart = GetRegisters(port);
/* Parse flags. */
const bool inverted = (flags & Flag_Inverted) != 0;
/* Calculate the baud rate divisor. */
constexpr u32 UartClock = 408000000;
const u32 divisor = (UartClock + (baud_rate * 16) / 2) / (baud_rate * 16);
/* Wait for idle state. */
WaitIdle(uart, UART_VENDOR_STATE_TX_IDLE);
/* Wait 100 us. */
util::WaitMicroSeconds(100);
/* Disable interrupts. */
uart->lcr = uart->lcr & ~UART_LCR_DLAB;
uart->ier = 0;
uart->mcr = 0;
/* Setup the uart in FIFO mode. */
uart->lcr = UART_LCR_DLAB | UART_LCR_WD_LENGTH_8;
uart->dll = static_cast<u8>(divisor);
uart->dlh = static_cast<u8>(divisor >> 8);
uart->lcr = uart->lcr & ~UART_LCR_DLAB;
reg::Read(std::addressof(uart->spr));
/* Wait three symbols. */
WaitSymbols(baud_rate, 3);
/* Enable FIFO with default settings. */
uart->fcr = UART_FCR_FCR_EN_FIFO;
uart->irda_csr = inverted ? UART_IRDA_CSR_INVERT_TXD : 0;
reg::Read(std::addressof(uart->spr));
/* Wait three cycles. */
WaitCycles(baud_rate, 3);
/* Flush the FIFO. */
WaitIdle(uart, UART_VENDOR_STATE_TX_IDLE);
uart->fcr = uart->fcr | UART_FCR_RX_CLR | UART_FCR_TX_CLR;
WaitCycles(baud_rate, 32);
/* Wait for idle state. */
WaitIdle(uart, UART_VENDOR_STATE_TX_IDLE | UART_VENDOR_STATE_RX_IDLE);
/* Wait 100 us. */
util::WaitMicroSeconds(100);
}
void SendText(Port port, const void *data, size_t size) {
/* Get the registers. */
auto *uart = GetRegisters(port);
/* Get pointer to data. */
const u8 *p = static_cast<const u8 *>(data);
/* Send each byte. */
for (size_t i = 0; i < size; ++i) {
WaitFifoNotFull(uart);
if (p[i] == '\n') {
*reinterpret_cast<volatile u8 *>(std::addressof(uart->thr)) = '\r';
WaitFifoNotFull(uart);
}
*reinterpret_cast<volatile u8 *>(std::addressof(uart->thr)) = p[i];
}
}
void WaitFlush(Port port) {
/* Get the registers. */
auto *uart = GetRegisters(port);
/* Wait for idle. */
WaitIdle(uart, UART_VENDOR_STATE_TX_IDLE);
}
}
| 5,061
|
C++
|
.cpp
| 114
| 35.807018
| 119
| 0.601384
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,902
|
libexo_cxx.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/libc/libexo_cxx.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#ifdef __cplusplus
extern "C" {
#endif
/* cxx implementation details to be stubbed here, as needed. */
void __cxa_pure_virtual() { AMS_ABORT("pure virtual function call"); }
#ifdef __cplusplus
} /* extern "C" */
#endif
| 882
|
C++
|
.cpp
| 24
| 35.041667
| 76
| 0.74386
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,903
|
pkg1_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/pkg1/pkg1_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::pkg1 {
namespace {
bool IsProductionImpl() {
return fuse::GetHardwareState() != fuse::HardwareState_Development;
}
}
bool IsProduction() {
return IsProductionImpl();
}
bool IsProductionForVersionCheck() {
return IsProductionImpl();
}
bool IsProductionForPublicKey() {
return IsProductionImpl();
}
}
| 1,066
|
C++
|
.cpp
| 32
| 29
| 79
| 0.709552
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,904
|
pinmux_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/pinmux/pinmux_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::pinmux {
namespace {
constinit uintptr_t g_pinmux_address = secmon::MemoryRegionPhysicalDeviceApbMisc.GetAddress();
constinit uintptr_t g_gpio_address = secmon::MemoryRegionPhysicalDeviceGpio.GetAddress();
void SetupFirstImpl(bool tx_cross_ext_con) {
if (tx_cross_ext_con) {
reg::Write(g_pinmux_address + PINMUX_AUX_UART2_TX, PINMUX_REG_BITS_ENUM(AUX_UART2_PM, UARTB),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(g_pinmux_address + PINMUX_AUX_UART3_TX, PINMUX_REG_BITS_ENUM(AUX_UART3_PM, UARTC),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
/* Configure GPIO for Uart-B/Uart-C. */
reg::ReadWrite(g_gpio_address + 0x108, REG_BITS_VALUE(0, 1, 1));
reg::ReadWrite(g_gpio_address + 0x00C, REG_BITS_VALUE(1, 1, 1));
reg::ReadWrite(g_gpio_address + 0x118, REG_BITS_VALUE(0, 1, 0));
reg::ReadWrite(g_gpio_address + 0x01C, REG_BITS_VALUE(1, 1, 0));
}
/* Configure PE6/PH6 */
reg::Write(g_pinmux_address + PINMUX_AUX_GPIO_PE6, PINMUX_REG_BITS_ENUM(AUX_GPIO_PE6_PM, RSVD0),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(g_pinmux_address + PINMUX_AUX_GPIO_PH6, PINMUX_REG_BITS_ENUM(AUX_GPIO_PH6_PM, RSVD0),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
/* Configure GPIO E6/H6. */
reg::ReadWrite(g_gpio_address + 0x100, REG_BITS_VALUE(6, 1, 1));
reg::ReadWrite(g_gpio_address + 0x10C, REG_BITS_VALUE(6, 1, 1));
reg::ReadWrite(g_gpio_address + 0x110, REG_BITS_VALUE(6, 1, 0));
reg::ReadWrite(g_gpio_address + 0x11C, REG_BITS_VALUE(6, 1, 0));
}
}
void SetRegisterAddress(uintptr_t pinmux_address, uintptr_t gpio_address) {
g_pinmux_address = pinmux_address;
g_gpio_address = gpio_address;
}
void SetupFirst(fuse::HardwareType hw_type) {
switch (hw_type) {
case fuse::HardwareType_Icosa:
case fuse::HardwareType_Iowa:
case fuse::HardwareType_Aula:
SetupFirstImpl(true);
break;
case fuse::HardwareType_Hoag:
case fuse::HardwareType_Calcio:
SetupFirstImpl(false);
break;
case fuse::HardwareType_Copper:
case fuse::HardwareType_Undefined:
break;
}
}
void SetupUartA() {
/* Get the registers. */
const uintptr_t PINMUX = g_pinmux_address;
/* Configure Uart-A. */
reg::Write(PINMUX + PINMUX_AUX_UART1_TX, PINMUX_REG_BITS_ENUM(AUX_UART1_PM, UARTA),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART1_RX, PINMUX_REG_BITS_ENUM(AUX_UART1_PM, UARTA),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_UP),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART1_RTS, PINMUX_REG_BITS_ENUM(AUX_UART1_PM, UARTA),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART1_CTS, PINMUX_REG_BITS_ENUM(AUX_UART1_PM, UARTA),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_DOWN),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
}
void SetupUartB() {
/* Get the registers. */
const uintptr_t PINMUX = g_pinmux_address;
/* Configure Uart-B. */
reg::Write(PINMUX + PINMUX_AUX_UART2_TX, PINMUX_REG_BITS_ENUM(AUX_UART2_PM, UARTB),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART2_RX, PINMUX_REG_BITS_ENUM(AUX_UART2_PM, UARTB),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART2_RTS, PINMUX_REG_BITS_ENUM(AUX_UART2_PM, UARTB),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART2_CTS, PINMUX_REG_BITS_ENUM(AUX_UART2_PM, UARTB),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
/* Configure GPIO for Uart-B. */
reg::ReadWrite(g_gpio_address + 0x108, REG_BITS_VALUE(0, 4, 0));
}
void SetupUartC() {
/* Get the registers. */
const uintptr_t PINMUX = g_pinmux_address;
/* Configure Uart-C. */
reg::Write(PINMUX + PINMUX_AUX_UART3_TX, PINMUX_REG_BITS_ENUM(AUX_UART3_PM, UARTC),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART3_RX, PINMUX_REG_BITS_ENUM(AUX_UART3_PM, UARTC),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, TRISTATE),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART3_RTS, PINMUX_REG_BITS_ENUM(AUX_UART3_PM, UARTC),
PINMUX_REG_BITS_ENUM(AUX_PUPD, PULL_DOWN),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_UART3_CTS, PINMUX_REG_BITS_ENUM(AUX_UART3_PM, UARTC),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, TRISTATE),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
/* Configure GPIO for Uart-C. */
reg::ReadWrite(g_gpio_address + 0x118, REG_BITS_VALUE(0, 1, 1));
reg::Read(g_gpio_address + 0x118);
reg::ReadWrite(g_gpio_address + 0x00C, REG_BITS_VALUE(1, 1, 0));
reg::Read(g_gpio_address + 0x00C);
}
void SetupI2c1() {
/* Get the registers. */
const uintptr_t PINMUX = g_pinmux_address;
/* Configure I2c1 */
reg::Write(PINMUX + PINMUX_AUX_GEN1_I2C_SCL, PINMUX_REG_BITS_ENUM(AUX_GEN1_I2C_PM, I2C1),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_GEN1_I2C_SDA, PINMUX_REG_BITS_ENUM(AUX_GEN1_I2C_PM, I2C1),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
}
void SetupI2c5() {
/* Get the registers. */
const uintptr_t PINMUX = g_pinmux_address;
/* Configure I2c5 */
reg::Write(PINMUX + PINMUX_AUX_PWR_I2C_SCL, PINMUX_REG_BITS_ENUM(AUX_PWR_I2C_PM, I2CPMU),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
reg::Write(PINMUX + PINMUX_AUX_PWR_I2C_SDA, PINMUX_REG_BITS_ENUM(AUX_PWR_I2C_PM, I2CPMU),
PINMUX_REG_BITS_ENUM(AUX_PUPD, NONE),
PINMUX_REG_BITS_ENUM(AUX_TRISTATE, PASSTHROUGH),
PINMUX_REG_BITS_ENUM(AUX_E_INPUT, ENABLE),
PINMUX_REG_BITS_ENUM(AUX_LOCK, DISABLE),
PINMUX_REG_BITS_ENUM(AUX_E_OD, DISABLE));
}
void SetupVolumeButton() {
/* Configure VOL_UP/VOL_DOWN */
reg::ReadWrite(g_gpio_address + 0x50C, REG_BITS_VALUE(6, 1, 1));
reg::ReadWrite(g_gpio_address + 0x50C, REG_BITS_VALUE(7, 1, 1));
reg::ReadWrite(g_gpio_address + 0x51C, REG_BITS_VALUE(6, 1, 0));
reg::ReadWrite(g_gpio_address + 0x51C, REG_BITS_VALUE(7, 1, 0));
}
void SetupHomeButton() {
/* Configure BUTTON_HOME */
reg::ReadWrite(g_gpio_address + 0x600, REG_BITS_VALUE(1, 1, 1));
reg::ReadWrite(g_gpio_address + 0x610, REG_BITS_VALUE(1, 1, 0));
}
}
| 16,601
|
C++
|
.cpp
| 221
| 45.524887
| 116
| 0.426605
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,905
|
gic_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/gic/gic_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::gic {
namespace {
struct GicDistributor {
u32 ctlr;
u32 typer;
u32 iidr;
u32 reserved_0x0c;
u32 statusr;
u32 reserved_0x14[3];
u32 impldef_0x20[8];
u32 setspi_nsr;
u32 reserved_0x44;
u32 clrspi_nsr;
u32 reserved_0x4c;
u32 setspi_sr;
u32 reserved_0x54;
u32 clrspi_sr;
u32 reserved_0x5c[9];
u32 igroupr[32];
u32 isenabler[32];
u32 icenabler[32];
u32 ispendr[32];
u32 icpendr[32];
u32 isactiver[32];
u32 icactiver[32];
union {
u8 bytes[1020];
u32 words[255];
} ipriorityr;
u32 _0x7fc;
union {
u8 bytes[1020];
u32 words[255];
} itargetsr;
u32 _0xbfc;
u32 icfgr[64];
u32 igrpmodr[32];
u32 _0xd80[32];
u32 nsacr[64];
u32 sgir;
u32 _0xf04[3];
u32 cpendsgir[4];
u32 spendsgir[4];
u32 reserved_0xf30[52];
static constexpr size_t SgirCpuTargetListShift = 16;
enum SgirTargetListFilter : u32 {
SgirTargetListFilter_CpuTargetList = (0 << 24),
SgirTargetListFilter_Others = (1 << 24),
SgirTargetListFilter_Self = (2 << 24),
SgirTargetListFilter_Reserved = (3 << 24),
};
};
static_assert(util::is_pod<GicDistributor>::value);
static_assert(sizeof(GicDistributor) == 0x1000);
static_assert(sizeof(GicDistributor) == secmon::MemoryRegionPhysicalDeviceGicDistributor.GetSize());
struct GicCpuInterface {
u32 ctlr;
u32 pmr;
u32 bpr;
u32 iar;
u32 eoir;
u32 rpr;
u32 hppir;
u32 abpr;
u32 aiar;
u32 aeoir;
u32 ahppir;
u32 statusr;
u32 reserved_30[4];
u32 impldef_40[36];
u32 apr[4];
u32 nsapr[4];
u32 reserved_f0[3];
u32 iidr;
u32 reserved_100[960];
u32 dir;
u32 _0x1004[1023];
};
static_assert(util::is_pod<GicCpuInterface>::value);
static_assert(sizeof(GicCpuInterface) == 0x2000);
static_assert(sizeof(GicCpuInterface) == secmon::MemoryRegionPhysicalDeviceGicCpuInterface.GetSize());
constexpr inline int InterruptWords = InterruptCount / BITSIZEOF(u32);
constexpr inline int SpiIndex = BITSIZEOF(u32);
constinit uintptr_t g_distributor_address = secmon::MemoryRegionPhysicalDeviceGicDistributor.GetAddress();
constinit uintptr_t g_cpu_interface_address = secmon::MemoryRegionPhysicalDeviceGicCpuInterface.GetAddress();
volatile GicDistributor *GetDistributor() {
return reinterpret_cast<volatile GicDistributor *>(g_distributor_address);
}
volatile GicCpuInterface *GetCpuInterface() {
return reinterpret_cast<volatile GicCpuInterface *>(g_cpu_interface_address);
}
void ReadWrite(uintptr_t address, int width, int i, u32 value) {
/* This code will never be invoked with a negative interrupt id. */
AMS_ASSUME(i >= 0);
const int scale = BITSIZEOF(u32) / width;
const int word = i / scale;
const int bit = (i % scale) * width;
const u32 mask = ((1u << width) - 1) << bit;
const uintptr_t reg_addr = address + sizeof(u32) * word;
const u32 old = reg::Read(reg_addr) & ~mask;
reg::Write(reg_addr, old | ((value << bit) & mask));
}
void Write(uintptr_t address, int width, int i, u32 value) {
/* This code will never be invoked with a negative interrupt id. */
AMS_ASSUME(i >= 0);
const int scale = BITSIZEOF(u32) / width;
const int word = i / scale;
const int bit = (i % scale) * width;
reg::Write(address + sizeof(u32) * word, value << bit);
}
}
void SetRegisterAddress(uintptr_t distributor_address, uintptr_t cpu_interface_address) {
g_distributor_address = distributor_address;
g_cpu_interface_address = cpu_interface_address;
}
void InitializeCommon() {
/* Get the gicd registers. */
auto *gicd = GetDistributor();
/* Set IGROUPR for to be FFs. */
for (int i = SpiIndex / BITSIZEOF(u32); i < InterruptWords; ++i) {
gicd->igroupr[i] = 0xFFFFFFFFu;
}
/* Set IPRIORITYR for spi interrupts to be 0x80. */
for (int i = SpiIndex; i < InterruptCount; ++i) {
gicd->ipriorityr.bytes[i] = 0x80;
}
/* Enable group 0. */
gicd->ctlr = 1;
}
void InitializeCoreUnique() {
/* Get the registers. */
auto *gicd = GetDistributor();
auto *gicc = GetCpuInterface();
/* Set IGROUPR0 to be FFs. */
gicd->igroupr[0] = 0xFFFFFFFFu;
/* Set IPRIORITYR for core local interrupts to be 0x80. */
for (int i = 0; i < SpiIndex; ++i) {
gicd->ipriorityr.bytes[i] = 0x80;
}
/* Enable group 0 as FIQs. */
gicc->ctlr = 0x1D9;
/* Set PMR. */
gicc->pmr = 0x80;
/* Set BPR. */
gicc->bpr = 7;
}
void SetPriority(int interrupt_id, int priority) {
ReadWrite(g_distributor_address + AMS_OFFSETOF(GicDistributor, ipriorityr), BITSIZEOF(u8), interrupt_id, priority);
}
void SetInterruptGroup(int interrupt_id, int group) {
ReadWrite(g_distributor_address + AMS_OFFSETOF(GicDistributor, igroupr), 1, interrupt_id, group);
}
void SetEnable(int interrupt_id, bool enable) {
Write(g_distributor_address + AMS_OFFSETOF(GicDistributor, isenabler), 1, interrupt_id, enable);
}
void SetSpiTargetCpu(int interrupt_id, u32 cpu_mask) {
ReadWrite(g_distributor_address + AMS_OFFSETOF(GicDistributor, itargetsr), BITSIZEOF(u8), interrupt_id, cpu_mask);
}
void SetSpiMode(int interrupt_id, InterruptMode mode) {
ReadWrite(g_distributor_address + AMS_OFFSETOF(GicDistributor, icfgr), 2, interrupt_id, static_cast<u32>(mode) << 1);
}
void SetPending(int interrupt_id) {
Write(g_distributor_address + AMS_OFFSETOF(GicDistributor, ispendr), 1, interrupt_id, 1);
}
int GetInterruptRequestId() {
return reg::Read(GetCpuInterface()->iar);
}
void SetEndOfInterrupt(int interrupt_id) {
reg::Write(GetCpuInterface()->eoir, interrupt_id);
}
}
| 7,553
|
C++
|
.cpp
| 187
| 30.320856
| 125
| 0.58256
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,906
|
clkrst_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/clkrst/clkrst_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::clkrst {
namespace {
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceClkRst.GetAddress();
constinit BpmpClockRate g_bpmp_clock_rate = BpmpClockRate_408MHz;
struct ClockParameters {
uintptr_t reset_offset;
uintptr_t clk_enb_offset;
uintptr_t clk_src_offset;
u8 index;
u8 clk_src;
u8 clk_div;
};
void EnableClock(const ClockParameters ¶m) {
/* Hold reset. */
reg::ReadWrite(g_register_address + param.reset_offset, REG_BITS_VALUE(param.index, 1, 1));
/* Disable clock. */
reg::ReadWrite(g_register_address + param.clk_enb_offset, REG_BITS_VALUE(param.index, 1, 0));
/* Set the clock source. */
if (param.clk_src_offset != 0) {
reg::Write(g_register_address + param.clk_src_offset, (param.clk_src << 29) | (param.clk_div << 0));
}
/* Enable clk. */
reg::ReadWrite(g_register_address + param.clk_enb_offset, REG_BITS_VALUE(param.index, 1, 1));
/* Release reset. */
reg::ReadWrite(g_register_address + param.reset_offset, REG_BITS_VALUE(param.index, 1, 0));
}
void DisableClock(const ClockParameters ¶m) {
/* Hold reset. */
reg::ReadWrite(g_register_address + param.reset_offset, REG_BITS_VALUE(param.index, 1, 1));
/* Disable clock. */
reg::ReadWrite(g_register_address + param.clk_enb_offset, REG_BITS_VALUE(param.index, 1, 0));
}
#define DEFINE_CLOCK_PARAMETERS(_VARNAME_, _REG_, _NAME_, _CLK_, _DIV_) \
constexpr inline const ClockParameters _VARNAME_ = { \
.reset_offset = CLK_RST_CONTROLLER_RST_DEVICES_##_REG_, \
.clk_enb_offset = CLK_RST_CONTROLLER_CLK_OUT_ENB_##_REG_, \
.clk_src_offset = CLK_RST_CONTROLLER_CLK_SOURCE_##_NAME_, \
.index = CLK_RST_CONTROLLER_CLK_ENB_##_NAME_##_INDEX, \
.clk_src = CLK_RST_CONTROLLER_CLK_SOURCE_##_NAME_##_##_NAME_##_CLK_SRC_##_CLK_, \
.clk_div = _DIV_, \
}
#define DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(_VARNAME_, _REG_, _NAME_) \
constexpr inline const ClockParameters _VARNAME_ = { \
.reset_offset = CLK_RST_CONTROLLER_RST_DEVICES_##_REG_, \
.clk_enb_offset = CLK_RST_CONTROLLER_CLK_OUT_ENB_##_REG_, \
.clk_src_offset = 0, \
.index = CLK_RST_CONTROLLER_CLK_ENB_##_NAME_##_INDEX, \
.clk_src = 0, \
.clk_div = 0, \
}
DEFINE_CLOCK_PARAMETERS(UartAClock, L, UARTA, PLLP_OUT0, 0);
DEFINE_CLOCK_PARAMETERS(UartBClock, L, UARTB, PLLP_OUT0, 0);
DEFINE_CLOCK_PARAMETERS(UartCClock, H, UARTC, PLLP_OUT0, 0);
DEFINE_CLOCK_PARAMETERS(I2c1Clock, L, I2C1, CLK_M, 0);
DEFINE_CLOCK_PARAMETERS(I2c5Clock, H, I2C5, CLK_M, 0);
DEFINE_CLOCK_PARAMETERS(SeClock, V, SE, PLLP_OUT0, 0);
DEFINE_CLOCK_PARAMETERS(ActmonClock, V, ACTMON, CLK_M, 0);
DEFINE_CLOCK_PARAMETERS(CsiteClock, U, CSITE, PLLP_OUT0, 4);
DEFINE_CLOCK_PARAMETERS(Host1xClock, L, HOST1X, PLLP_OUT0, 3);
DEFINE_CLOCK_PARAMETERS(TsecClock, U, TSEC, PLLP_OUT0, 2);
DEFINE_CLOCK_PARAMETERS(Sor1Clock, X, SOR1, PLLP_OUT0, 2);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(CldvfsClock, W, DVFS);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(TzramClock, V, TZRAM);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(SorSafeClock, Y, SOR_SAFE);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(Sor0Clock, X, SOR0);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(KfuseClock, H, KFUSE);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(Cache2Clock, L, CACHE2);
DEFINE_CLOCK_PARAMETERS_WITHOUT_CLKDIV(Cram2Clock, U, CRAM2);
constexpr const u32 PllcDivn[] = {
[BpmpClockRate_408MHz] = 0,
[BpmpClockRate_544MHz] = 85,
[BpmpClockRate_576MHz] = 90,
[BpmpClockRate_589MHz] = 92,
};
void EnablePllc(BpmpClockRate rate) {
const u32 desired_divn = PllcDivn[rate];
/* Check if we're already enabled. */
const bool is_enabled = reg::HasValue(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_ENABLE, ENABLE));
const bool is_good_divn = reg::HasValue(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_VALUE(PLLC_BASE_PLLC_DIVN, desired_divn));
if (is_enabled && is_good_divn) {
return;
}
/* Take PLLC out of reset. */
reg::Write(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC, (reg::Read(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC) & 0xBFF0000F) | (0x80000 << 4));
reg::SetBits(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC2, 0xF0 << 8);
/* Disable pll. */
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_ENABLE, DISABLE));
reg::ClearBits(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC1, (1u << 27));
util::WaitMicroSeconds(10);
/* Set dividers. */
reg::Write(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_VALUE(PLLC_BASE_PLLC_DIVM, 4),
CLK_RST_REG_BITS_VALUE(PLLC_BASE_PLLC_DIVN, desired_divn));
/* Enable pll. */
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_ENABLE, ENABLE));
while (!reg::HasValue(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_LOCK, LOCK))) {
/* ... */
}
/* Disable PLLC_OUT1. */
reg::Write(g_register_address + CLK_RST_CONTROLLER_PLLC_OUT, CLK_RST_REG_BITS_VALUE(PLLC_OUT_PLLC_OUT1_RATIO, 1));
/* Enable PLLC_OUT1. */
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_OUT, CLK_RST_REG_BITS_ENUM(PLLC_OUT_PLLC_OUT1_RSTN, RESET_DISABLE),
CLK_RST_REG_BITS_ENUM(PLLC_OUT_PLLC_OUT1_CLKEN, ENABLE));
util::WaitMicroSeconds(1'000);
}
void DisablePllc() {
/* Disable PLLC/PLLC_OUT1. */
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_OUT, CLK_RST_REG_BITS_ENUM(PLLC_OUT_PLLC_OUT1_RSTN, RESET_ENABLE),
CLK_RST_REG_BITS_ENUM(PLLC_OUT_PLLC_OUT1_CLKEN, DISABLE));
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_ENABLE, DISABLE));
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_PLLC_BASE, CLK_RST_REG_BITS_ENUM(PLLC_BASE_PLLC_REF_DIS, REF_DISABLE));
reg::SetBits(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC1, (1u << 27));
reg::SetBits(g_register_address + CLK_RST_CONTROLLER_PLLC_MISC, (1u << 30));
util::WaitMicroSeconds(10);
}
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
void SetFuseVisibility(bool visible) {
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_MISC_CLK_ENB, CLK_RST_REG_BITS_VALUE(MISC_CLK_ENB_CFG_ALL_VISIBLE, visible ? 1 : 0));
}
void EnableUartAClock() {
EnableClock(UartAClock);
}
void EnableUartBClock() {
EnableClock(UartBClock);
}
void EnableUartCClock() {
EnableClock(UartCClock);
}
void EnableActmonClock() {
EnableClock(ActmonClock);
}
void EnableI2c1Clock() {
EnableClock(I2c1Clock);
}
void EnableI2c5Clock() {
EnableClock(I2c5Clock);
}
void EnableSeClock() {
EnableClock(SeClock);
if (fuse::GetSocType() == fuse::SocType_Mariko) {
reg::ReadWrite(g_register_address + CLK_RST_CONTROLLER_CLK_SOURCE_SE, CLK_RST_REG_BITS_ENUM(CLK_SOURCE_SE_CLK_LOCK, ENABLE));
}
}
void EnableCldvfsClock() {
EnableClock(CldvfsClock);
}
void EnableCsiteClock() {
EnableClock(CsiteClock);
}
void EnableTzramClock() {
EnableClock(TzramClock);
}
void EnableCache2Clock() {
EnableClock(Cache2Clock);
}
void EnableCram2Clock() {
EnableClock(Cram2Clock);
}
void EnableHost1xClock() {
EnableClock(Host1xClock);
}
void EnableTsecClock() {
EnableClock(TsecClock);
}
void EnableSorSafeClock() {
EnableClock(SorSafeClock);
}
void EnableSor0Clock() {
EnableClock(Sor0Clock);
}
void EnableSor1Clock() {
EnableClock(Sor1Clock);
}
void EnableKfuseClock() {
EnableClock(KfuseClock);
}
void DisableI2c1Clock() {
DisableClock(I2c1Clock);
}
void DisableHost1xClock() {
DisableClock(Host1xClock);
}
void DisableTsecClock() {
DisableClock(TsecClock);
}
void DisableSorSafeClock() {
DisableClock(SorSafeClock);
}
void DisableSor0Clock() {
DisableClock(Sor0Clock);
}
void DisableSor1Clock() {
DisableClock(Sor1Clock);
}
void DisableKfuseClock() {
DisableClock(KfuseClock);
}
BpmpClockRate GetBpmpClockRate() {
return g_bpmp_clock_rate;
}
BpmpClockRate SetBpmpClockRate(BpmpClockRate rate) {
/* Get the current rate. */
const auto prev_rate = g_bpmp_clock_rate;
/* Cap our rate. */
if (rate >= BpmpClockRate_Count) {
rate = BpmpClockRate_589MHz;
}
/* Change the rate, if we need to. */
if (rate == prev_rate) {
return prev_rate;
}
/* Configure the rate. */
if (rate != BpmpClockRate_408MHz) {
/* If we were previously overclocked, restore to PLLP_OUT. */
if (prev_rate != BpmpClockRate_408MHz) {
reg::Write(g_register_address + CLK_RST_CONTROLLER_SCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SYS_STATE, RUN),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_FIQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IRQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_RUN_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IDLE_SOURCE, PLLP_OUT0));
util::WaitMicroSeconds(1'000);
}
/* Configure PLLC. */
EnablePllc(rate);
/* Set SCLK. */
reg::Write(g_register_address + CLK_RST_CONTROLLER_CLK_SYSTEM_RATE, CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_HCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_AHB_RATE, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_PCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_APB_RATE, 3));
reg::Write(g_register_address + CLK_RST_CONTROLLER_SCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SYS_STATE, RUN),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_FIQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IRQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_RUN_SOURCE, PLLC_OUT1),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IDLE_SOURCE, CLKM));
} else {
/* Configure to use PLLP_OUT0. */
reg::Write(g_register_address + CLK_RST_CONTROLLER_SCLK_BURST_POLICY, CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SYS_STATE, RUN),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_FIQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_COP_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_CPU_AUTO_SWAKEUP_FROM_IRQ, NOP),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_FIQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IRQ_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_RUN_SOURCE, PLLP_OUT0),
CLK_RST_REG_BITS_ENUM(SCLK_BURST_POLICY_SWAKEUP_IDLE_SOURCE, CLKM));
util::WaitMicroSeconds(1'000);
reg::Write(g_register_address + CLK_RST_CONTROLLER_CLK_SYSTEM_RATE, CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_HCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_AHB_RATE, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_PCLK_DIS, 0),
CLK_RST_REG_BITS_VALUE(CLK_SYSTEM_RATE_APB_RATE, 2));
/* Disable PLLC. */
DisablePllc();
}
/* Set the clock rate. */
g_bpmp_clock_rate = rate;
/* Return the previous rate. */
return prev_rate;
}
}
| 17,567
|
C++
|
.cpp
| 285
| 43.550877
| 168
| 0.50523
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,907
|
rtc_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/rtc/rtc_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "max77620-rtc.h"
namespace ams::rtc {
namespace {
constexpr inline int I2cAddressMax77620Rtc = 0x68;
/* TODO: Find datasheet, link to it instead. */
/* NOTE: Tentatively, Max77620 "mostly" matches https://datasheets.maximintegrated.com/en/ds/MAX77863.pdf. */
constexpr inline int Max77620RtcRegisterUpdate0 = 0x04;
constexpr inline int Max77620RtcRegisterAlarmStart = 0x0E;
constexpr inline int Max77620RtcRegisterAlarm1Sec = 0x0E;
constexpr inline int Max77620RtcRegisterAlarm1Min = 0x0F;
constexpr inline int Max77620RtcRegisterAlarm1Hour = 0x10;
constexpr inline int Max77620RtcRegisterAlarm1Weekday = 0x11;
constexpr inline int Max77620RtcRegisterAlarm1Month = 0x12;
constexpr inline int Max77620RtcRegisterAlarm1Year = 0x13;
constexpr inline int Max77620RtcRegisterAlarm1Date = 0x14;
constexpr inline int Max77620RtcRegisterAlarm2Sec = 0x15;
constexpr inline int Max77620RtcRegisterAlarm2Min = 0x16;
constexpr inline int Max77620RtcRegisterAlarm2Hour = 0x17;
constexpr inline int Max77620RtcRegisterAlarm2Weekday = 0x18;
constexpr inline int Max77620RtcRegisterAlarm2Month = 0x19;
constexpr inline int Max77620RtcRegisterAlarm2Year = 0x1A;
constexpr inline int Max77620RtcRegisterAlarm2Date = 0x1B;
constexpr inline int Max77620RtcRegisterAlarmLast = 0x1B;
}
void StopAlarm() {
/* Begin update. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Rtc, Max77620RtcRegisterUpdate0, MAX77620_RTC_READ_UPDATE);
/* Clear ALARM_EN for all alarm registers. */
for (auto reg = Max77620RtcRegisterAlarmStart; reg <= Max77620RtcRegisterAlarmLast; ++reg) {
u8 val = i2c::QueryByte(i2c::Port_5, I2cAddressMax77620Rtc, reg);
val &= ~MAX77620_RTC_ALARM_EN_MASK;
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Rtc, reg, val);
}
/* End update. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Rtc, Max77620RtcRegisterUpdate0, MAX77620_RTC_WRITE_UPDATE);
}
}
| 2,830
|
C++
|
.cpp
| 53
| 46.849057
| 117
| 0.719711
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,908
|
pmic_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/pmic/pmic_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "max77620.h"
#include "max7762x.h"
namespace ams::pmic {
namespace {
constexpr inline int I2cAddressEristaMax77621 = 0x1B;
constexpr inline int I2cAddressMarikoMax77812_A = 0x31;
constexpr inline int I2cAddressMarikoMax77812_B = 0x33;
constexpr inline int I2cAddressMax77620Pmic = 0x3C;
/* https://github.com/Atmosphere-NX/Atmosphere/blob/master/emummc/source/power/max77620.h */
/* https://github.com/Atmosphere-NX/Atmosphere/blob/master/emummc/source/power/max7762x.h */
/* TODO: Find datasheet, link to it instead. */
/* NOTE: Tentatively, Max77620 "mostly" matches https://datasheets.maximintegrated.com/en/ds/MAX77863.pdf. */
/* This does not contain Max77621 documentation, though. */
constexpr inline int Max77620RegisterCnfgBbc = 0x04;
constexpr inline int Max77620RegisterOnOffStat = 0x15;
constexpr inline int Max77620RegisterSd0 = 0x16;
constexpr inline int Max77620RegisterSd1 = 0x17;
constexpr inline int Max77620RegisterCnfg2Sd = 0x22;
constexpr inline int Max77620RegisterCnfg1Ldo8 = 0x33;
constexpr inline int Max77620RegisterGpio0 = 0x36;
constexpr inline int Max77620RegisterAmeGpio = 0x40;
constexpr inline int Max77620RegisterOnOffCnfg1 = 0x41;
constexpr inline int Max77620RegisterCnfgFps0 = 0x43;
constexpr inline int Max77620RegisterCnfgFps1 = 0x44;
constexpr inline int Max77620RegisterCnfgFps2 = 0x45;
constexpr inline int Max77620RegisterFpsLdo4 = 0x4A;
constexpr inline int Max77620RegisterFpsLdo8 = 0x4E;
constexpr inline int Max77620RegisterFpsSd0 = 0x4F;
constexpr inline int Max77620RegisterFpsSd1 = 0x50;
constexpr inline int Max77620RegisterFpsSd3 = 0x52;
constexpr inline int Max77620RegisterFpsGpio3 = 0x56;
constexpr inline int Max77621RegisterVOut = 0x00;
constexpr inline int Max77621RegisterVOutDvc = 0x01;
constexpr inline int Max77621RegisterControl1 = 0x02;
constexpr inline int Max77621RegisterControl2 = 0x03;
/* https://datasheets.maximintegrated.com/en/ds/MAX77812.pdf */
constexpr inline int Max77812RegisterEnCtrl = 0x06;
constexpr inline int Max77812RegisterM4VOut = 0x26;
void Max77620EnableGpio(int gpio) {
u8 val;
/* Clear the AE for the GPIO */
if (i2c::Query(std::addressof(val), sizeof(val), i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterAmeGpio)) {
val &= ~(1 << gpio);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterAmeGpio, val);
}
/* Set GPIO_DRV_PUSHPULL (bit 0), GPIO_OUTPUT_VAL_HIGH (bit 3). */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterGpio0 + gpio, MAX77620_CNFG_GPIO_DRV_PUSHPULL | MAX77620_CNFG_GPIO_OUTPUT_VAL_HIGH);
}
void SetEnBitErista() {
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterVOut, MAX77621_VOUT_ENABLE);
}
void EnableVddCpuErista() {
/* Enable GPIO 5. */
/* TODO: What does this control? */
Max77620EnableGpio(5);
/* Configure Max77621 control registers. */
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterControl1, MAX77621_AD_ENABLE | MAX77621_NFSR_ENABLE | MAX77621_SNS_ENABLE | MAX77621_RAMP_12mV_PER_US);
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterControl2, MAX77621_T_JUNCTION_120 | MAX77621_WDTMR_ENABLE | MAX77621_CKKADV_TRIP_75mV_PER_US| MAX77621_INDUCTOR_NOMINAL);
/* Configure Max77621 VOut to 0.95v */
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterVOut, MAX77621_VOUT_ENABLE | MAX77621_VOUT_0_95V);
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterVOutDvc, MAX77621_VOUT_ENABLE | MAX77621_VOUT_0_95V);
}
void DisableVddCpuErista() {
/* Disable Max77621 VOut. */
i2c::SendByte(i2c::Port_5, I2cAddressEristaMax77621, Max77621RegisterVOut, MAX77621_VOUT_DISABLE);
}
int GetI2cAddressForMarikoMax77812(Regulator regulator) {
switch (regulator) {
case Regulator_Mariko_Max77812_A: return I2cAddressMarikoMax77812_A;
case Regulator_Mariko_Max77812_B: return I2cAddressMarikoMax77812_B;
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void SetEnBitMariko(Regulator regulator) {
/* Set EN_M3_LPM to enable BUCK Master 3 low power mode. */
i2c::SendByte(i2c::Port_5, GetI2cAddressForMarikoMax77812(regulator), Max77812RegisterEnCtrl, 0x40);
}
void EnableVddCpuMariko(Regulator regulator) {
const int address = GetI2cAddressForMarikoMax77812(regulator);
/* Set EN_M3_LPM to enable BUCK Master 3 low power mode. */
u8 ctrl;
if (i2c::Query(std::addressof(ctrl), sizeof(ctrl), i2c::Port_5, address, Max77812RegisterEnCtrl)) {
ctrl |= 0x40;
i2c::SendByte(i2c::Port_5, address, Max77812RegisterEnCtrl, ctrl);
}
/* Set BUCK Master 4 output voltage to 110. */
i2c::SendByte(i2c::Port_5, address, Max77812RegisterM4VOut, 110);
}
void DisableVddCpuMariko(Regulator regulator) {
const int address = GetI2cAddressForMarikoMax77812(regulator);
/* Clear EN_M3_LPM to disable BUCK Master 3 low power mode. */
u8 ctrl;
if (i2c::Query(std::addressof(ctrl), sizeof(ctrl), i2c::Port_5, address, Max77812RegisterEnCtrl)) {
ctrl &= ~0x40;
i2c::SendByte(i2c::Port_5, address, Max77812RegisterEnCtrl, ctrl);
}
}
u8 GetPmicOnOffStat() {
return i2c::QueryByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterOnOffStat);
}
void ShutdownSystemImpl(bool reboot) {
/* Get value, set or clear software reset mask. */
u8 on_off_2_val = i2c::QueryByte(i2c::Port_5, I2cAddressMax77620Pmic, MAX77620_REG_ONOFFCNFG2);
if (reboot) {
on_off_2_val |= MAX77620_ONOFFCNFG2_SFT_RST_WK;
} else {
on_off_2_val &= ~(MAX77620_ONOFFCNFG2_SFT_RST_WK);
}
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, MAX77620_REG_ONOFFCNFG2, on_off_2_val);
/* Get value, set software reset mask. */
u8 on_off_1_val = i2c::QueryByte(i2c::Port_5, I2cAddressMax77620Pmic, MAX77620_REG_ONOFFCNFG1);
on_off_1_val |= MAX77620_ONOFFCNFG1_SFT_RST;
/* NOTE: Here, userland finalizes the battery on non-Calcio. */
if (fuse::GetHardwareType() != fuse::HardwareType_Calcio) {
/* ... */
}
/* Actually write the value to trigger shutdown/reset. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, MAX77620_REG_ONOFFCNFG1, on_off_1_val);
}
void SetBackupBatteryConfig() {
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfgBbc, 0x40);
}
void SetForcePowerOffTimeConfig() {
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterOnOffCnfg1, 0x58);
}
void SetFlexiblePowerSequencer() {
/* Configure FPS registers. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfgFps0, 0x38);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfgFps1, 0x3A);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfgFps2, 0x38);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsLdo4, 0x0F);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsLdo8, 0xC7);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsSd0, 0x4F);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsSd1, 0x29);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsSd3, 0x1B);
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterFpsGpio3, 0x22);
}
void SetVoltage(int reg, int mv) {
const u8 v = ((mv - 600) * 1000) / 12500;
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, reg, v);
}
}
void SetEnBit(Regulator regulator) {
switch (regulator) {
case Regulator_Erista_Max77621:
return SetEnBitErista();
case Regulator_Mariko_Max77812_A:
case Regulator_Mariko_Max77812_B:
return SetEnBitMariko(regulator);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void EnableVddCpu(Regulator regulator) {
switch (regulator) {
case Regulator_Erista_Max77621:
return EnableVddCpuErista();
case Regulator_Mariko_Max77812_A:
case Regulator_Mariko_Max77812_B:
return EnableVddCpuMariko(regulator);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void DisableVddCpu(Regulator regulator) {
switch (regulator) {
case Regulator_Erista_Max77621:
return DisableVddCpuErista();
case Regulator_Mariko_Max77812_A:
case Regulator_Mariko_Max77812_B:
return DisableVddCpuMariko(regulator);
AMS_UNREACHABLE_DEFAULT_CASE();
}
}
void EnableSleep() {
/* Get the current onoff cfg. */
u8 cnfg = i2c::QueryByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterOnOffCnfg1);
/* Set SlpEn. */
cnfg |= MAX77620_ONOFFCNFG1_SLPEN;
/* Write the new cfg. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterOnOffCnfg1, cnfg);
}
void ShutdownSystem(bool reboot) {
ShutdownSystemImpl(reboot);
/* Allow up to 5 seconds for shutdown/reboot to take place. */
util::WaitMicroSeconds(5'000'000ul);
AMS_ABORT("Shutdown failed");
}
void PowerOff() {
ShutdownSystemImpl(false);
}
bool IsAcOk() {
return (GetPmicOnOffStat() & (1 << 1)) != 0;
}
bool IsPowerButtonPressed() {
return (GetPmicOnOffStat() & (1 << 2)) != 0;
}
void SetSystemSetting(fuse::SocType soc_type) {
SetBackupBatteryConfig();
SetForcePowerOffTimeConfig();
if (soc_type == fuse::SocType_Erista) {
SetFlexiblePowerSequencer();
}
}
void EnableVddCore(fuse::SocType soc_type) {
if (soc_type == fuse::SocType_Erista) {
SetVoltage(Max77620RegisterSd0, 1125);
} else /* if (soc_type == fuse::SocType_Mariko) */ {
SetVoltage(Max77620RegisterSd0, 1050);
}
}
void EnableLdo8() {
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfg1Ldo8, 0xE8);
}
void EnableVddMemory(fuse::SocType soc_type) {
/* Disable remote sense for Sd1. */
i2c::SendByte(i2c::Port_5, I2cAddressMax77620Pmic, Max77620RegisterCnfg2Sd, 0x05);
/* On Erista, set Sd1 voltage. */
if (soc_type == fuse::SocType_Erista) {
SetVoltage(Max77620RegisterSd1, 1100);
}
}
}
| 12,266
|
C++
|
.cpp
| 237
| 41.64135
| 202
| 0.649937
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,909
|
se_hash.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_hash.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
void SetMessageSize(volatile SecurityEngineRegisters *SE, size_t src_size) {
/* Set the message size. */
reg::Write(SE->SE_SHA_MSG_LENGTH[0], src_size * BITSIZEOF(u8));
reg::Write(SE->SE_SHA_MSG_LENGTH[1], 0);
reg::Write(SE->SE_SHA_MSG_LENGTH[2], 0);
reg::Write(SE->SE_SHA_MSG_LENGTH[3], 0);
/* Set the message remaining size. */
reg::Write(SE->SE_SHA_MSG_LEFT[0], src_size * BITSIZEOF(u8));
reg::Write(SE->SE_SHA_MSG_LEFT[1], 0);
reg::Write(SE->SE_SHA_MSG_LEFT[2], 0);
reg::Write(SE->SE_SHA_MSG_LEFT[3], 0);
}
void GetHashResult(volatile SecurityEngineRegisters *SE, void *dst, size_t dst_size) {
/* Copy out the words. */
const int num_words = dst_size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
const u32 word = reg::Read(SE->SE_HASH_RESULT[i]);
util::StoreBigEndian(static_cast<u32 *>(dst) + i, word);
}
}
}
void CalculateSha256(Sha256Hash *dst, const void *src, size_t src_size) {
/* Get the engine. */
auto *SE = GetRegisters();
/* Configure the engine to perform SHA256 "encryption". */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_MODE, SHA256),
SE_REG_BITS_ENUM(CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_ENC_ALG, SHA),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DST, HASH_REG));
/* Begin a hardware hash operation. */
reg::Write(SE->SE_SHA_CONFIG, SE_REG_BITS_VALUE(SHA_CONFIG_HW_INIT_HASH, 1));
/* Set the message size. */
SetMessageSize(SE, src_size);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, src, src_size);
/* Get the result. */
GetHashResult(SE, dst, sizeof(*dst));
}
}
| 2,837
|
C++
|
.cpp
| 59
| 38.491525
| 94
| 0.583725
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,910
|
se_oaep.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_oaep.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
/* NOTE: This implementation is mostly copy/pasted from crypto::impl::RsaOaepImpl. */
namespace {
constexpr inline size_t HashSize = sizeof(Sha256Hash);
constexpr inline u8 HeadMagic = 0x00;
void ApplyMGF1(u8 *dst, size_t dst_size, const void *src, size_t src_size) {
/* Check our pre-conditions. */
AMS_ABORT_UNLESS(src_size <= RsaSize - (1 + HashSize));
/* Create a buffer. */
util::AlignedBuffer<hw::DataCacheLineSize, RsaSize - (1 + HashSize) + sizeof(u32)> buf;
u32 counter = 0;
while (dst_size > 0) {
/* Setup the current hash buffer. */
const size_t cur_size = std::min(HashSize, dst_size);
std::memcpy(static_cast<u8 *>(buf), src, src_size);
{
u32 counter_be;
util::StoreBigEndian(std::addressof(counter_be), counter++);
std::memcpy(static_cast<u8 *>(buf) + src_size, std::addressof(counter_be), sizeof(counter_be));
}
/* Ensure se sees correct data. */
hw::FlushDataCache(buf, src_size + sizeof(u32));
hw::DataSynchronizationBarrierInnerShareable();
/* Calculate the hash. */
Sha256Hash hash;
se::CalculateSha256(std::addressof(hash), buf, src_size + sizeof(u32));
/* Mask the current output. */
const u8 *mask = hash.bytes;
for (size_t i = 0; i < cur_size; ++i) {
*(dst++) ^= *(mask++);
}
/* Advance. */
dst_size -= cur_size;
}
}
}
size_t DecodeRsaOaepSha256(void *dst, size_t dst_size, void *src, size_t src_size, const void *label_digest, size_t label_digest_size) {
/* Check our preconditions. */
AMS_ABORT_UNLESS(src_size == RsaSize);
AMS_ABORT_UNLESS(label_digest_size == HashSize);
/* Get a byte-readable copy of the input. */
u8 *buf = static_cast<u8 *>(src);
/* Validate sanity byte. */
bool is_valid = buf[0] == HeadMagic;
/* Decrypt seed and masked db. */
size_t db_len = src_size - HashSize - 1;
u8 *seed = buf + 1;
u8 *db = seed + HashSize;
ApplyMGF1(seed, HashSize, db, db_len);
ApplyMGF1(db, db_len, seed, HashSize);
/* Check the label digest. */
is_valid &= crypto::IsSameBytes(label_digest, db, HashSize);
/* Skip past the label digest. */
db += HashSize;
db_len -= HashSize;
/* Verify that DB is of the form 0000...0001 < message > */
s32 msg_ofs = 0;
{
int looking_for_one = 1;
int invalid_db_padding = 0;
int is_zero;
int is_one;
for (size_t i = 0; i < db_len; /* ... */) {
is_zero = (db[i] == 0);
is_one = (db[i] == 1);
msg_ofs += (looking_for_one & is_one) * (static_cast<s32>(++i));
looking_for_one &= ~is_one;
invalid_db_padding |= (looking_for_one & ~is_zero);
}
is_valid &= (invalid_db_padding == 0);
}
/* If we're invalid, return zero size. */
const size_t valid_msg_size = db_len - msg_ofs;
const size_t msg_size = std::min(dst_size, static_cast<size_t>(is_valid) * valid_msg_size);
/* Copy to output. */
std::memcpy(dst, db + msg_ofs, msg_size);
/* Return copied size. */
return msg_size;
}
}
| 4,359
|
C++
|
.cpp
| 97
| 34.42268
| 140
| 0.551333
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,911
|
se_management.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_management.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceSecurityEngine.GetAddress();
constinit uintptr_t g_register2_address = secmon::MemoryRegionPhysicalDeviceSecurityEngine2.GetAddress();
constinit DoneHandler g_done_handler = nullptr;
void SetSecure(volatile SecurityEngineRegisters *SE, bool secure) {
/* Set the security software setting. */
if (secure) {
reg::ReadWrite(SE->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_SOFT_SETTING, SECURE));
} else {
reg::ReadWrite(SE->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_SOFT_SETTING, NONSECURE));
}
/* Read the status register to force an update. */
reg::Read(SE->SE_SE_SECURITY);
}
}
volatile SecurityEngineRegisters *GetRegisters() {
return reinterpret_cast<volatile SecurityEngineRegisters *>(g_register_address);
}
volatile SecurityEngineRegisters *GetRegisters2() {
return reinterpret_cast<volatile SecurityEngineRegisters *>(g_register2_address);
}
void SetRegisterAddress(uintptr_t address, uintptr_t address2) {
g_register_address = address;
g_register2_address = address2;
}
void Initialize() {
auto *SE = GetRegisters();
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_STATUS, SE_REG_BITS_ENUM(STATUS_STATE, IDLE)));
}
void SetSecure(bool secure) {
/* Set security for SE1. */
SetSecure(GetRegisters(), secure);
/* If SE2 is present, set security for SE2. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
SetSecure(GetRegisters2(), secure);
}
}
void SetTzramSecure() {
auto *SE = GetRegisters();
/* Set the TZRAM setting to secure. */
SE->SE_TZRAM_SECURITY = SE_TZRAM_SETTING_SECURE;
}
void SetPerKeySecure() {
auto *SE = GetRegisters();
/* Update PERKEY_SETTING to secure. */
reg::ReadWrite(SE->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_PERKEY_SETTING, SECURE));
}
void SetContextSaveSecure() {
/* Context save lock to trustzone secure is only available on mariko. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
auto *SE = GetRegisters();
auto *SE2 = GetRegisters2();
reg::ReadWrite(SE->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_CTX_SAVE_TZ_LOCK, SECURE));
reg::ReadWrite(SE2->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_CTX_SAVE_TZ_LOCK, SECURE));
}
}
void Lockout() {
auto *SE = GetRegisters();
/* Lock access to the AES keyslots. */
for (int i = 0; i < AesKeySlotCount; ++i) {
SE->SE_CRYPTO_KEYTABLE_ACCESS[i] = 0;
}
/* Lock access to the RSA keyslots. */
for (int i = 0; i < RsaKeySlotCount; ++i) {
SE->SE_RSA_KEYTABLE_ACCESS[i] = 0;
}
/* Set Per Key secure. */
SetPerKeySecure();
/* Configure SE_SECURITY. */
{
reg::ReadWrite(SE->SE_SE_SECURITY, SE_REG_BITS_ENUM(SECURITY_HARD_SETTING, SECURE),
SE_REG_BITS_ENUM(SECURITY_ENG_DIS, DISABLE),
SE_REG_BITS_ENUM(SECURITY_PERKEY_SETTING, SECURE),
SE_REG_BITS_ENUM(SECURITY_SOFT_SETTING, SECURE));
}
}
void HandleInterrupt() {
/* Get the registers. */
auto *SE = GetRegisters();
/* Disable the SE interrupt. */
reg::Write(SE->SE_INT_ENABLE, 0);
/* Execute the handler if we have one. */
if (const auto handler = g_done_handler; handler != nullptr) {
g_done_handler = nullptr;
handler();
}
}
void SetDoneHandler(volatile SecurityEngineRegisters *SE, DoneHandler handler) {
/* Set the done handler. */
g_done_handler = handler;
/* Configure to trigger an interrupt when done. */
reg::Write(SE->SE_INT_ENABLE, SE_REG_BITS_ENUM(INT_ENABLE_SE_OP_DONE, ENABLE));
}
}
| 4,895
|
C++
|
.cpp
| 112
| 34.767857
| 113
| 0.61477
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,912
|
se_rng.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_rng.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
constexpr inline int RngReseedInterval = 70001;
void ConfigRng(volatile SecurityEngineRegisters *SE, SE_CONFIG_DST dst, SE_RNG_CONFIG_MODE mode) {
/* Configure the engine to do RNG encryption. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM (CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM (CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM (CONFIG_ENC_ALG, RNG),
SE_REG_BITS_ENUM (CONFIG_DEC_ALG, NOP),
SE_REG_BITS_VALUE(CONFIG_DST, dst));
reg::Write(SE->SE_CRYPTO_CONFIG, SE_REG_BITS_ENUM (CRYPTO_CONFIG_MEMIF, AHB),
SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_CORE_SEL, ENCRYPT),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, RANDOM),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, BYPASS),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
/* Configure the RNG to use Entropy as source. */
reg::Write(SE->SE_RNG_CONFIG, SE_REG_BITS_ENUM(RNG_CONFIG_SRC, ENTROPY), SE_REG_BITS_VALUE(RNG_CONFIG_MODE, mode));
}
void InitializeRandom(volatile SecurityEngineRegisters *SE) {
/* Lock the entropy source. */
reg::Write(SE->SE_RNG_SRC_CONFIG, SE_REG_BITS_ENUM(RNG_SRC_CONFIG_RO_ENTROPY_SOURCE, ENABLE),
SE_REG_BITS_ENUM(RNG_SRC_CONFIG_RO_ENTROPY_SOURCE_LOCK, ENABLE));
/* Set the reseed interval to force a reseed every 70000 blocks. */
SE->SE_RNG_RESEED_INTERVAL = RngReseedInterval;
/* Initialize the DRBG. */
{
u8 dummy_buf[AesBlockSize];
/* Configure the engine to force drbg instantiation by writing random to memory. */
ConfigRng(SE, SE_CONFIG_DST_MEMORY, SE_RNG_CONFIG_MODE_FORCE_INSTANTIATION);
/* Configure to do a single RNG block operation to trigger DRBG init. */
SE->SE_CRYPTO_LAST_BLOCK = 0;
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dummy_buf, sizeof(dummy_buf), nullptr, 0);
}
}
void GenerateSrk(volatile SecurityEngineRegisters *SE) {
/* Configure the RNG to output to SRK and force a reseed. */
ConfigRng(SE, SE_CONFIG_DST_SRK, SE_RNG_CONFIG_MODE_FORCE_RESEED);
/* Configure a single block operation. */
SE->SE_CRYPTO_LAST_BLOCK = 0;
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, nullptr, 0);
}
}
void InitializeRandom() {
/* Initialize random for SE1. */
InitializeRandom(GetRegisters());
/* If we have SE2, initialize random for SE2. */
/* NOTE: Nintendo's implementation of this is incorrect. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
InitializeRandom(GetRegisters2());
}
}
void GenerateRandomBytes(void *dst, size_t size) {
/* If we're not generating any bytes, there's nothing to do. */
if (size == 0) {
return;
}
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine how many blocks to generate. */
const size_t num_blocks = size / AesBlockSize;
const size_t aligned_size = num_blocks * AesBlockSize;
const size_t fractional = size - aligned_size;
/* Configure the RNG to generate random to memory. */
ConfigRng(SE, SE_CONFIG_DST_MEMORY, SE_RNG_CONFIG_MODE_NORMAL);
/* Generate as many aligned blocks as we can. */
if (aligned_size > 0) {
/* Configure the engine to generate the right number of blocks. */
SE->SE_CRYPTO_LAST_BLOCK = num_blocks - 1;
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dst, aligned_size, nullptr, 0);
}
/* Generate a single block to output. */
if (fractional > 0) {
ExecuteOperationSingleBlock(SE, static_cast<u8 *>(dst) + aligned_size, fractional, nullptr, 0);
}
}
void SetRandomKey(int slot) {
/* NOTE: Nintendo does not validate the destination keyslot here. */
/* Get the engine. */
auto *SE = GetRegisters();
/* Configure the RNG to output to the keytable. */
ConfigRng(SE, SE_CONFIG_DST_KEYTABLE, SE_RNG_CONFIG_MODE_NORMAL);
/* Configure the keytable destination to be the low part of the key. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_DST, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_DST_KEY_INDEX, slot), SE_REG_BITS_ENUM(CRYPTO_KEYTABLE_DST_WORD_QUAD, KEYS_0_3));
/* Configure a single block operation. */
SE->SE_CRYPTO_LAST_BLOCK = 0;
/* Execute the operation to generate a random low-part of the key. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, nullptr, 0);
/* Configure the keytable destination to be the high part of the key. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_DST, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_DST_KEY_INDEX, slot), SE_REG_BITS_ENUM(CRYPTO_KEYTABLE_DST_WORD_QUAD, KEYS_4_7));
/* Execute the operation to generate a random high-part of the key. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, nullptr, 0);
}
void GenerateSrk() {
/* Generate SRK for SE1. */
GenerateSrk(GetRegisters());
/* If we have SE2, generate SRK for SE2. */
/* NOTE: Nintendo's implementation of this is incorrect. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
GenerateSrk(GetRegisters2());
}
}
}
| 7,162
|
C++
|
.cpp
| 126
| 44.063492
| 162
| 0.582286
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,913
|
se_rsa.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_rsa.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
struct RsaKeyInfo {
int modulus_size_val;
int exponent_size_val;
};
constinit RsaKeyInfo g_rsa_key_infos[RsaKeySlotCount] = {};
void ClearRsaKeySlot(volatile SecurityEngineRegisters *SE, int slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL expmod) {
constexpr int NumWords = se::RsaSize / sizeof(u32);
for (int i = 0; i < NumWords; ++i) {
/* Select the keyslot word. */
reg::Write(SE->SE_RSA_KEYTABLE_ADDR, SE_REG_BITS_ENUM (RSA_KEYTABLE_ADDR_INPUT_MODE, REGISTER),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_KEY_SLOT, slot),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_EXPMOD_SEL, expmod),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_WORD_ADDR, i));
/* Clear the keyslot word. */
SE->SE_RSA_KEYTABLE_DATA = 0;
}
}
void SetRsaKey(volatile SecurityEngineRegisters *SE, int slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL expmod, const void *key, size_t key_size) {
const int num_words = key_size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
/* Select the keyslot word. */
reg::Write(SE->SE_RSA_KEYTABLE_ADDR, SE_REG_BITS_ENUM (RSA_KEYTABLE_ADDR_INPUT_MODE, REGISTER),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_KEY_SLOT, slot),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_EXPMOD_SEL, expmod),
SE_REG_BITS_VALUE(RSA_KEYTABLE_ADDR_WORD_ADDR, i));
/* Get the word. */
const u32 word = util::LoadBigEndian(static_cast<const u32 *>(key) + (num_words - 1 - i));
/* Write the keyslot word. */
SE->SE_RSA_KEYTABLE_DATA = word;
}
}
void GetRsaResult(volatile SecurityEngineRegisters *SE, void *dst, size_t size) {
/* Copy out the words. */
const int num_words = size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
const u32 word = reg::Read(SE->SE_RSA_OUTPUT[i]);
util::StoreBigEndian(static_cast<u32 *>(dst) + num_words - 1 - i, word);
}
}
void WaitForInputReadComplete(volatile SecurityEngineRegisters *SE) {
while (reg::HasValue(SE->SE_INT_STATUS, SE_REG_BITS_ENUM(INT_STATUS_IN_DONE, CLEAR))) { /* ... */ }
}
}
void ClearRsaKeySlot(int slot) {
/* Validate the key slot. */
AMS_ABORT_UNLESS(0 <= slot && slot < RsaKeySlotCount);
/* Clear the info. */
g_rsa_key_infos[slot] = {};
/* Get the engine. */
auto *SE = GetRegisters();
/* Clear the modulus. */
ClearRsaKeySlot(SE, slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL_MODULUS);
/* Clear the exponent. */
ClearRsaKeySlot(SE, slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL_EXPONENT);
}
void LockRsaKeySlot(int slot, u32 flags) {
/* Validate the key slot. */
AMS_ABORT_UNLESS(0 <= slot && slot < RsaKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Set non per-key flags. */
if ((flags & ~KeySlotLockFlags_PerKey) != 0) {
/* Pack the flags into the expected format. */
u32 value = 0;
value |= ((flags & KeySlotLockFlags_KeyRead) == 0) ? (1u << 0) : 0;
value |= ((flags & KeySlotLockFlags_KeyRead) == 0) ? (1u << 1) : 0;
value |= ((flags & KeySlotLockFlags_KeyRead) == 0) ? (1u << 2) : 0;
reg::Write(SE->SE_RSA_KEYTABLE_ACCESS[slot], SE_REG_BITS_ENUM_SEL(RSA_KEYTABLE_ACCESS_KEYREAD, (flags & KeySlotLockFlags_KeyRead) != 0, DISABLE, ENABLE),
SE_REG_BITS_ENUM_SEL(RSA_KEYTABLE_ACCESS_KEYUPDATE, (flags & KeySlotLockFlags_KeyWrite) != 0, DISABLE, ENABLE),
SE_REG_BITS_ENUM_SEL(RSA_KEYTABLE_ACCESS_KEYUSE, (flags & KeySlotLockFlags_KeyUse) != 0, DISABLE, ENABLE));
}
/* Set per-key flag. */
if ((flags & KeySlotLockFlags_PerKey) != 0) {
reg::ReadWrite(SE->SE_RSA_SECURITY_PERKEY, REG_BITS_VALUE(slot, 1, 0));
}
}
void SetRsaKey(int slot, const void *mod, size_t mod_size, const void *exp, size_t exp_size) {
/* Validate the key slot and sizes. */
AMS_ABORT_UNLESS(0 <= slot && slot < RsaKeySlotCount);
AMS_ABORT_UNLESS(mod_size <= RsaSize);
AMS_ABORT_UNLESS(exp_size <= RsaSize);
/* Set the sizes in the info. */
auto &info = g_rsa_key_infos[slot];
info.modulus_size_val = (mod_size / 64) - 1;
info.exponent_size_val = (exp_size / 4);
/* Get the engine. */
auto *SE = GetRegisters();
/* Set the modulus and exponent. */
SetRsaKey(SE, slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL_MODULUS, mod, mod_size);
SetRsaKey(SE, slot, SE_RSA_KEYTABLE_ADDR_EXPMOD_SEL_EXPONENT, exp, exp_size);
}
void ModularExponentiate(void *dst, size_t dst_size, int slot, const void *src, size_t src_size) {
/* Validate the slot and sizes. */
AMS_ABORT_UNLESS(0 <= slot && slot < RsaKeySlotCount);
AMS_ABORT_UNLESS(src_size <= RsaSize);
AMS_ABORT_UNLESS(dst_size <= RsaSize);
/* Get the engine. */
auto *SE = GetRegisters();
/* Create a work buffer. */
u8 work[RsaSize];
util::ClearMemory(work, sizeof(work));
/* Copy the input into the work buffer (reversing endianness). */
const u8 *src_u8 = static_cast<const u8 *>(src);
for (size_t i = 0; i < src_size; ++i) {
work[src_size - 1 - i] = src_u8[i];
}
/* Flush the work buffer to ensure the SE sees correct results. */
hw::FlushDataCache(work, sizeof(work));
hw::DataSynchronizationBarrierInnerShareable();
/* Configure the engine to perform RSA encryption. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_ENC_ALG, RSA),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DST, RSA_REG));
/* Configure the engine to use the keyslot and correct modulus/exp sizes. */
const auto &info = g_rsa_key_infos[slot];
reg::Write(SE->SE_RSA_CONFIG, SE_REG_BITS_VALUE(RSA_CONFIG_KEY_SLOT, slot));
reg::Write(SE->SE_RSA_KEY_SIZE, info.modulus_size_val);
reg::Write(SE->SE_RSA_EXP_SIZE, info.exponent_size_val);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, work, src_size);
/* Copy out the result. */
GetRsaResult(SE, dst, dst_size);
}
void ModularExponentiateAsync(int slot, const void *src, size_t src_size, DoneHandler handler) {
/* Validate the slot and size. */
AMS_ABORT_UNLESS(0 <= slot && slot < RsaKeySlotCount);
AMS_ABORT_UNLESS(src_size <= RsaSize);
/* Get the engine. */
auto *SE = GetRegisters();
/* Create a work buffer. */
u8 work[RsaSize];
util::ClearMemory(work, sizeof(work));
/* Copy the input into the work buffer (reversing endianness). */
const u8 *src_u8 = static_cast<const u8 *>(src);
for (size_t i = 0; i < src_size; ++i) {
work[src_size - 1 - i] = src_u8[i];
}
/* Flush the work buffer to ensure the SE sees correct results. */
hw::FlushDataCache(work, sizeof(work));
hw::DataSynchronizationBarrierInnerShareable();
/* Configure the engine to perform RSA encryption. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_ENC_ALG, RSA),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DST, RSA_REG));
/* Configure the engine to use the keyslot and correct modulus/exp sizes. */
const auto &info = g_rsa_key_infos[slot];
reg::Write(SE->SE_RSA_CONFIG, SE_REG_BITS_VALUE(RSA_CONFIG_KEY_SLOT, slot));
reg::Write(SE->SE_RSA_KEY_SIZE, info.modulus_size_val);
reg::Write(SE->SE_RSA_EXP_SIZE, info.exponent_size_val);
/* Set the done handler. */
SetDoneHandler(SE, handler);
/* Trigger the input operation. */
StartInputOperation(SE, work, src_size);
/* Wait for input to be read by the se. */
WaitForInputReadComplete(SE);
}
void GetRsaResult(void *dst, size_t dst_size) {
GetRsaResult(GetRegisters(), dst, dst_size);
}
}
| 10,009
|
C++
|
.cpp
| 183
| 42.344262
| 169
| 0.563043
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,914
|
se_aes.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_aes.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
constexpr inline int AesKeySizeMax = 256 / BITSIZEOF(u8);
enum AesMode {
AesMode_Aes128 = ((SE_CONFIG_ENC_MODE_AESMODE_KEY128 << SE_CONFIG_ENC_MODE_OFFSET) | (SE_CONFIG_DEC_MODE_AESMODE_KEY128 << SE_CONFIG_DEC_MODE_OFFSET)) >> SE_CONFIG_DEC_MODE_OFFSET,
AesMode_Aes192 = ((SE_CONFIG_ENC_MODE_AESMODE_KEY192 << SE_CONFIG_ENC_MODE_OFFSET) | (SE_CONFIG_DEC_MODE_AESMODE_KEY192 << SE_CONFIG_DEC_MODE_OFFSET)) >> SE_CONFIG_DEC_MODE_OFFSET,
AesMode_Aes256 = ((SE_CONFIG_ENC_MODE_AESMODE_KEY256 << SE_CONFIG_ENC_MODE_OFFSET) | (SE_CONFIG_DEC_MODE_AESMODE_KEY256 << SE_CONFIG_DEC_MODE_OFFSET)) >> SE_CONFIG_DEC_MODE_OFFSET,
};
enum MemoryInterface {
MemoryInterface_Ahb = SE_CRYPTO_CONFIG_MEMIF_AHB,
MemoryInterface_Mc = SE_CRYPTO_CONFIG_MEMIF_MCCIF,
};
constexpr inline u32 AesConfigEcb = reg::Encode(SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, BYPASS),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
constexpr inline u32 AesConfigCtr = reg::Encode(SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 1),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, LINEAR_CTR),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, BOTTOM),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
constexpr inline u32 AesConfigCmac = reg::Encode(SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, INIT_AESOUT),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, TOP),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, ENABLE));
constexpr inline u32 AesConfigCbcEncrypt = reg::Encode(SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, INIT_AESOUT),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, TOP),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
constexpr inline u32 AesConfigCbcDecrypt = reg::Encode(SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, INIT_PREV_MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, BOTTOM),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
void SetConfig(volatile SecurityEngineRegisters *SE, bool encrypt, SE_CONFIG_DST dst) {
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM (CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM (CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM_SEL(CONFIG_ENC_ALG, encrypt, AES_ENC, NOP),
SE_REG_BITS_ENUM_SEL(CONFIG_DEC_ALG, encrypt, NOP, AES_DEC),
SE_REG_BITS_VALUE (CONFIG_DST, dst));
}
void SetAesConfig(volatile SecurityEngineRegisters *SE, int slot, bool encrypt, u32 config) {
const u32 encoded = reg::Encode(SE_REG_BITS_ENUM (CRYPTO_CONFIG_MEMIF, AHB),
SE_REG_BITS_VALUE (CRYPTO_CONFIG_KEY_INDEX, slot),
SE_REG_BITS_ENUM_SEL(CRYPTO_CONFIG_CORE_SEL, encrypt, ENCRYPT, DECRYPT));
reg::Write(SE->SE_CRYPTO_CONFIG, (config | encoded));
}
void SetBlockCount(volatile SecurityEngineRegisters *SE, int count) {
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, count - 1);
}
void UpdateAesMode(volatile SecurityEngineRegisters *SE, AesMode mode) {
reg::ReadWrite(SE->SE_CONFIG, REG_BITS_VALUE(16, 16, mode));
}
void UpdateMemoryInterface(volatile SecurityEngineRegisters *SE, MemoryInterface memif) {
reg::ReadWrite(SE->SE_CRYPTO_CONFIG, SE_REG_BITS_VALUE(CRYPTO_CONFIG_MEMIF, memif));
}
void SetCounter(volatile SecurityEngineRegisters *SE, const void *ctr) {
const u32 *ctr_32 = reinterpret_cast<const u32 *>(ctr);
/* Copy the input ctr to the linear CTR registers. */
reg::Write(SE->SE_CRYPTO_LINEAR_CTR[0], util::LoadLittleEndian(ctr_32 + 0));
reg::Write(SE->SE_CRYPTO_LINEAR_CTR[1], util::LoadLittleEndian(ctr_32 + 1));
reg::Write(SE->SE_CRYPTO_LINEAR_CTR[2], util::LoadLittleEndian(ctr_32 + 2));
reg::Write(SE->SE_CRYPTO_LINEAR_CTR[3], util::LoadLittleEndian(ctr_32 + 3));
}
void SetAesKeyIv(volatile SecurityEngineRegisters *SE, int slot, const void *iv, size_t iv_size) {
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
AMS_ABORT_UNLESS(iv_size <= AesBlockSize);
/* Set each iv word in order. */
const u32 *iv_u32 = static_cast<const u32 *>(iv);
const int num_words = iv_size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
/* Select the keyslot. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_KEYIV_SEL, IV),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_IV_SEL, ORIGINAL_IV),
SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_WORD, i));
/* Set the iv word. */
SE->SE_CRYPTO_KEYTABLE_DATA = *(iv_u32++);
}
}
void SetEncryptedAesKey(int dst_slot, int kek_slot, const void *key, size_t key_size, AesMode mode) {
AMS_ABORT_UNLESS(key_size <= AesKeySizeMax);
AMS_ABORT_UNLESS(0 <= dst_slot && dst_slot < AesKeySlotCount);
AMS_ABORT_UNLESS(0 <= kek_slot && kek_slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Configure for single AES ECB decryption to key table. */
SetConfig(SE, false, SE_CONFIG_DST_KEYTABLE);
SetAesConfig(SE, kek_slot, false, AesConfigEcb);
UpdateAesMode(SE, mode);
SetBlockCount(SE, 1);
/* Select the destination keyslot. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_DST, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_DST_KEY_INDEX, dst_slot), SE_REG_BITS_ENUM(CRYPTO_KEYTABLE_DST_WORD_QUAD, KEYS_0_3));
/* Ensure that the se sees the keydata we want it to. */
hw::FlushDataCache(key, key_size);
hw::DataSynchronizationBarrierInnerShareable();
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, key, key_size);
}
void EncryptAes(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, AesMode mode) {
/* If nothing to decrypt, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(dst_size == AesBlockSize);
AMS_ABORT_UNLESS(src_size == AesBlockSize);
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Configure for AES-ECB encryption to memory. */
SetConfig(SE, true, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, true, AesConfigEcb);
UpdateAesMode(SE, mode);
/* Execute the operation. */
ExecuteOperationSingleBlock(SE, dst, dst_size, src, src_size);
}
void ExpandSubkey(u8 *subkey) {
/* Shift everything left one bit. */
u8 prev = 0;
for (int i = AesBlockSize - 1; i >= 0; --i) {
const u8 top = (subkey[i] >> 7);
subkey[i] = ((subkey[i] << 1) | prev);
prev = top;
}
/* And xor with Rb if necessary. */
if (prev != 0) {
subkey[AesBlockSize - 1] ^= 0x87;
}
}
void ExpandSubkeyLittleEndian(u8 *subkey) {
/* Shift everything left one bit. */
u8 prev = 0;
for (size_t i = 0; i < AesBlockSize; ++i) {
const u8 top = (subkey[i] >> 7);
subkey[i] = ((subkey[i] << 1) | prev);
prev = top;
}
/* And xor with Rb if necessary. */
if (prev != 0) {
subkey[0] ^= 0x87;
}
}
void GetCmacResult(volatile SecurityEngineRegisters *SE, void *dst, size_t dst_size) {
const int num_words = dst_size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
reg::Write(static_cast<u32 *>(dst) + i, reg::Read(SE->SE_HASH_RESULT[i]));
}
}
void ComputeAesCmac(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, AesMode mode) {
/* Validate input. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine mac extents. */
const int num_blocks = util::DivideUp(src_size, AesBlockSize);
const size_t last_block_size = (src_size == 0) ? 0 : (src_size - ((num_blocks - 1) * AesBlockSize));
/* Create subkey. */
u8 subkey[AesBlockSize];
{
/* Encrypt zeroes. */
std::memset(subkey, 0, sizeof(subkey));
EncryptAes(subkey, sizeof(subkey), slot, subkey, sizeof(subkey), mode);
/* Expand. */
ExpandSubkey(subkey);
/* Account for last block. */
if (last_block_size != AesBlockSize) {
ExpandSubkey(subkey);
}
}
/* Configure for AES-CMAC. */
SetConfig(SE, true, SE_CONFIG_DST_HASH_REG);
SetAesConfig(SE, slot, true, AesConfigCmac);
UpdateAesMode(SE, mode);
/* Set the IV to zero. */
for (int i = 0; i < 4; ++i) {
/* Select the keyslot. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_KEYIV_SEL, IV),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_IV_SEL, ORIGINAL_IV),
SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_WORD, i));
/* Set the iv word. */
SE->SE_CRYPTO_KEYTABLE_DATA = 0;
}
/* Handle blocks before the last. */
if (num_blocks > 1) {
SetBlockCount(SE, num_blocks - 1);
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, src, src_size);
reg::ReadWrite(SE->SE_CRYPTO_CONFIG, SE_REG_BITS_ENUM(CRYPTO_CONFIG_IV_SELECT, UPDATED));
}
/* Handle the last block. */
{
SetBlockCount(SE, 1);
/* Create the last block. */
u8 last_block[AesBlockSize];
if (last_block_size < sizeof(last_block)) {
std::memset(last_block, 0, sizeof(last_block));
last_block[last_block_size] = 0x80;
}
std::memcpy(last_block, static_cast<const u8 *>(src) + src_size - last_block_size, last_block_size);
/* Xor with the subkey. */
for (size_t i = 0; i < AesBlockSize; ++i) {
last_block[i] ^= subkey[i];
}
/* Ensure the SE sees correct data. */
hw::FlushDataCache(last_block, sizeof(last_block));
hw::DataSynchronizationBarrierInnerShareable();
ExecuteOperation(SE, SE_OPERATION_OP_START, nullptr, 0, last_block, sizeof(last_block));
}
/* Get the output. */
GetCmacResult(SE, dst, dst_size);
}
void EncryptAesCbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size, AesMode mode) {
/* If nothing to encrypt, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine extents. */
const size_t num_blocks = src_size / AesBlockSize;
const size_t aligned_size = num_blocks * AesBlockSize;
AMS_ABORT_UNLESS(src_size == aligned_size);
/* Configure for aes-cbc encryption. */
SetConfig(SE, true, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, true, AesConfigCbcEncrypt);
UpdateAesMode(SE, mode);
/* Set the iv. */
SetAesKeyIv(SE, slot, iv, iv_size);
/* Set the block count. */
SetBlockCount(SE, num_blocks);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dst, dst_size, src, aligned_size);
}
void DecryptAesCbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size, AesMode mode) {
/* If nothing to decrypt, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine extents. */
const size_t num_blocks = src_size / AesBlockSize;
const size_t aligned_size = num_blocks * AesBlockSize;
AMS_ABORT_UNLESS(src_size == aligned_size);
/* Configure for aes-cbc encryption. */
SetConfig(SE, false, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, false, AesConfigCbcDecrypt);
UpdateAesMode(SE, mode);
/* Set the iv. */
SetAesKeyIv(SE, slot, iv, iv_size);
/* Set the block count. */
SetBlockCount(SE, num_blocks);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dst, dst_size, src, aligned_size);
}
void XorWithXtsTweak(void *dst, size_t dst_size, const void *src, size_t src_size, const void *base_tweak) {
/* Copy tweak. */
u8 tweak[se::AesBlockSize];
std::memcpy(tweak, base_tweak, sizeof(tweak));
/* Perform xor. */
u8 *dst_u8 = static_cast<u8 *>(dst);
const u8 *src_u8 = static_cast<const u8 *>(src);
const size_t num_blocks = std::min<size_t>(dst_size, src_size) / sizeof(tweak);
for (size_t i = 0; i < num_blocks; ++i) {
for (size_t j = 0; j < sizeof(tweak); ++j) {
dst_u8[j] = src_u8[j] ^ tweak[j];
}
dst_u8 += sizeof(tweak);
src_u8 += sizeof(tweak);
ExpandSubkeyLittleEndian(tweak);
}
}
void DecryptAesXts(void *dst, size_t dst_size, int slot_enc, int slot_tweak, const void *src, size_t src_size, size_t sector, AesMode mode) {
/* If nothing to decrypt, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(util::IsAligned(dst_size, AesBlockSize));
AMS_ABORT_UNLESS(util::IsAligned(src_size, AesBlockSize));
AMS_ABORT_UNLESS(0 <= slot_enc && slot_enc < AesKeySlotCount);
AMS_ABORT_UNLESS(0 <= slot_tweak && slot_tweak < AesKeySlotCount);
/* Generate tweak. */
u32 base_tweak[se::AesBlockSize / sizeof(u32)] = {};
base_tweak[util::size(base_tweak) - 1] = util::ConvertToBigEndian<u32>(static_cast<u32>(sector));
if constexpr (sizeof(sector) > sizeof(u32)) {
static_assert(sizeof(sector) <= sizeof(u64));
base_tweak[util::size(base_tweak) - 2] = util::ConvertToBigEndian<u32>(static_cast<u32>(sector >> BITSIZEOF(u32)));
}
se::EncryptAes128(base_tweak, sizeof(base_tweak), slot_tweak, base_tweak, sizeof(base_tweak));
/* Xor all data. */
XorWithXtsTweak(dst, dst_size, src, src_size, base_tweak);
/* Ensure the SE sees correct data. */
hw::FlushDataCache(dst, dst_size);
/* Decrypt all data. */
{
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine extents. */
const size_t num_blocks = dst_size / AesBlockSize;
/* Configure for AES-ECB decryption to memory. */
SetConfig(SE, false, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot_enc, false, AesConfigEcb);
UpdateAesMode(SE, mode);
/* Set the block count. */
SetBlockCount(SE, num_blocks);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dst, dst_size, dst, dst_size);
/* Ensure the cpu sees correct data. */
hw::InvalidateDataCache(dst, dst_size);
}
/* Xor all data. */
XorWithXtsTweak(dst, dst_size, dst, dst_size, base_tweak);
}
void ComputeAes128Async(u32 out_ll_address, int slot, u32 in_ll_address, u32 size, DoneHandler handler, u32 config, bool encrypt, volatile SecurityEngineRegisters *SE) {
/* If nothing to decrypt, succeed. */
if (size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Configure for the specific operation. */
SetConfig(SE, encrypt, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, encrypt, config);
UpdateMemoryInterface(SE, MemoryInterface_Mc);
/* Configure the number of blocks. */
const int num_blocks = size / AesBlockSize;
SetBlockCount(SE, num_blocks);
/* Set the done handler. */
SetDoneHandler(SE, handler);
/* Start the raw operation. */
StartOperationRaw(SE, SE_OPERATION_OP_START, out_ll_address, in_ll_address);
}
void ClearAesKeySlot(volatile SecurityEngineRegisters *SE, int slot) {
/* Validate the key slot. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
for (int i = 0; i < 16; ++i) {
/* Select the keyslot. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot), SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_WORD, i));
/* Write the data. */
SE->SE_CRYPTO_KEYTABLE_DATA = 0;
}
}
}
void ClearAesKeySlot(int slot) {
/* Clear the slot in SE1. */
ClearAesKeySlot(GetRegisters(), slot);
}
void ClearAesKeySlot2(int slot) {
/* Clear the slot in SE2. */
ClearAesKeySlot(GetRegisters2(), slot);
}
void ClearAesKeyIv(int slot) {
/* Validate the key slot. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Set each iv word in order. */
for (int i = 0; i < 4; ++i) {
/* Select the keyslot original iv. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_KEYIV_SEL, IV),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_IV_SEL, ORIGINAL_IV),
SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_WORD, i));
/* Set the iv word. */
SE->SE_CRYPTO_KEYTABLE_DATA = 0;
/* Select the keyslot updated iv. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_KEYIV_SEL, IV),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_IV_SEL, UPDATED_IV),
SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_WORD, i));
/* Set the iv word. */
SE->SE_CRYPTO_KEYTABLE_DATA = 0;
}
}
void LockAesKeySlot(int slot, u32 flags) {
/* Validate the key slot. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Set non per-key flags. */
if ((flags & ~KeySlotLockFlags_PerKey) != 0) {
/* KeySlotLockFlags_DstKeyTableOnly is Mariko-only. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
reg::ReadWrite(SE->SE_CRYPTO_KEYTABLE_ACCESS[slot], REG_BITS_VALUE(0, 7, ~flags), REG_BITS_VALUE(7, 1, ((flags & KeySlotLockFlags_DstKeyTableOnly) != 0) ? 1 : 0));
} else {
reg::ReadWrite(SE->SE_CRYPTO_KEYTABLE_ACCESS[slot], REG_BITS_VALUE(0, 7, ~flags));
}
}
/* Set per-key flag. */
if ((flags & KeySlotLockFlags_PerKey) != 0) {
reg::ReadWrite(SE->SE_CRYPTO_SECURITY_PERKEY, REG_BITS_VALUE(slot, 1, 0));
}
}
void SetAesKey(int slot, const void *key, size_t key_size) {
/* Validate the key slot and key size. */
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
AMS_ABORT_UNLESS(key_size <= AesKeySizeMax);
/* Get the engine. */
auto *SE = GetRegisters();
/* Set each key word in order. */
const u32 *key_u32 = static_cast<const u32 *>(key);
const int num_words = key_size / sizeof(u32);
for (int i = 0; i < num_words; ++i) {
/* Select the keyslot. */
reg::Write(SE->SE_CRYPTO_KEYTABLE_ADDR, SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_SLOT, slot),
SE_REG_BITS_ENUM (CRYPTO_KEYTABLE_ADDR_KEYIV_KEYIV_SEL, KEY),
SE_REG_BITS_VALUE(CRYPTO_KEYTABLE_ADDR_KEYIV_KEY_WORD, i));
/* Set the key word. */
SE->SE_CRYPTO_KEYTABLE_DATA = *(key_u32++);
}
}
void SetEncryptedAesKey128(int dst_slot, int kek_slot, const void *key, size_t key_size) {
return SetEncryptedAesKey(dst_slot, kek_slot, key, key_size, AesMode_Aes128);
}
void SetEncryptedAesKey256(int dst_slot, int kek_slot, const void *key, size_t key_size) {
return SetEncryptedAesKey(dst_slot, kek_slot, key, key_size, AesMode_Aes256);
}
void EncryptAes128(void *dst, size_t dst_size, int slot, const void *src, size_t src_size) {
return EncryptAes(dst, dst_size, slot, src, src_size, AesMode_Aes128);
}
void DecryptAes128(void *dst, size_t dst_size, int slot, const void *src, size_t src_size) {
/* If nothing to decrypt, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(dst_size == AesBlockSize);
AMS_ABORT_UNLESS(src_size == AesBlockSize);
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Configure for AES-ECB decryption to memory. */
SetConfig(SE, false, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, false, AesConfigEcb);
ExecuteOperationSingleBlock(SE, dst, dst_size, src, src_size);
}
void ComputeAes128Ctr(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) {
/* If nothing to do, succeed. */
if (src_size == 0) { return; }
/* Validate input. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
AMS_ABORT_UNLESS(0 <= slot && slot < AesKeySlotCount);
/* Get the engine. */
auto *SE = GetRegisters();
/* Determine how many full blocks we can operate on. */
const size_t num_blocks = src_size / AesBlockSize;
const size_t aligned_size = num_blocks * AesBlockSize;
const size_t fractional = src_size - aligned_size;
/* Here Nintendo writes 1 to SE_SPARE. It's unclear why they do this, but we will do so as well. */
SE->SE_SPARE = 0x1;
/* Configure for AES-CTR encryption/decryption to memory. */
SetConfig(SE, true, SE_CONFIG_DST_MEMORY);
SetAesConfig(SE, slot, true, AesConfigCtr);
/* Set the counter. */
SetCounter(SE, iv);
/* Process as many aligned blocks as we can. */
if (aligned_size > 0) {
/* Configure the engine to process the right number of blocks. */
SetBlockCount(SE, num_blocks);
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, dst, dst_size, src, aligned_size);
/* Synchronize around this point. */
hw::DataSynchronizationBarrierInnerShareable();
}
/* Process a single block to output. */
if (fractional > 0 && dst_size > aligned_size) {
const size_t copy_size = std::min(fractional, dst_size - aligned_size);
ExecuteOperationSingleBlock(SE, static_cast<u8 *>(dst) + aligned_size, copy_size, static_cast<const u8 *>(src) + aligned_size, fractional);
}
}
void ComputeAes128Cmac(void *dst, size_t dst_size, int slot, const void *src, size_t src_size) {
return ComputeAesCmac(dst, dst_size, slot, src, src_size, AesMode_Aes128);
}
void ComputeAes256Cmac(void *dst, size_t dst_size, int slot, const void *src, size_t src_size) {
return ComputeAesCmac(dst, dst_size, slot, src, src_size, AesMode_Aes256);
}
void EncryptAes128Cbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) {
return EncryptAesCbc(dst, dst_size, slot, src, src_size, iv, iv_size, AesMode_Aes128);
}
void EncryptAes256Cbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) {
return EncryptAesCbc(dst, dst_size, slot, src, src_size, iv, iv_size, AesMode_Aes256);
}
void DecryptAes128Cbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) {
return DecryptAesCbc(dst, dst_size, slot, src, src_size, iv, iv_size, AesMode_Aes128);
}
void DecryptAes256Cbc(void *dst, size_t dst_size, int slot, const void *src, size_t src_size, const void *iv, size_t iv_size) {
return DecryptAesCbc(dst, dst_size, slot, src, src_size, iv, iv_size, AesMode_Aes256);
}
void DecryptAes128Xts(void *dst, size_t dst_size, int slot_enc, int slot_tweak, const void *src, size_t src_size, size_t sector) {
return DecryptAesXts(dst, dst_size, slot_enc, slot_tweak, src, src_size, sector, AesMode_Aes128);
}
void EncryptAes128CbcAsync(u32 out_ll_address, int slot, u32 in_ll_address, u32 size, const void *iv, size_t iv_size, DoneHandler handler) {
/* Validate the iv. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
/* Get the registers. */
volatile auto *SE = GetRegisters();
/* Set the iv. */
SetAesKeyIv(SE, slot, iv, iv_size);
/* Perform the asynchronous aes operation. */
ComputeAes128Async(out_ll_address, slot, in_ll_address, size, handler, AesConfigCbcEncrypt, true, SE);
}
void DecryptAes128CbcAsync(u32 out_ll_address, int slot, u32 in_ll_address, u32 size, const void *iv, size_t iv_size, DoneHandler handler) {
/* Validate the iv. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
/* Get the registers. */
volatile auto *SE = GetRegisters();
/* Set the iv. */
SetAesKeyIv(SE, slot, iv, iv_size);
/* Perform the asynchronous aes operation. */
ComputeAes128Async(out_ll_address, slot, in_ll_address, size, handler, AesConfigCbcDecrypt, false, SE);
}
void ComputeAes128CtrAsync(u32 out_ll_address, int slot, u32 in_ll_address, u32 size, const void *iv, size_t iv_size, DoneHandler handler) {
/* Validate the iv. */
AMS_ABORT_UNLESS(iv_size == AesBlockSize);
/* Get the registers. */
volatile auto *SE = GetRegisters();
/* Here Nintendo writes 1 to SE_SPARE. It's unclear why they do this, but we will do so as well. */
SE->SE_SPARE = 0x1;
/* Set the counter. */
SetCounter(SE, iv);
/* Perform the asynchronous aes operation. */
ComputeAes128Async(out_ll_address, slot, in_ll_address, size, handler, AesConfigCtr, true, SE);
}
}
| 33,376
|
C++
|
.cpp
| 550
| 44.787273
| 192
| 0.532825
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,915
|
se_execute.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_execute.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
struct LinkedListEntry {
u32 zero;
u32 address;
u32 size;
};
static_assert(util::is_pod<LinkedListEntry>::value);
static_assert(sizeof(LinkedListEntry) == 0xC);
uintptr_t GetPhysicalAddress(const void *ptr) {
const uintptr_t virt_address = reinterpret_cast<uintptr_t>(ptr);
#if defined(ATMOSPHERE_ARCH_ARM64)
u64 phys_address;
__asm__ __volatile__("at s1e3r, %[virt]; mrs %[phys], par_el1" : [phys]"=r"(phys_address) : [virt]"r"(virt_address) : "memory", "cc");
return (phys_address & 0x0000FFFFFFFFF000ul) | (virt_address & 0x0000000000000FFFul);
#elif defined(ATMOSPHERE_ARCH_ARM)
return virt_address;
#else
#error "Unknown architecture for Tegra Security Engine physical address translation"
#endif
}
constexpr void SetLinkedListEntry(LinkedListEntry *entry, const void *ptr, size_t size) {
/* Clear the zero field. */
entry->zero = 0;
/* Set the address. */
if (ptr != nullptr) {
entry->address = GetPhysicalAddress(ptr);
entry->size = static_cast<u32>(size);
} else {
entry->address = 0;
entry->size = 0;
}
}
void StartOperation(volatile SecurityEngineRegisters *SE, SE_OPERATION_OP op) {
/* Write back the current values of the error and interrupt status. */
reg::Write(SE->SE_ERR_STATUS, reg::Read(SE->SE_ERR_STATUS));
reg::Write(SE->SE_INT_STATUS, reg::Read(SE->SE_INT_STATUS));
/* Write the operation. */
reg::Write(SE->SE_OPERATION, SE_REG_BITS_VALUE(OPERATION_OP, op));
}
void EnsureOperationStarted(volatile SecurityEngineRegisters *SE) {
/* Read the operation register to make sure our write takes. */
reg::Read(SE->SE_OPERATION);
hw::DataSynchronizationBarrierInnerShareable();
}
void WaitForOperationComplete(volatile SecurityEngineRegisters *SE) {
/* Spin until the operation is done. */
while (reg::HasValue(SE->SE_INT_STATUS, SE_REG_BITS_ENUM(INT_STATUS_SE_OP_DONE, CLEAR))) { /* ... */ }
/* Check for operation success. */
ValidateAesOperationResult(SE);
}
}
void ExecuteOperation(volatile SecurityEngineRegisters *SE, SE_OPERATION_OP op, void *dst, size_t dst_size, const void *src, size_t src_size) {
/* Set the linked list entries. */
LinkedListEntry src_entry;
LinkedListEntry dst_entry;
SetLinkedListEntry(std::addressof(src_entry), src, src_size);
SetLinkedListEntry(std::addressof(dst_entry), dst, dst_size);
/* Ensure the linked list entry data is seen correctly. */
hw::FlushDataCache(std::addressof(src_entry), sizeof(src_entry));
hw::FlushDataCache(std::addressof(dst_entry), sizeof(dst_entry));
hw::DataSynchronizationBarrierInnerShareable();
/* Configure the linked list addresses. */
reg::Write(SE->SE_IN_LL_ADDR, static_cast<u32>(GetPhysicalAddress(std::addressof(src_entry))));
reg::Write(SE->SE_OUT_LL_ADDR, static_cast<u32>(GetPhysicalAddress(std::addressof(dst_entry))));
/* Start the operation. */
StartOperation(SE, op);
/* Wait for the operation to complete. */
WaitForOperationComplete(SE);
}
void ExecuteOperationSingleBlock(volatile SecurityEngineRegisters *SE, void *dst, size_t dst_size, const void *src, size_t src_size) {
/* Validate sizes. */
AMS_ABORT_UNLESS(dst_size <= AesBlockSize);
AMS_ABORT_UNLESS(src_size <= AesBlockSize);
/* Set the block count to 1. */
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, 0);
/* Create an aligned buffer. */
util::AlignedBuffer<hw::DataCacheLineSize, AesBlockSize> aligned;
std::memcpy(aligned, src, src_size);
hw::FlushDataCache(aligned, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_START, aligned, AesBlockSize, aligned, AesBlockSize);
/* Ensure that the CPU will see the correct output. */
hw::DataSynchronizationBarrierInnerShareable();
hw::FlushDataCache(aligned, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Copy the output to the destination. */
std::memcpy(dst, aligned, dst_size);
}
void StartInputOperation(volatile SecurityEngineRegisters *SE, const void *src, size_t src_size) {
/* Set the linked list entry. */
LinkedListEntry src_entry;
SetLinkedListEntry(std::addressof(src_entry), src, src_size);
/* Ensure the linked list entry data is seen correctly. */
hw::FlushDataCache(std::addressof(src_entry), sizeof(src_entry));
hw::DataSynchronizationBarrierInnerShareable();
/* Configure the linked list addresses. */
reg::Write(SE->SE_IN_LL_ADDR, static_cast<u32>(GetPhysicalAddress(std::addressof(src_entry))));
/* Start the operation. */
StartOperation(SE, SE_OPERATION_OP_START);
/* Ensure the operation is started. */
EnsureOperationStarted(SE);
}
void StartOperationRaw(volatile SecurityEngineRegisters *SE, SE_OPERATION_OP op, u32 out_ll_address, u32 in_ll_address) {
/* Configure the linked list addresses. */
reg::Write(SE->SE_IN_LL_ADDR, in_ll_address);
reg::Write(SE->SE_OUT_LL_ADDR, out_ll_address);
/* Start the operation. */
StartOperation(SE, op);
/* Ensure the operation is started. */
EnsureOperationStarted(SE);
}
void ValidateAesOperationResult(volatile SecurityEngineRegisters *SE) {
/* Ensure no error occurred. */
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_INT_STATUS, SE_REG_BITS_ENUM(INT_STATUS_ERR_STAT, CLEAR)));
/* Ensure the security engine is idle. */
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_STATUS, SE_REG_BITS_ENUM(STATUS_STATE, IDLE)));
/* Ensure there is no error status. */
AMS_ABORT_UNLESS(reg::Read(SE->SE_ERR_STATUS) == 0);
}
void ValidateAesOperationResult() {
return ValidateAesOperationResult(GetRegisters());
}
}
| 7,212
|
C++
|
.cpp
| 142
| 41.640845
| 150
| 0.642156
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,916
|
se_suspend.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/se/se_suspend.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "se_execute.hpp"
namespace ams::se {
namespace {
constexpr inline size_t SE1ContextSaveOperationCount = 133;
constexpr inline size_t SE2ContextSaveOperationCount = 646;
static_assert(((SE1ContextSaveOperationCount - 2) + 1) * se::AesBlockSize == sizeof(se::Context));
constinit const u8 FixedPattern[AesBlockSize] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
};
bool TestRegister(volatile u32 &r, u16 v) {
return (static_cast<u16>(reg::Read(r))) == v;
}
void ExecuteContextSaveOperation(volatile SecurityEngineRegisters *SE, void *dst, size_t dst_size, const void *src, size_t src_size) {
/* Save the output to a temporary buffer. */
util::AlignedBuffer<hw::DataCacheLineSize, AesBlockSize> temp;
AMS_ABORT_UNLESS(dst_size <= AesBlockSize);
/* Ensure that the cpu and SE see consistent data. */
if (src_size > 0) {
hw::FlushDataCache(src, src_size);
hw::DataSynchronizationBarrierInnerShareable();
}
if (dst_size > 0) {
hw::FlushDataCache(temp, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
}
/* Execute the operation. */
ExecuteOperation(SE, SE_OPERATION_OP_CTX_SAVE, temp, dst_size, src, src_size);
/* Copy output from the operation, if any. */
if (dst_size > 0) {
hw::DataSynchronizationBarrierInnerShareable();
hw::FlushDataCache(temp, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
std::memcpy(dst, temp, dst_size);
}
}
void SaveContextBlock(volatile SecurityEngineRegisters *SE, void *dst) {
/* Configure to encrypt a single block. */
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, 0);
/* Execute the operation. */
ExecuteContextSaveOperation(SE, dst, AesBlockSize, nullptr, 0);
}
void ConfigureForAutomaticContextSave(volatile SecurityEngineRegisters *SE) {
/* Configure the engine to do RNG encryption. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_ENC_ALG, RNG),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DST, MEMORY));
reg::Write(SE->SE_CRYPTO_CONFIG, SE_REG_BITS_ENUM (CRYPTO_CONFIG_MEMIF, AHB),
SE_REG_BITS_VALUE(CRYPTO_CONFIG_CTR_CNTN, 0),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_KEYSCH_BYPASS, DISABLE),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_CORE_SEL, ENCRYPT),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_IV_SELECT, ORIGINAL),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_VCTRAM_SEL, MEMORY),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_INPUT_SEL, RANDOM),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_XOR_POS, BYPASS),
SE_REG_BITS_ENUM (CRYPTO_CONFIG_HASH_ENB, DISABLE));
}
void WaitAutomaticContextSaveDone(volatile SecurityEngineRegisters *SE) {
/* Wait for operation. */
while (!reg::HasValue(SE->SE_INT_STATUS, SE_REG_BITS_ENUM(INT_STATUS_SE_OP_DONE, ACTIVE))) { /* ... */ }
/* Wait for the engine to be idle. */
while (!reg::HasValue(SE->SE_STATUS, SE_REG_BITS_ENUM(STATUS_STATE, IDLE))) { /* ... */ }
/* Wait for the memory interface to be idle. */
while (!reg::HasValue(SE->SE_STATUS, SE_REG_BITS_ENUM(STATUS_MEM_INTERFACE, IDLE))) { /* ... */ }
}
void ValidateErrStatus(volatile SecurityEngineRegisters *SE) {
/* Ensure there is no error status. */
AMS_ABORT_UNLESS(reg::Read(SE->SE_ERR_STATUS) == 0);
/* Ensure no error occurred. */
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_INT_STATUS, SE_REG_BITS_ENUM(INT_STATUS_ERR_STAT, CLEAR)));
}
}
bool ValidateStickyBits(const StickyBits &bits) {
/* Get the registers. */
auto *SE = GetRegisters();
/* Check SE_SECURITY. */
if (!TestRegister(SE->SE_SE_SECURITY, bits.se_security)) { return false; }
/* Check TZRAM_SECURITY. */
if (!TestRegister(SE->SE_TZRAM_SECURITY, bits.tzram_security)) { return false; }
/* Check CRYPTO_SECURITY_PERKEY. */
if (!TestRegister(SE->SE_CRYPTO_SECURITY_PERKEY, bits.crypto_security_perkey)) { return false; }
/* Check CRYPTO_KEYTABLE_ACCESS. */
for (int i = 0; i < AesKeySlotCount; ++i) {
if (!TestRegister(SE->SE_CRYPTO_KEYTABLE_ACCESS[i], bits.crypto_keytable_access[i])) { return false; }
}
/* Test RSA_SECURITY_PERKEY */
if (!TestRegister(SE->SE_RSA_SECURITY_PERKEY, bits.rsa_security_perkey)) { return false; }
/* Check RSA_KEYTABLE_ACCESS. */
for (int i = 0; i < RsaKeySlotCount; ++i) {
if (!TestRegister(SE->SE_RSA_KEYTABLE_ACCESS[i], bits.rsa_keytable_access[i])) { return false; }
}
/* All sticky bits are valid. */
return true;
}
void SaveContext(Context *dst) {
/* Get the registers. */
auto *SE = GetRegisters();
/* Generate a random srk. */
GenerateSrk();
/* Save a randomly-generated block. */
{
util::AlignedBuffer<hw::DataCacheLineSize, AesBlockSize> random_block;
/* Flush the region we're about to fill to ensure consistency with the SE. */
hw::FlushDataCache(random_block, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Generate random bytes. */
GenerateRandomBytes(random_block, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Flush to ensure the CPU sees consistent data for the region. */
hw::FlushDataCache(random_block, AesBlockSize);
hw::DataSynchronizationBarrierInnerShareable();
/* Configure to encrypt the random block to memory. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_DEC_MODE, AESMODE_KEY128),
SE_REG_BITS_ENUM(CONFIG_ENC_ALG, AES_ENC),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DST, MEMORY));
/* Configure to context save using memory as source. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM(CTX_SAVE_CONFIG_SRC, MEM));
/* Configure to encrypt a single block. */
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, 0);
/* Execute the operation. */
ExecuteContextSaveOperation(SE, dst->random, AesBlockSize, random_block, AesBlockSize);
}
/* Save the sticky bits. */
for (size_t i = 0; i < util::size(dst->sticky_bits); ++i) {
/* Configure to encrypt the sticky bits block. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_SRC, STICKY_BITS),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_STICKY_WORD_QUAD, i));
/* Save the block. */
SaveContextBlock(SE, dst->sticky_bits[i]);
}
/* Save the aes keytable. */
{
for (size_t key = 0; key < util::size(dst->aes_key); ++key) {
for (auto part = 0; part < AesKeySlotPartCount; ++part) {
/* Configure to encrypt the part of the key. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_SRC, AES_KEYTABLE),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_AES_KEY_INDEX, key),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_AES_WORD_QUAD, part));
/* Save the block. */
SaveContextBlock(SE, dst->aes_key[key][part]);
}
}
for (size_t key = 0; key < util::size(dst->aes_oiv); ++key) {
/* Configure to encrypt the original iv. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_SRC, AES_KEYTABLE),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_AES_KEY_INDEX, key),
SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_AES_WORD_QUAD, ORIGINAL_IVS));
/* Save the block. */
SaveContextBlock(SE, dst->aes_oiv[key]);
}
for (size_t key = 0; key < util::size(dst->aes_uiv); ++key) {
/* Configure to encrypt the updated iv. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_SRC, AES_KEYTABLE),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_AES_KEY_INDEX, key),
SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_AES_WORD_QUAD, UPDATED_IVS));
/* Save the block. */
SaveContextBlock(SE, dst->aes_uiv[key]);
}
}
/* Save the rsa keytable. */
for (size_t key = 0; key < util::size(dst->rsa_key); ++key) {
for (auto part = 0; part < RsaKeySlotPartCount; ++part) {
/* Note that the parts are done in reverse order. */
const auto part_index = RsaKeySlotPartCount - 1 - part;
/* Determine a total key index. */
const auto key_index = key * util::size(dst->rsa_key) + part_index;
for (size_t block = 0; block < RsaSize / AesBlockSize; ++block) {
/* Configure to encrypt the part of the key. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM (CTX_SAVE_CONFIG_SRC, RSA_KEYTABLE),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_RSA_KEY_INDEX, key_index),
SE_REG_BITS_VALUE(CTX_SAVE_CONFIG_RSA_WORD_QUAD, block));
/* Save the block. */
SaveContextBlock(SE, dst->rsa_key[key][part][block]);
}
}
}
/* Save the fixed pattern. */
{
/* Configure to context save using memory as source. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM(CTX_SAVE_CONFIG_SRC, MEM));
/* Configure to encrypt a single block. */
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, 0);
/* Execute the operation. */
ExecuteContextSaveOperation(SE, dst->fixed_pattern, AesBlockSize, FixedPattern, AesBlockSize);
}
/* Save the srk. */
{
/* Configure to context save using srk as source. */
reg::Write(SE->SE_CTX_SAVE_CONFIG, SE_REG_BITS_ENUM(CTX_SAVE_CONFIG_SRC, SRK));
/* Configure to encrypt a single block. */
reg::Write(SE->SE_CRYPTO_LAST_BLOCK, 0);
/* Execute the operation. */
ExecuteContextSaveOperation(SE, nullptr, 0, nullptr, 0);
}
/* Perform a no-op context save operation. */
{
/* Configure to perform no-op. */
reg::Write(SE->SE_CONFIG, SE_REG_BITS_ENUM(CONFIG_ENC_ALG, NOP),
SE_REG_BITS_ENUM(CONFIG_DEC_ALG, NOP));
/* Execute the operation. */
ExecuteContextSaveOperation(SE, nullptr, 0, nullptr, 0);
}
}
void ConfigureAutomaticContextSave() {
/* Get registers. */
auto *SE = GetRegisters();
auto *SE2 = GetRegisters2();
/* Automatic context save is supported only on mariko. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
/* Configure SE1 to do automatic context save. */
reg::Write(SE->SE_CTX_SAVE_AUTO, SE_REG_BITS_ENUM(CTX_SAVE_AUTO_ENABLE, YES),
SE_REG_BITS_ENUM(CTX_SAVE_AUTO_LOCK, YES));
/* Configure SE2 to do automatic context save. */
reg::Write(SE2->SE_CTX_SAVE_AUTO, SE_REG_BITS_ENUM(CTX_SAVE_AUTO_ENABLE, YES),
SE_REG_BITS_ENUM(CTX_SAVE_AUTO_LOCK, YES));
}
}
void SaveContextAutomatic() {
/* Get registers. */
auto *SE = GetRegisters();
auto *SE2 = GetRegisters2();
/* Ensure there's no error status before or after we save context. */
ValidateErrStatus();
ON_SCOPE_EXIT { ValidateErrStatus(); };
/* Perform atomic context save. */
{
/* Check that context save has not already been performed. */
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_CTX_SAVE_AUTO, SE_REG_BITS_VALUE(CTX_SAVE_AUTO_CURR_CNT, 0)));
AMS_ABORT_UNLESS(reg::HasValue(SE2->SE_CTX_SAVE_AUTO, SE_REG_BITS_VALUE(CTX_SAVE_AUTO_CURR_CNT, 0)));
/* Configure SE1 to do context save. */
ConfigureForAutomaticContextSave(SE);
ConfigureForAutomaticContextSave(SE2);
/* Start the context save operation. */
reg::Write(SE->SE_OPERATION, SE_REG_BITS_ENUM(OPERATION_OP, CTX_SAVE));
reg::Write(SE2->SE_OPERATION, SE_REG_BITS_ENUM(OPERATION_OP, CTX_SAVE));
/* Wait for the context save operation to complete. */
WaitAutomaticContextSaveDone(SE);
WaitAutomaticContextSaveDone(SE2);
/* Check that the correct sizes were written. */
AMS_ABORT_UNLESS(reg::HasValue(SE->SE_CTX_SAVE_AUTO, SE_REG_BITS_VALUE(CTX_SAVE_AUTO_CURR_CNT, SE1ContextSaveOperationCount)));
AMS_ABORT_UNLESS(reg::HasValue(SE2->SE_CTX_SAVE_AUTO, SE_REG_BITS_VALUE(CTX_SAVE_AUTO_CURR_CNT, SE2ContextSaveOperationCount)));
}
}
void SaveTzramAutomatic() {
/* Get registers. */
auto *SE = GetRegisters();
/* Begin save-to-shadow-tzram operation. */
reg::Write(SE->SE_TZRAM_OPERATION, SE_REG_BITS_ENUM(TZRAM_OPERATION_MODE, SAVE),
SE_REG_BITS_ENUM(TZRAM_OPERATION_REQ, INITIATE));
/* Wait for operation to complete. */
while (reg::HasValue(SE->SE_TZRAM_OPERATION, SE_REG_BITS_ENUM(TZRAM_OPERATION_BUSY, YES))) { /* ... */ }
}
void ValidateErrStatus() {
/* Ensure SE has no error status. */
ValidateErrStatus(GetRegisters());
/* If on mariko, ensure SE2 has no error status. */
if (fuse::GetSocType() == fuse::SocType_Mariko) {
ValidateErrStatus(GetRegisters2());
}
}
}
| 16,267
|
C++
|
.cpp
| 280
| 43.210714
| 142
| 0.547163
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,917
|
log_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/log/log_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::log {
namespace {
constexpr inline uart::Port DefaultLogPort = uart::Port_ReservedDebug;
constexpr inline u32 DefaultLogFlags = static_cast<u32>(uart::Flag_None);
constexpr inline int DefaultBaudRate = 115200;
constinit uart::Port g_log_port = DefaultLogPort;
constinit bool g_initialized_uart = false;
ALWAYS_INLINE void SetupUartClock(uart::Port port) {
/* The debug port must always be set up, for compatibility with official hos. */
pinmux::SetupUartA();
clkrst::EnableUartAClock();
/* If logging to a joy-con port, configure appropriately. */
if (port == uart::Port_LeftJoyCon) {
/* Logging to left joy-con (e.g. with Joyless). */
static_assert(uart::Port_LeftJoyCon == uart::Port_C);
pinmux::SetupUartC();
clkrst::EnableUartCClock();
} else if (port == uart::Port_RightJoyCon) {
/* Logging to right joy-con (e.g. with Joyless). */
static_assert(uart::Port_RightJoyCon == uart::Port_B);
pinmux::SetupUartB();
clkrst::EnableUartBClock();
}
}
}
void Initialize() {
return Initialize(DefaultLogPort, DefaultBaudRate, DefaultLogFlags);
}
void Initialize(uart::Port port, u32 baud_rate, u32 flags) {
/* Initialize pinmux and clock for the target uart port. */
SetupUartClock(port);
/* Initialize the target uart port. */
uart::Initialize(port, baud_rate, flags);
/* Note that we've initialized. */
g_log_port = port;
g_initialized_uart = true;
}
void Finalize() {
g_initialized_uart = false;
}
NOINLINE void VPrintf(const char *fmt, ::std::va_list vl) {
/* TODO: What's a good size for the log buffer? Nintendo uses 0x100, but this seems big. */
char log_buf[0x80];
const auto len = util::TVSNPrintf(log_buf, sizeof(log_buf), fmt, vl);
if (g_initialized_uart) {
uart::SendText(g_log_port, log_buf, len);
}
}
NOINLINE void Printf(const char *fmt, ...) {
::std::va_list vl;
va_start(vl, fmt);
VPrintf(fmt, vl);
va_end(vl);
}
NOINLINE void Dump(const void *src, size_t size) {
const u8 *src_u8 = static_cast<const u8 *>(src);
for (size_t i = 0; i < size; ++i) {
if ((i % 0x20) == 0x00) {
Printf("%03zx| ", i);
}
Printf("%02x ", src_u8[i]);
if ((i % 0x20) == 0x1F) {
Printf("\n");
}
}
if ((size % 0x20) != 0) {
Printf("\n");
}
}
void SendText(const void *text, size_t size) {
if (g_initialized_uart) {
uart::SendText(g_log_port, text, size);
}
}
void Flush() {
if (g_initialized_uart) {
uart::WaitFlush(g_log_port);
}
}
}
| 3,720
|
C++
|
.cpp
| 96
| 30.135417
| 99
| 0.582408
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,918
|
pmc_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/pmc/pmc_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::pmc {
namespace {
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDevicePmc.GetAddress();
constexpr inline u32 WriteMask = 0x1;
constexpr inline u32 ReadMask = 0x2;
enum class LockMode {
Read,
Write,
ReadWrite,
};
template<LockMode Mode>
constexpr inline u32 LockMask = [] {
switch (Mode) {
case LockMode::Read: return ReadMask;
case LockMode::Write: return WriteMask;
case LockMode::ReadWrite: return ReadMask | WriteMask;
default: __builtin_unreachable();
}
}();
constexpr inline size_t NumSecureScratchRegisters = 120;
constexpr inline size_t NumSecureDisableRegisters = 8;
template<size_t SecureScratch> requires (SecureScratch < NumSecureScratchRegisters)
constexpr inline std::pair<size_t, size_t> DisableRegisterIndex = [] {
if constexpr (SecureScratch < 8) {
return std::pair<size_t, size_t>{0, 4 + 2 * SecureScratch};
} else {
constexpr size_t Relative = SecureScratch - 8;
return std::pair<size_t, size_t>{1 + (Relative / 16), 2 * (Relative % 16)};
}
}();
struct LockInfo {
size_t scratch;
LockMode mode;
};
template<LockInfo Info>
constexpr ALWAYS_INLINE void SetSecureScratchMask(std::array<u32, NumSecureDisableRegisters> &disables) {
constexpr std::pair<size_t, size_t> Location = DisableRegisterIndex<Info.scratch>;
disables[Location.first] |= LockMask<Info.mode> << Location.second;
}
template<LockInfo... Info>
constexpr ALWAYS_INLINE void SetSecureScratchMasks(std::array<u32, NumSecureDisableRegisters> &disables) {
(SetSecureScratchMask<Info>(disables), ...);
}
template<size_t... Ix>
constexpr ALWAYS_INLINE void SetSecureScratchReadWriteMasks(std::array<u32, NumSecureDisableRegisters> &disables) {
(SetSecureScratchMask<LockInfo{Ix, LockMode::ReadWrite}>(disables), ...);
}
template<size_t... Ix>
constexpr ALWAYS_INLINE void SetSecureScratchReadMasks(std::array<u32, NumSecureDisableRegisters> &disables) {
(SetSecureScratchMask<LockInfo{Ix, LockMode::Read}>(disables), ...);
}
template<size_t... Ix>
constexpr ALWAYS_INLINE void SetSecureScratchWriteMasks(std::array<u32, NumSecureDisableRegisters> &disables) {
(SetSecureScratchMask<LockInfo{Ix, LockMode::Write}>(disables), ...);
}
template<SecureRegister Register>
constexpr ALWAYS_INLINE std::array<u32, NumSecureDisableRegisters> GetSecureScratchMasks() {
std::array<u32, NumSecureDisableRegisters> disables = {};
if constexpr ((Register & SecureRegister_Other) != 0) {
constexpr std::array<u32, NumSecureDisableRegisters> NonOtherDisables = GetSecureScratchMasks<static_cast<SecureRegister>(~SecureRegister_Other)>();
for (size_t i = 0; i < NumSecureDisableRegisters; i++) {
disables[i] |= ~NonOtherDisables[i];
}
disables[0] &= 0x007FFFF0;
}
if constexpr ((Register & SecureRegister_DramParameters) != 0) {
SetSecureScratchReadWriteMasks< 8, 9, 10, 11, 12, 13, 14, 15,
17, 18, 19, 20,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
52, 53, 54,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
79, 80, 81, 82, 83, 84,
86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
104, 105, 106, 107
>(disables);
}
if constexpr ((Register & SecureRegister_ResetVector) != 0) {
SetSecureScratchReadWriteMasks<34, 35>(disables);
}
if constexpr ((Register & SecureRegister_Carveout) != 0) {
SetSecureScratchReadWriteMasks<16, 39, 51, 55, 74, 75, 76, 77, 78, 99, 100, 101, 102, 103>(disables);
}
if constexpr ((Register & SecureRegister_CmacWrite) != 0) {
SetSecureScratchWriteMasks<112, 113, 114, 115>(disables);
}
if constexpr ((Register & SecureRegister_CmacRead) != 0) {
SetSecureScratchReadMasks<112, 113, 114, 115>(disables);
}
if constexpr ((Register & SecureRegister_KeySourceWrite) != 0) {
SetSecureScratchWriteMasks<24, 25, 26, 27>(disables);
}
if constexpr ((Register & SecureRegister_KeySourceRead) != 0) {
SetSecureScratchReadMasks<24, 25, 26, 27>(disables);
}
if constexpr ((Register & SecureRegister_Srk) != 0) {
SetSecureScratchReadWriteMasks<4, 5, 6, 7>(disables);
}
return disables;
}
/* Validate that the secure scratch masks produced are correct. */
#include "pmc_secure_scratch_test.inc"
ALWAYS_INLINE void LockBits(uintptr_t address, u32 mask) {
reg::Write(address, reg::Read(address) | mask);
}
template<SecureRegister Register>
ALWAYS_INLINE void SetSecureScratchMasks(uintptr_t address) {
constexpr auto Masks = GetSecureScratchMasks<Register>();
if constexpr (Masks[0] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE , Masks[0]); }
if constexpr (Masks[1] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE2, Masks[1]); }
if constexpr (Masks[2] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE3, Masks[2]); }
if constexpr (Masks[3] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE4, Masks[3]); }
if constexpr (Masks[4] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE5, Masks[4]); }
if constexpr (Masks[5] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE6, Masks[5]); }
if constexpr (Masks[6] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE7, Masks[6]); }
if constexpr (Masks[7] != 0) { LockBits(address + APBDEV_PMC_SEC_DISABLE8, Masks[7]); }
static_assert(Masks.size() == 8);
}
template<SecureRegister Register>
ALWAYS_INLINE bool TestSecureScratchMasks(uintptr_t address) {
constexpr auto Masks = GetSecureScratchMasks<Register>();
if constexpr (Masks[0] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE ) & Masks[0]) != Masks[0]) { return false; } }
if constexpr (Masks[1] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE2) & Masks[1]) != Masks[1]) { return false; } }
if constexpr (Masks[2] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE3) & Masks[2]) != Masks[2]) { return false; } }
if constexpr (Masks[3] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE4) & Masks[3]) != Masks[3]) { return false; } }
if constexpr (Masks[4] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE5) & Masks[4]) != Masks[4]) { return false; } }
if constexpr (Masks[5] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE6) & Masks[5]) != Masks[5]) { return false; } }
if constexpr (Masks[6] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE7) & Masks[6]) != Masks[6]) { return false; } }
if constexpr (Masks[7] != 0) { if ((reg::Read(address + APBDEV_PMC_SEC_DISABLE8) & Masks[7]) != Masks[7]) { return false; } }
static_assert(Masks.size() == 8);
return true;
}
NOINLINE void WriteRandomValueToRegister(uintptr_t offset) {
/* Create an aligned buffer. */
util::AlignedBuffer<hw::DataCacheLineSize, sizeof(u32)> buf;
/* Generate random bytes into it. */
se::GenerateRandomBytes(buf, sizeof(u32));
/* Read the random value. */
const u32 random = *reinterpret_cast<const u32 *>(static_cast<u8 *>(buf));
/* Get the address. */
const uintptr_t address = g_register_address + offset;
/* Write the value. */
reg::Write(address, random);
/* Verify it was written. */
AMS_ABORT_UNLESS(reg::Read(address) == random);
}
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
void InitializeRandomScratch() {
/* Write random data to the scratch that contains the SRK. */
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH4);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH5);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH6);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH7);
/* Lock the SRK scratch. */
LockSecureRegister(SecureRegister_Srk);
/* Write random data to the scratch used for tzram cmac. */
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH112);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH113);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH114);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH115);
/* Write random data to the scratch used for tzram key source. */
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH24);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH25);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH26);
WriteRandomValueToRegister(APBDEV_PMC_SECURE_SCRATCH27);
/* Here, Nintendo locks the SRK scratch a second time. */
/* This may just be "to be sure". */
LockSecureRegister(SecureRegister_Srk);
}
void EnableWakeEventDetection() {
/* Get the address. */
const uintptr_t address = g_register_address;
/* Wait 75us, then enable event detection, then wait another 75us. */
util::WaitMicroSeconds(75);
reg::ReadWrite(address + APBDEV_PMC_CNTRL2, PMC_REG_BITS_ENUM(CNTRL2_WAKE_DET_EN, ENABLE));
util::WaitMicroSeconds(75);
/* Enable all wake events. */
reg::Write(address + APBDEV_PMC_WAKE_STATUS, 0xFFFFFFFFu);
reg::Write(address + APBDEV_PMC_WAKE2_STATUS, 0xFFFFFFFFu);
util::WaitMicroSeconds(75);
}
void ConfigureForSc7Entry() {
/* Get the address. */
const uintptr_t address = g_register_address;
/* Configure the bootrom to perform a warmboot. */
reg::Write(address + APBDEV_PMC_SCRATCH0, 0x1);
/* Enable the TSC multiplier. */
reg::ReadWrite(address + APBDEV_PMC_DPD_ENABLE, PMC_REG_BITS_ENUM(DPD_ENABLE_TSC_MULT_EN, ENABLE));
}
void LockSecureRegister(SecureRegister reg) {
/* Get the address. */
const uintptr_t address = g_register_address;
/* Apply each mask. */
#define PMC_PROCESS_REG(REG) do { if ((reg & SecureRegister_##REG) != 0) { SetSecureScratchMasks<SecureRegister_##REG>(address); } } while (0)
PMC_PROCESS_REG(Other);
PMC_PROCESS_REG(DramParameters);
PMC_PROCESS_REG(ResetVector);
PMC_PROCESS_REG(Carveout);
PMC_PROCESS_REG(CmacWrite);
PMC_PROCESS_REG(CmacRead);
PMC_PROCESS_REG(KeySourceWrite);
PMC_PROCESS_REG(KeySourceRead);
PMC_PROCESS_REG(Srk);
#undef PMC_PROCESS_REG
}
LockState GetSecureRegisterLockState(SecureRegister reg) {
bool all_valid = true;
bool any_valid = false;
/* Get the address. */
const uintptr_t address = g_register_address;
/* Test each mask. */
#define PMC_PROCESS_REG(REG) do { if ((reg & SecureRegister_##REG) != 0) { const bool test = TestSecureScratchMasks<SecureRegister_##REG>(address); all_valid &= test; any_valid |= test; } } while (0)
PMC_PROCESS_REG(Other);
PMC_PROCESS_REG(DramParameters);
PMC_PROCESS_REG(ResetVector);
PMC_PROCESS_REG(Carveout);
PMC_PROCESS_REG(CmacWrite);
PMC_PROCESS_REG(CmacRead);
PMC_PROCESS_REG(KeySourceWrite);
PMC_PROCESS_REG(KeySourceRead);
PMC_PROCESS_REG(Srk);
#undef PMC_PROCESS_REG
if (all_valid) {
return LockState::Locked;
} else if (any_valid) {
return LockState::PartiallyLocked;
} else {
return LockState::NotLocked;
}
}
}
| 13,545
|
C++
|
.cpp
| 249
| 42.835341
| 207
| 0.600831
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,919
|
i2c_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/i2c/i2c_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::i2c {
namespace {
constexpr inline size_t MaxTransferSize = sizeof(u32);
constinit std::array<uintptr_t, Port_Count> g_register_addresses = [] {
std::array<uintptr_t, Port_Count> arr = {};
arr[Port_1] = secmon::MemoryRegionPhysicalDeviceI2c1.GetAddress();
arr[Port_5] = secmon::MemoryRegionPhysicalDeviceI2c5.GetAddress();
return arr;
}();
void LoadConfig(uintptr_t address) {
/* Configure for TIMEOUT and MSTR config load. */
/* NOTE: Nintendo writes value 1 to reserved bit 5 here. This bit is documented as having no meaning. */
/* We will reproduce the write just in case it is undocumented. */
reg::Write(address + I2C_CONFIG_LOAD, I2C_REG_BITS_VALUE(CONFIG_LOAD_RESERVED_BIT_5, 1),
I2C_REG_BITS_ENUM (CONFIG_LOAD_TIMEOUT_CONFIG_LOAD, ENABLE),
I2C_REG_BITS_ENUM (CONFIG_LOAD_SLV_CONFIG_LOAD, DISABLE),
I2C_REG_BITS_ENUM (CONFIG_LOAD_MSTR_CONFIG_LOAD, ENABLE));
/* Wait up to 20 microseconds for the master config to be loaded. */
for (int i = 0; i < 20; ++i) {
if (reg::HasValue(address + I2C_CONFIG_LOAD, I2C_REG_BITS_ENUM(CONFIG_LOAD_MSTR_CONFIG_LOAD, DISABLE))) {
return;
}
util::WaitMicroSeconds(1);
}
}
void ClearBus(uintptr_t address) {
/* Configure the bus clear register. */
reg::Write(address + I2C_BUS_CLEAR_CONFIG, I2C_REG_BITS_VALUE(BUS_CLEAR_CONFIG_BC_SCLK_THRESHOLD, 9),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_STOP_COND, NO_STOP),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_TERMINATE, IMMEDIATE),
I2C_REG_BITS_ENUM (BUS_CLEAR_CONFIG_BC_ENABLE, ENABLE));
/* Load the config. */
LoadConfig(address);
/* Wait up to 250us (in 25 us increments) until the bus clear is done. */
for (int i = 0; i < 10; ++i) {
if (reg::HasValue(address + I2C_INTERRUPT_STATUS_REGISTER, I2C_REG_BITS_ENUM(INTERRUPT_STATUS_REGISTER_BUS_CLEAR_DONE, SET))) {
break;
}
util::WaitMicroSeconds(25);
}
/* Read the bus clear status. */
reg::Read(address + I2C_BUS_CLEAR_STATUS);
}
void InitializePort(uintptr_t address) {
/* Calculate the divisor. */
constexpr int Divisor = util::DivideUp(19200, 8 * 400);
/* Set the divisor. */
reg::Write(address + I2C_CLK_DIVISOR_REGISTER, I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_STD_FAST_MODE, Divisor - 1),
I2C_REG_BITS_VALUE(CLK_DIVISOR_REGISTER_HSMODE, 1));
/* Clear the bus. */
ClearBus(address);
/* Clear the status. */
reg::Write(address + I2C_INTERRUPT_STATUS_REGISTER, reg::Read(address + I2C_INTERRUPT_STATUS_REGISTER));
}
bool Write(uintptr_t base_address, Port port, int address, const void *src, size_t src_size, bool unused) {
AMS_UNUSED(port, unused);
/* Ensure we don't write too much. */
u32 data = 0;
if (src_size > MaxTransferSize) {
return false;
}
/* Copy the data to a transfer word. */
std::memcpy(std::addressof(data), src, src_size);
/* Configure the to write the 7-bit address. */
reg::Write(base_address + I2C_I2C_CMD_ADDR0, I2C_REG_BITS_VALUE(I2C_CMD_ADDR0_7BIT_ADDR, address),
I2C_REG_BITS_ENUM (I2C_CMD_ADDR0_7BIT_RW, WRITE));
/* Configure to write the data. */
reg::Write(base_address + I2C_I2C_CMD_DATA1, data);
/* Configure to write the correct amount of data. */
reg::Write(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM (I2C_CNFG_DEBOUNCE_CNT, DEBOUNCE_4T),
I2C_REG_BITS_ENUM (I2C_CNFG_NEW_MASTER_FSM, ENABLE),
I2C_REG_BITS_ENUM (I2C_CNFG_CMD1, WRITE),
I2C_REG_BITS_VALUE(I2C_CNFG_LENGTH, src_size - 1));
/* Load the configuration. */
LoadConfig(base_address);
/* Start the command. */
reg::ReadWrite(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM(I2C_CNFG_SEND, GO));
/* Wait for the command to be done. */
while (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_BUSY, NOT_BUSY))) { /* ... */ }
/* Check if the transfer was successful. */
return reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_CMD1_STAT, SL1_XFER_SUCCESSFUL));
}
bool Read(uintptr_t base_address, Port port, void *dst, size_t dst_size, int address, bool unused) {
AMS_UNUSED(port, unused);
/* Ensure we don't read too much. */
if (dst_size > MaxTransferSize) {
return false;
}
/* Configure the to read the 7-bit address. */
reg::Write(base_address + I2C_I2C_CMD_ADDR0, I2C_REG_BITS_VALUE(I2C_CMD_ADDR0_7BIT_ADDR, address),
I2C_REG_BITS_ENUM (I2C_CMD_ADDR0_7BIT_RW, READ));
/* Configure to read the correct amount of data. */
reg::Write(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM (I2C_CNFG_DEBOUNCE_CNT, DEBOUNCE_4T),
I2C_REG_BITS_ENUM (I2C_CNFG_NEW_MASTER_FSM, ENABLE),
I2C_REG_BITS_ENUM (I2C_CNFG_CMD1, READ),
I2C_REG_BITS_VALUE(I2C_CNFG_LENGTH, dst_size - 1));
/* Load the configuration. */
LoadConfig(base_address);
/* Start the command. */
reg::ReadWrite(base_address + I2C_I2C_CNFG, I2C_REG_BITS_ENUM(I2C_CNFG_SEND, GO));
/* Wait for the command to be done. */
while (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_BUSY, NOT_BUSY))) { /* ... */ }
/* Check that the transfer was successful. */
if (!reg::HasValue(base_address + I2C_I2C_STATUS, I2C_REG_BITS_ENUM(I2C_STATUS_CMD1_STAT, SL1_XFER_SUCCESSFUL))) {
return false;
}
/* Read and copy out the data. */
u32 data = reg::Read(base_address + I2C_I2C_CMD_DATA1);
std::memcpy(dst, std::addressof(data), dst_size);
return true;
}
}
void SetRegisterAddress(Port port, uintptr_t address) {
g_register_addresses[port] = address;
}
void Initialize(Port port) {
InitializePort(g_register_addresses[port]);
}
bool Query(void *dst, size_t dst_size, Port port, int address, int r) {
const uintptr_t base_address = g_register_addresses[port];
/* Select the register we want to read. */
bool success = Write(base_address, port, address, std::addressof(r), 1, false);
if (success) {
/* If we successfully selected, read data from the register. */
success = Read(base_address, port, dst, dst_size, address, true);
}
return success;
}
bool Send(Port port, int address, int r, const void *src, size_t src_size) {
const uintptr_t base_address = g_register_addresses[port];
/* Create a transfer buffer, make sure we can use it. */
u8 buffer[MaxTransferSize];
if (src_size > sizeof(buffer) - 1) {
return false;
}
/* Copy data into the buffer. */
buffer[0] = static_cast<u8>(r);
std::memcpy(buffer + 1, src, src_size);
return Write(base_address, port, address, buffer, src_size + 1, false);
}
}
| 9,131
|
C++
|
.cpp
| 157
| 43.133758
| 143
| 0.546157
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,920
|
actmon_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/actmon/actmon_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "actmon_registers.hpp"
namespace ams::actmon {
namespace {
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceActivityMonitor.GetAddress();
constinit InterruptHandler g_interrupt_handler = nullptr;
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
void HandleInterrupt() {
/* Get the registers. */
const uintptr_t ACTMON = g_register_address;
/* Disable the actmon interrupt. */
reg::Write(ACTMON + ACTMON_COP_CTRL, ACTMON_REG_BITS_ENUM(COP_CTRL_ENB, DISABLE));
/* Update the interrupt status. */
reg::Write(ACTMON + ACTMON_COP_INTR_STATUS, reg::Read(ACTMON + ACTMON_COP_INTR_STATUS));
/* Invoke the handler. */
if (g_interrupt_handler != nullptr) {
g_interrupt_handler();
g_interrupt_handler = nullptr;
}
}
void StartMonitoringBpmp(InterruptHandler handler) {
/* Get the registers. */
const uintptr_t ACTMON = g_register_address;
/* Configure the activity monitor to poll once per microsecond. */
reg::Write(ACTMON + ACTMON_GLB_PERIOD_CTRL, ACTMON_REG_BITS_ENUM (GLB_PERIOD_CTRL_SOURCE, USEC),
ACTMON_REG_BITS_VALUE(GLB_PERIOD_CTRL_SAMPLE_PERIOD, 0));
/* Configure the activity monitor to generate an interrupt the first time the event occurs. */
reg::Write(ACTMON + ACTMON_COP_UPPER_WMARK, 0);
/* Set the interrupt handler. */
g_interrupt_handler = handler;
/* Configure the activity monitor to generate events whenever the bpmp is woken up. */
reg::Write(ACTMON + ACTMON_COP_CTRL, ACTMON_REG_BITS_ENUM (COP_CTRL_ENB, ENABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_CONSECUTIVE_ABOVE_WMARK_EN, ENABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_CONSECUTIVE_BELOW_WMARK_EN, DISABLE),
ACTMON_REG_BITS_VALUE(COP_CTRL_ABOVE_WMARK_NUM, 0),
ACTMON_REG_BITS_VALUE(COP_CTRL_BELOW_WMARK_NUM, 0),
ACTMON_REG_BITS_ENUM (COP_CTRL_WHEN_OVERFLOW_EN, DISABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_AVG_ABOVE_WMARK_EN, DISABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_AVG_BELOW_WMARK_EN, DISABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_AT_END_EN, DISABLE),
ACTMON_REG_BITS_ENUM (COP_CTRL_ENB_PERIODIC, ENABLE));
/* Read the activity monitor control register to make sure our configuration takes. */
reg::Read(ACTMON + ACTMON_COP_CTRL);
}
void StopMonitoringBpmp() {
/* Get the registers. */
const uintptr_t ACTMON = g_register_address;
/* Disable the actmon interrupt. */
reg::Write(ACTMON + ACTMON_COP_CTRL, ACTMON_REG_BITS_ENUM(COP_CTRL_ENB, DISABLE));
/* Update the interrupt status. */
reg::Write(ACTMON + ACTMON_COP_INTR_STATUS, reg::Read(ACTMON + ACTMON_COP_INTR_STATUS));
/* Clear the interrupt handler. */
g_interrupt_handler = nullptr;
}
}
| 4,131
|
C++
|
.cpp
| 73
| 44.479452
| 114
| 0.594601
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,921
|
tsec_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/tsec/tsec_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
#include "tsec_registers.hpp"
#include "../kfuse/kfuse_registers.hpp"
namespace ams::tsec {
namespace {
constexpr inline const uintptr_t KFUSE = 0x7000FC00;
constexpr inline const uintptr_t TSEC = 0x54500000;
enum TsecResult : u32 {
TsecResult_Success = 0xB0B0B0B0,
TsecResult_Failure = 0xD0D0D0D0,
};
enum TsecMemory {
TsecMemory_Imem,
TsecMemory_Dmem,
};
bool WaitForKfuseReady() {
constexpr auto KfuseTimeout = 10 * 1000; /* 10 ms. */
const u32 end_time = util::GetMicroSeconds() + KfuseTimeout;
/* Wait for STATE_DONE. */
while (!reg::HasValue(KFUSE + KFUSE_STATE, KFUSE_REG_BITS_ENUM(STATE_DONE, DONE))) {
if (util::GetMicroSeconds() >= end_time) {
return false;
}
}
/* Check for STATE_CRCPASS. */
return reg::HasValue(KFUSE + KFUSE_STATE, KFUSE_REG_BITS_ENUM(STATE_CRCPASS, PASS));
}
void WaitForDmaIdle() {
constexpr auto DmaTimeout = 10 * 1000 * 1000; /* 10 Seconds. */
u32 cur_time = util::GetMicroSeconds();
const u32 end_time = cur_time + DmaTimeout;
while (cur_time <= end_time) {
if (reg::HasValue(TSEC + TSEC_FALCON_DMATRFCMD, TSEC_REG_BITS_ENUM(FALCON_DMATRFCMD_BUSY, IDLE))) {
return;
}
cur_time = util::GetMicroSeconds();
}
AMS_ABORT("tsec dma timeout");
}
void WaitForTsecIdle() {
constexpr auto TsecTimeout = 2 * 1000 * 1000; /* 2 Seconds. */
u32 cur_time = util::GetMicroSeconds();
const u32 end_time = cur_time + TsecTimeout;
while (cur_time <= end_time) {
if (reg::HasValue(TSEC + TSEC_FALCON_CPUCTL, TSEC_REG_BITS_ENUM(FALCON_CPUCTL_HALTED, TRUE))) {
return;
}
cur_time = util::GetMicroSeconds();
}
AMS_ABORT("tsec timeout");
}
void DoDma256(TsecMemory memory, u32 dst_offset, u32 src_offset) {
reg::Write(TSEC + TSEC_FALCON_DMATRFMOFFS, TSEC_REG_BITS_VALUE(FALCON_DMATRFMOFFS_OFFSET, dst_offset));
reg::Write(TSEC + TSEC_FALCON_DMATRFFBOFFS, src_offset);
if (memory == TsecMemory_Imem) {
reg::Write(TSEC + TSEC_FALCON_DMATRFCMD, TSEC_REG_BITS_ENUM(FALCON_DMATRFCMD_TO, IMEM),
TSEC_REG_BITS_ENUM(FALCON_DMATRFCMD_SIZE, 4B));
} else {
reg::Write(TSEC + TSEC_FALCON_DMATRFCMD, TSEC_REG_BITS_ENUM(FALCON_DMATRFCMD_TO, DMEM),
TSEC_REG_BITS_ENUM(FALCON_DMATRFCMD_SIZE, 256B));
}
WaitForDmaIdle();
}
}
bool RunTsecFirmware(const void *fw, size_t fw_size) {
/* Enable relevant clocks. */
clkrst::EnableHost1xClock();
clkrst::EnableTsecClock();
clkrst::EnableSorSafeClock();
clkrst::EnableSor0Clock();
clkrst::EnableSor1Clock();
clkrst::EnableKfuseClock();
/* Disable clocks once we're done. */
ON_SCOPE_EXIT {
clkrst::DisableHost1xClock();
clkrst::DisableTsecClock();
clkrst::DisableSorSafeClock();
clkrst::DisableSor0Clock();
clkrst::DisableSor1Clock();
clkrst::DisableKfuseClock();
};
/* Wait for kfuse to be ready. */
if (!WaitForKfuseReady()) {
return false;
}
/* Configure falcon. */
reg::Write(TSEC + TSEC_FALCON_DMACTL, 0);
reg::Write(TSEC + TSEC_FALCON_IRQMSET, 0xFFF2);
reg::Write(TSEC + TSEC_FALCON_IRQDEST, 0xFFF0);
reg::Write(TSEC + TSEC_FALCON_ITFEN, 0x3);
/* Wait for TSEC dma to be idle. */
WaitForDmaIdle();
/* Set the base address for transfers. */
reg::Write(TSEC + TSEC_FALCON_DMATRFBASE, reinterpret_cast<uintptr_t>(fw) >> 8);
/* Transfer all data to TSEC imem. */
for (size_t i = 0; i < fw_size; i += 0x100) {
DoDma256(TsecMemory_Imem, i, i);
}
/* Write the magic value to host1x syncpoint 160. */
reg::Write(0x50003300, 0x34C2E1DA);
/* Execute the firmware. */
reg::Write(TSEC + TSEC_FALCON_MAILBOX0, 0);
reg::Write(TSEC + TSEC_FALCON_MAILBOX1, 0);
reg::Write(TSEC + TSEC_FALCON_BOOTVEC, 0);
reg::Write(TSEC + TSEC_FALCON_CPUCTL, TSEC_REG_BITS_ENUM(FALCON_CPUCTL_STARTCPU, TRUE));
/* Wait for TSEC dma to be idle. */
WaitForDmaIdle();
/* Wait for TSEC to complete. */
WaitForTsecIdle();
/* Clear magic value from host1x syncpoint 160. */
reg::Write(0x50003300, 0);
/* Return whether the tsec firmware succeeded. */
return reg::Read(TSEC + TSEC_FALCON_MAILBOX1) == TsecResult_Success;
}
void Lock() {
/* Set the tsec host1x syncpoint (160) to be secure. */
/* TODO: constexpr value. */
reg::ReadWrite(0x500038F8, REG_BITS_VALUE(0, 1, 0));
/* Clear the tsec host1x syncpoint. */
reg::Write(0x50003300, 0);
}
}
| 6,027
|
C++
|
.cpp
| 137
| 33.313869
| 115
| 0.577922
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,922
|
flow_api.cpp
|
Atmosphere-NX_Atmosphere/libraries/libexosphere/source/flow/flow_api.cpp
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <exosphere.hpp>
namespace ams::flow {
namespace {
struct FlowControllerRegisterOffset {
u16 cpu_csr;
u16 halt_cpu_events;
u16 cc4_core_ctrl;
};
constinit uintptr_t g_register_address = secmon::MemoryRegionPhysicalDeviceFlowController.GetAddress();
constexpr const FlowControllerRegisterOffset FlowControllerRegisterOffsets[] = {
{ FLOW_CTLR_CPU0_CSR, FLOW_CTLR_HALT_CPU0_EVENTS, FLOW_CTLR_CC4_CORE0_CTRL, },
{ FLOW_CTLR_CPU1_CSR, FLOW_CTLR_HALT_CPU1_EVENTS, FLOW_CTLR_CC4_CORE1_CTRL, },
{ FLOW_CTLR_CPU2_CSR, FLOW_CTLR_HALT_CPU2_EVENTS, FLOW_CTLR_CC4_CORE2_CTRL, },
{ FLOW_CTLR_CPU3_CSR, FLOW_CTLR_HALT_CPU3_EVENTS, FLOW_CTLR_CC4_CORE3_CTRL, },
};
constexpr u32 GetHaltCpuEventsValue(bool resume_on_irq) {
if (resume_on_irq) {
return reg::Encode(FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_FLOW_MODE, WAITEVENT),
FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_LIC_IRQN, ENABLE),
FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_LIC_FIQN, ENABLE),
FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_GIC_IRQN, ENABLE),
FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_GIC_FIQN, ENABLE));
} else {
return reg::Encode(FLOW_REG_BITS_ENUM(HALT_CPUN_EVENTS_FLOW_MODE, WAITEVENT));
}
}
}
void SetRegisterAddress(uintptr_t address) {
g_register_address = address;
}
void ResetCpuRegisters(int core) {
AMS_ASSUME(core >= 0);
const auto &offsets = FlowControllerRegisterOffsets[core];
reg::Write(g_register_address + offsets.cpu_csr, 0);
reg::Write(g_register_address + offsets.halt_cpu_events, 0);
}
void SetCpuCsr(int core, u32 enable_ext) {
reg::Write(g_register_address + FlowControllerRegisterOffsets[core].cpu_csr, FLOW_REG_BITS_ENUM (CPUN_CSR_INTR_FLAG, TRUE),
FLOW_REG_BITS_ENUM (CPUN_CSR_EVENT_FLAG, TRUE),
FLOW_REG_BITS_VALUE(CPUN_CSR_ENABLE_EXT, enable_ext),
FLOW_REG_BITS_VALUE(CPUN_CSR_WAIT_WFI_BITMAP, (1u << core)),
FLOW_REG_BITS_ENUM (CPUN_CSR_ENABLE, ENABLE));
}
void SetHaltCpuEvents(int core, bool resume_on_irq) {
reg::Write(g_register_address + FlowControllerRegisterOffsets[core].halt_cpu_events, GetHaltCpuEventsValue(resume_on_irq));
}
void SetCc4Ctrl(int core, u32 value) {
reg::Write(g_register_address + FlowControllerRegisterOffsets[core].cc4_core_ctrl, value);
}
void ClearL2FlushControl() {
reg::Write(g_register_address + FLOW_CTLR_L2FLUSH_CONTROL, 0);
}
}
| 3,765
|
C++
|
.cpp
| 68
| 41.941176
| 146
| 0.586638
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.