protected override Result DoOpenFile(out IFile file, U8Span path, OpenMode mode) { UnsafeHelpers.SkipParamInit(out file); Result rc = ResolveFullPath(out string fullPath, path, true); if (rc.IsFailure()) { return(rc); } rc = GetEntryType(out DirectoryEntryType entryType, path); if (rc.IsFailure()) { return(rc); } if (entryType == DirectoryEntryType.Directory) { return(ResultFs.PathNotFound.Log()); } FileStream fileStream = null; rc = TargetLockedAvoidance.RetryToAvoidTargetLocked(() => OpenFileInternal(out fileStream, fullPath, mode), _fsClient); if (rc.IsFailure()) { return(rc); } file = new LocalFile(fileStream, mode); return(Result.Success); }
public static Result GetAndClearPatrolReadAllocateBufferCount(this StorageService service, out long successCount, out long failureCount) { UnsafeHelpers.SkipParamInit(out successCount, out failureCount); ReferenceCountedDisposable <IStorageDeviceOperator> mmcOperator = null; try { Result rc = service.GetMmcManagerOperator(out mmcOperator); if (rc.IsFailure()) { return(rc); } int operationId = MakeOperationId(MmcManagerOperationIdValue.GetAndClearPatrolReadAllocateBufferCount); OutBuffer successCountBuffer = OutBuffer.FromStruct(ref successCount); OutBuffer failureCountBuffer = OutBuffer.FromStruct(ref failureCount); return(mmcOperator.Target.OperateOut2(out _, successCountBuffer, out _, failureCountBuffer, operationId)); } finally { mmcOperator?.Dispose(); } }
public Result ReadEntryCount(out int count) { UnsafeHelpers.SkipParamInit(out count); // This should only be called at the start of reading stream. Assert.SdkRequiresEqual(_offset, 0); // Read and validate header. var header = new KeyValueArchiveHeader(); Result rc = Read(SpanHelpers.AsByteSpan(ref header)); if (rc.IsFailure()) { return(rc); } if (!header.IsValid()) { return(ResultKvdb.InvalidKeyValue.Log()); } count = header.EntryCount; return(Result.Success); }
private static int ConvertCharacterUtf16ToUtf32(out uint outUtf32, ushort codeUnit1, ushort codeUnit2) { UnsafeHelpers.SkipParamInit(out outUtf32); // If the first code unit isn't a surrogate, simply copy it to the output if ((codeUnit1 & 0xF800) != 0xD800) { outUtf32 = codeUnit1; return(1); } // Make sure the high surrogate isn't in the range of low surrogate values if ((codeUnit1 & 0x400) != 0) { return(-1); } // We still output a code point value if we have an unpaired high surrogate. // Nintendo's reason for doing this is unclear. outUtf32 = ((codeUnit1 - 0xD800u) << 10) + codeUnit2 + 0x2400; // Make sure the low surrogate is in the range of low surrogate values if ((codeUnit2 & 0xFC00) != 0xDC00) { return(-2); } return(2); }
public static Result CreateSubFileSystem(out IFileSystem subFileSystem, IFileSystem baseFileSystem, string path, bool createPathIfMissing) { UnsafeHelpers.SkipParamInit(out subFileSystem); Result rc; if (!createPathIfMissing) { if (path == null) { return(ResultFs.NullptrArgument.Log()); } rc = baseFileSystem.GetEntryType(out DirectoryEntryType entryType, path.ToU8Span()); if (rc.IsFailure() || entryType != DirectoryEntryType.Directory) { return(ResultFs.PathNotFound.Log()); } } rc = baseFileSystem.EnsureDirectoryExists(path); if (rc.IsFailure()) { return(rc); } return(CreateSubFileSystemImpl(out subFileSystem, baseFileSystem, path)); }
public Result EnumerateDeliveryCacheDirectory(out int namesRead, Span <DirectoryName> nameBuffer) { UnsafeHelpers.SkipParamInit(out namesRead); lock (Locker) { var metaReader = new DeliveryCacheDirectoryMetaAccessor(Server); Result rc = metaReader.ReadApplicationDirectoryMeta(ApplicationId, true); if (rc.IsFailure()) { return(rc); } int i; for (i = 0; i < nameBuffer.Length; i++) { rc = metaReader.GetEntry(out DeliveryCacheDirectoryMetaEntry entry, i); if (rc.IsFailure()) { if (!ResultBcat.NotFound.Includes(rc)) { return(rc); } break; } StringUtils.Copy(nameBuffer[i].Bytes, entry.Name.Bytes); } namesRead = i; return(Result.Success); } }
public Result OperateRange(out QueryRangeInfo rangeInfo, int operationId, long offset, long size) { UnsafeHelpers.SkipParamInit(out rangeInfo); rangeInfo.Clear(); if (operationId == (int)OperationId.InvalidateCache) { Result rc = BaseFile.OperateRange(Span <byte> .Empty, OperationId.InvalidateCache, offset, size, ReadOnlySpan <byte> .Empty); if (rc.IsFailure()) { return(rc); } } else if (operationId == (int)OperationId.QueryRange) { Unsafe.SkipInit(out QueryRangeInfo info); Result rc = BaseFile.OperateRange(SpanHelpers.AsByteSpan(ref info), OperationId.QueryRange, offset, size, ReadOnlySpan <byte> .Empty); if (rc.IsFailure()) { return(rc); } rangeInfo.Merge(in info); } return(Result.Success); }
public Result Create(out ReferenceCountedDisposable <IFileSystem> subDirFileSystem, ref ReferenceCountedDisposable <IFileSystem> baseFileSystem, U8Span path, bool preserveUnc) { UnsafeHelpers.SkipParamInit(out subDirFileSystem); // Verify the sub-path exists Result rc = baseFileSystem.Target.OpenDirectory(out IDirectory _, path, OpenDirectoryMode.Directory); if (rc.IsFailure()) { return(rc); } // Initialize the SubdirectoryFileSystem var subDir = new SubdirectoryFileSystem(ref baseFileSystem, preserveUnc); using var subDirShared = new ReferenceCountedDisposable <SubdirectoryFileSystem>(subDir); rc = subDirShared.Target.Initialize(path); if (rc.IsFailure()) { return(rc); } subDirFileSystem = subDirShared.AddReference <IFileSystem>(); return(Result.Success); }
public static Result ConvertToFspPath(out FspPath fspPath, ReadOnlySpan <byte> path) { UnsafeHelpers.SkipParamInit(out fspPath); int length = StringUtils.Copy(SpanHelpers.AsByteSpan(ref fspPath), path, PathTool.EntryNameLengthMax + 1); if (length >= PathTool.EntryNameLengthMax + 1) { return(ResultFs.TooLongPath.Log()); } Result rc = PathFormatter.SkipMountName(out ReadOnlySpan <byte> pathWithoutMountName, out _, new U8Span(path)); if (rc.IsFailure()) { return(rc); } if (!WindowsPath12.IsWindowsPath(pathWithoutMountName, true)) { Replace(SpanHelpers.AsByteSpan(ref fspPath).Slice(0, 0x300), AltDirectorySeparator, DirectorySeparator); } else if (fspPath.Str[0] == DirectorySeparator && fspPath.Str[1] == DirectorySeparator) { SpanHelpers.AsByteSpan(ref fspPath)[0] = AltDirectorySeparator; SpanHelpers.AsByteSpan(ref fspPath)[1] = AltDirectorySeparator; } return(Result.Success); }
protected override Result DoGetFileAttributes(out NxFileAttributes attributes, U8Span path) { UnsafeHelpers.SkipParamInit(out attributes); Unsafe.SkipInit(out FsPath normalizedPath); Result rc = PathNormalizer.Normalize(normalizedPath.Str, out _, path, false, false); if (rc.IsFailure()) { return(rc); } if (FsTable.GetFile(normalizedPath, out FileNode file).IsSuccess()) { attributes = file.Attributes; return(Result.Success); } if (FsTable.GetDirectory(normalizedPath, out DirectoryNode dir).IsSuccess()) { attributes = dir.Attributes; return(Result.Success); } return(ResultFs.PathNotFound.Log()); }
public Result OpenBaseFileSystem(out ReferenceCountedDisposable <IFileSystemSf> fileSystem, BaseFileSystemId fileSystemId) { UnsafeHelpers.SkipParamInit(out fileSystem); Result rc = CheckCapabilityById(fileSystemId, _processId); if (rc.IsFailure()) { return(rc); } ReferenceCountedDisposable <IFileSystem> fs = null; try { // Open the file system rc = _serviceImpl.OpenBaseFileSystem(out fs, fileSystemId); if (rc.IsFailure()) { return(rc); } // Create an SF adapter for the file system fileSystem = FileSystemInterfaceAdapter.CreateShared(ref fs); return(Result.Success); } finally { fs?.Dispose(); } }
protected override Result DoGetEntryType(out DirectoryEntryType entryType, U8Span path) { UnsafeHelpers.SkipParamInit(out entryType); Unsafe.SkipInit(out FsPath normalizedPath); Result rc = PathNormalizer.Normalize(normalizedPath.Str, out _, path, false, false); if (rc.IsFailure()) { return(rc); } if (FsTable.GetFile(normalizedPath, out _).IsSuccess()) { entryType = DirectoryEntryType.File; return(Result.Success); } if (FsTable.GetDirectory(normalizedPath, out _).IsSuccess()) { entryType = DirectoryEntryType.Directory; return(Result.Success); } return(ResultFs.PathNotFound.Log()); }
public Uuid128 Increment(ulong value) { unsafe { fixed(Uuid128 *self = &this) { // serialize GUID into High Endian format byte *buf = stackalloc byte[16]; WriteUnsafe((Guid *)self, buf); // Add the low 64 bits (in HE) ulong lo = UnsafeHelpers.LoadUInt64BE(buf + 8); ulong sum = lo + value; if (sum < value) { // overflow occured, we must carry to the high 64 bits (in HE) ulong hi = UnsafeHelpers.LoadUInt64BE(buf); UnsafeHelpers.StoreUInt64BE(buf, unchecked (hi + 1)); } UnsafeHelpers.StoreUInt64BE(buf + 8, sum); // deserialize back to GUID return(new Uuid128(ReadUnsafe(buf))); } } }
public static Result GetCaseSensitivePath(out int bytesWritten, Span <byte> buffer, U8Span path, U8Span workingDirectoryPath) { UnsafeHelpers.SkipParamInit(out bytesWritten); string pathUtf16 = StringUtils.Utf8ZToString(path); string workingDirectoryPathUtf16 = StringUtils.Utf8ZToString(workingDirectoryPath); Result rc = GetCaseSensitivePathFull(out string caseSensitivePath, out int rootPathLength, pathUtf16, workingDirectoryPathUtf16); if (rc.IsFailure()) { return(rc); } OperationStatus status = Utf8.FromUtf16(caseSensitivePath.AsSpan(rootPathLength), buffer.Slice(0, buffer.Length - 1), out _, out int utf8BytesWritten); if (status == OperationStatus.DestinationTooSmall) { return(ResultFs.TooLongPath.Log()); } if (status == OperationStatus.InvalidData || status == OperationStatus.NeedMoreData) { return(ResultFs.InvalidCharacter.Log()); } buffer[utf8BytesWritten] = NullTerminator; bytesWritten = utf8BytesWritten; return(Result.Success); }
static LUtfNode DefaultMaterialNode(LUtfNode parent, ColladaMaterial mat, int i) { var matnode = new LUtfNode() { Name = mat.Name, Parent = parent }; matnode.Children = new List <LUtfNode>(); matnode.Children.Add(new LUtfNode() { Name = "Type", Parent = matnode, Data = Encoding.ASCII.GetBytes("DcDt") }); var arr = new float[] { mat.Dc.R, mat.Dc.G, mat.Dc.B }; matnode.Children.Add(new LUtfNode() { Name = "Dc", Parent = matnode, Data = UnsafeHelpers.CastArray(arr) }); matnode.Children.Add(new LUtfNode() { Name = "Dt_name", Parent = matnode, Data = Encoding.ASCII.GetBytes(mat.Name + ".dds") }); matnode.Children.Add(new LUtfNode() { Name = "Dt_flags", Parent = matnode, Data = BitConverter.GetBytes(64) }); return(matnode); }
public Dictionary <string, object> DoString(string str, string name = "[string]") { if (!thn_compile(str, name, out IntPtr buf, out int sz)) { var err = thn_geterror(); var errstring = UnsafeHelpers.PtrToStringUTF8(err); thn_free(err); throw new Exception(errstring); } var compiled = new byte[sz]; Marshal.Copy(buf, compiled, 0, sz); thn_free(buf); using (var stream = new MemoryStream(compiled)) { LuaPrototype p; if (!Undump.Load(stream, out p)) { throw new Exception("Undump failed"); } var runtime = new LuaBinaryRuntime(p); runtime.Env = Env; runtime.Run(); return(runtime.Globals); } }
static LUtfNode DefaultMaterialNode(LUtfNode parent, string name, int i) { var matnode = new LUtfNode() { Name = name, Parent = parent }; matnode.Children = new List <LUtfNode>(); matnode.Children.Add(new LUtfNode() { Name = "Type", Parent = matnode, Data = Encoding.ASCII.GetBytes("DcDt") }); matnode.Children.Add(new LUtfNode() { Name = "Dc", Parent = matnode, Data = UnsafeHelpers.CastArray(matColors[i % matColors.Length]) }); matnode.Children.Add(new LUtfNode() { Name = "Dt_name", Parent = matnode, Data = Encoding.ASCII.GetBytes(name + ".dds") }); matnode.Children.Add(new LUtfNode() { Name = "Dt_flags", Parent = matnode, Data = BitConverter.GetBytes(64) }); return(matnode); }
public static string GtkSave(IntPtr parent, FileDialogFilters filters) { if (!gtk_init_check(IntPtr.Zero, IntPtr.Zero)) { throw new Exception(); } var dlg = gtk_file_chooser_dialog_new("Save File", IntPtr.Zero, GTK_FILE_CHOOSER_ACTION_SAVE, IntPtr.Zero); gtk_dialog_add_button(dlg, "_Cancel", GTK_RESPONSE_CANCEL); gtk_dialog_add_button(dlg, "_Accept", GTK_RESPONSE_ACCEPT); SetFilters(dlg, filters); gtk_widget_realize(dlg); XSetTransientForHint(gdk_x11_get_default_xdisplay(), gdk_x11_drawable_get_xid(gtk_widget_get_window(dlg)), parent); string result = null; if (gtk_dialog_run(dlg) == GTK_RESPONSE_ACCEPT) { result = UnsafeHelpers.PtrToStringUTF8(gtk_file_chooser_get_filename(dlg)); } WaitCleanup(); gtk_widget_destroy(dlg); WaitCleanup(); return(result); }
public Result OpenAccessFailureDetectionEventNotifier(out ReferenceCountedDisposable <IEventNotifier> notifier, ulong processId, bool notifyOnDeepRetry) { UnsafeHelpers.SkipParamInit(out notifier); Result rc = GetProgramInfo(out ProgramInfo programInfo); if (rc.IsFailure()) { return(rc); } if (!programInfo.AccessControl.CanCall(OperationType.OpenAccessFailureDetectionEventNotifier)) { return(ResultFs.PermissionDenied.Log()); } rc = _serviceImpl.CreateNotifier(out IEventNotifier tempNotifier, processId, notifyOnDeepRetry); if (rc.IsFailure()) { return(rc); } notifier = new ReferenceCountedDisposable <IEventNotifier>(tempNotifier); return(Result.Success); }
public void AddTtfFile(string file) { var str = UnsafeHelpers.StringToHGlobalUTF8(file); pg_addttfglobal(str); Marshal.FreeHGlobal(str); }
public Result GetSize(out long size) { const int maxTryCount = 2; UnsafeHelpers.SkipParamInit(out size); Result rc = Result.Success; long tmpSize = 0; for (int tryNum = 0; tryNum < maxTryCount; tryNum++) { rc = BaseFile.GetSize(out tmpSize); // Retry on ResultDataCorrupted if (!ResultFs.DataCorrupted.Includes(rc)) { break; } } if (rc.IsFailure()) { return(rc); } size = tmpSize; return(Result.Success); }
public static Result GetGameCardHandle(this FileSystemClient fs, out GameCardHandle handle) { UnsafeHelpers.SkipParamInit(out handle); using ReferenceCountedDisposable <IFileSystemProxy> fsProxy = fs.Impl.GetFileSystemProxyServiceObject(); ReferenceCountedDisposable <IDeviceOperator> deviceOperator = null; try { Result rc = fsProxy.Target.OpenDeviceOperator(out deviceOperator); fs.Impl.AbortIfNeeded(rc); if (rc.IsFailure()) { return(rc); } rc = deviceOperator.Target.GetGameCardHandle(out handle); fs.Impl.AbortIfNeeded(rc); return(rc); } finally { deviceOperator?.Dispose(); } }
public static CharacterEncodingResult GetLengthOfConvertedStringUtf32ToUtf8(out int length, ReadOnlySpan <uint> source, int sourceLength) { UnsafeHelpers.SkipParamInit(out length); Span <byte> buffer = stackalloc byte[0x20]; Assert.SdkRequires(0 <= sourceLength, $"{nameof(sourceLength)} must not be negative."); Assert.SdkRequires(sourceLength <= source.Length); int totalLength = 0; source = source.Slice(0, sourceLength); while (source.Length > 0) { CharacterEncodingResult result = ConvertStringUtf32ToUtf8Impl(out int writtenCount, out int readCount, buffer, source); if (result == CharacterEncodingResult.InvalidFormat) { return(CharacterEncodingResult.InvalidFormat); } totalLength += writtenCount; source = source.Slice(readCount); } Assert.SdkAssert(0 <= totalLength); length = totalLength; return(CharacterEncodingResult.Success); }
public static bool TryGetSectionTypeFromIndex(int index, NcaContentType contentType, out NcaSectionType type) { switch (index) { case 0 when contentType == NcaContentType.Program: type = NcaSectionType.Code; return(true); case 1 when contentType == NcaContentType.Program: type = NcaSectionType.Data; return(true); case 2 when contentType == NcaContentType.Program: type = NcaSectionType.Logo; return(true); case 0: type = NcaSectionType.Data; return(true); default: UnsafeHelpers.SkipParamInit(out type); return(false); } }
public static Result GetAndClearMmcErrorInfo(this StorageService service, out StorageErrorInfo errorInfo, out long logSize, Span <byte> logBuffer) { UnsafeHelpers.SkipParamInit(out errorInfo, out logSize); ReferenceCountedDisposable <IStorageDeviceOperator> mmcOperator = null; try { Result rc = service.GetMmcManagerOperator(out mmcOperator); if (rc.IsFailure()) { return(rc); } int operationId = MakeOperationId(MmcManagerOperationIdValue.GetAndClearErrorInfo); var logOutBuffer = new OutBuffer(logBuffer); OutBuffer errorInfoOutBuffer = OutBuffer.FromStruct(ref errorInfo); return(mmcOperator.Target.OperateOut2(out _, errorInfoOutBuffer, out logSize, logOutBuffer, operationId)); } finally { mmcOperator?.Dispose(); } }
/// <summary> /// Opens an <see cref="IStorage"/> of the initial process binary. If the binary is embedded in /// the kernel, this method will attempt to locate and return the embedded binary. /// </summary> /// <param name="iniStorage">If the method returns successfully, contains an <see cref="IStorage"/> /// of the initial process binary.</param> /// <returns>The <see cref="Result"/> of the operation.</returns> public Result OpenIni(out IStorage iniStorage) { if (HasIniPayload()) { return(OpenPayload(out iniStorage, IniPayloadIndex)); } // Ini is embedded in the kernel UnsafeHelpers.SkipParamInit(out iniStorage); Result rc = OpenKernel(out IStorage kernelStorage); if (rc.IsFailure()) { return(rc); } if (!IniExtract.TryGetIni1Offset(out int offset, out int size, kernelStorage)) { // Unable to find the ini. Could be a new, unsupported layout. return(ResultLibHac.NotImplemented.Log()); } iniStorage = new SubStorage(kernelStorage, offset, size); return(Result.Success); }
public Result GetKeyValueSize(out int keySize, out int valueSize) { UnsafeHelpers.SkipParamInit(out keySize, out valueSize); // This should only be called after ReadEntryCount. Assert.SdkNotEqual(_offset, 0); // Peek the next entry header. Unsafe.SkipInit(out KeyValueArchiveEntryHeader header); Result rc = Peek(SpanHelpers.AsByteSpan(ref header)); if (rc.IsFailure()) { return(rc); } if (!header.IsValid()) { return(ResultKvdb.InvalidKeyValue.Log()); } keySize = header.KeySize; valueSize = header.ValueSize; return(Result.Success); }
private Result GetDecryptor(out ICipher decryptor, long offset) { if (offset == 0) { // Use the IV directly decryptor = Aes.CreateCbcDecryptor(_key, _iv); return(Result.Success); } UnsafeHelpers.SkipParamInit(out decryptor); // Need to get the output of the previous block Span <byte> prevBlock = stackalloc byte[BlockSize]; Result rc = BaseStorage.Read(offset - BlockSize, prevBlock); if (rc.IsFailure()) { return(rc); } ICipher tmpDecryptor = Aes.CreateCbcDecryptor(_key, _iv); tmpDecryptor.Transform(prevBlock, prevBlock); decryptor = tmpDecryptor; return(Result.Success); }
internal static Result FindFileSystem(this FileSystemClientImpl fs, out FileSystemAccessor fileSystem, out U8Span subPath, U8Span path) { UnsafeHelpers.SkipParamInit(out fileSystem); subPath = default; if (path.IsNull()) { return(ResultFs.NullptrArgument.Log()); } int hostMountNameLen = StringUtils.GetLength(CommonPaths.HostRootFileSystemMountName); if (StringUtils.Compare(path, CommonPaths.HostRootFileSystemMountName, hostMountNameLen) == 0) { return(ResultFs.NotMounted.Log()); } Result rc = GetMountNameAndSubPath(out MountName mountName, out subPath, path); if (rc.IsFailure()) { return(rc); } return(fs.Find(out fileSystem, new U8Span(mountName.Name))); }
protected override Result DoOpenDirectory(out IDirectory directory, U8Span path, OpenDirectoryMode mode) { UnsafeHelpers.SkipParamInit(out directory); Result rc = ResolveFullPath(out string fullPath, path, true); if (rc.IsFailure()) { return(rc); } rc = GetDirInfo(out DirectoryInfo dirInfo, fullPath); if (rc.IsFailure()) { return(rc); } if (!dirInfo.Attributes.HasFlag(FileAttributes.Directory)) { return(ResultFs.PathNotFound.Log()); } IDirectory dirTemp = null; rc = TargetLockedAvoidance.RetryToAvoidTargetLocked(() => OpenDirectoryInternal(out dirTemp, mode, dirInfo), _fsClient); if (rc.IsFailure()) { return(rc); } directory = dirTemp; return(Result.Success); }