/// <summary> /// Accesses a file's contents as a stream for writing. /// </summary> /// <param name="objectFileOperations">The instance of <see cref="VaultObjectFileOperations"/> to use.</param> /// <param name="objectFile">The file to open for writing.</param> /// <param name="vault">The vault the file comes from.</param> /// <param name="automaticallyCommitOnDisposal">If true, will automatically save the file contents to the vault when this stream is disposed of.</param> /// <returns>The file opened as a write-only <see cref="Stream"/>.</returns> /// <remarks>Use <see cref="OpenFileForWriting(VaultObjectFileOperations, ObjectFile, ObjID, Vault, bool)"/> if you have the <see cref="ObjID"/> as this is more efficient.</remarks> public static Stream OpenFileForWriting ( this VaultObjectFileOperations objectFileOperations, ObjectFile objectFile, Vault vault, bool automaticallyCommitOnDisposal = true ) { // Sanity. if (null == objectFileOperations) { throw new ArgumentNullException(nameof(objectFileOperations)); } if (null == objectFile) { throw new ArgumentNullException(nameof(objectFile)); } if (null == vault) { throw new ArgumentNullException(nameof(vault)); } // Return a file stream of the object. return(new FileUploadStream ( objectFile.FileVer, vault.ObjectFileOperations.GetObjIDOfFile(objectFile.ID), vault, automaticallyCommitOnDisposal )); }
/// <summary> /// Creates a new ObjectFile with the parts provided /// </summary> /// <param name="parts">Collection of CodeParts generated by the compiler</param> /// <returns>Id of the new ObjectFile</returns> public Guid AddObjectFile(IEnumerable <CodePart> parts) { var objectFile = new ObjectFile(parts); objectFiles.Add(objectFile.Id, objectFile); return(objectFile.Id); }
/// <inheritdoc /> public virtual void VisitObjectFile(ObjectFile objectFile) { foreach (var section in objectFile.Sections) { section.Accept(this); } }
public Context CreateContext(ObjectFile objectfile) { Contract.Requires <ArgumentNullException>(objectfile != null); Contract.Ensures(Contract.Result <Context>() != null); return(default(Context)); }
private void WriteSections() { var sections = ObjectFile.Sections; if (sections.Count == 0) { return; } sections = ObjectFile.GetSectionsOrderedByStreamIndex(); // We write the content all sections including shadows for (var i = 0; i < sections.Count; i++) { var section = sections[i]; // Write only section with content if (section.HasContent) { Stream.Position = (long)(_startOfFile + section.Offset); section.WriteInternal(this); } } // Write section header table WriteSectionHeaderTable(); }
/// <summary> /// Loads an object file from a file. /// </summary> /// <param name="path">the source fie to read from</param> /// <param name="obj">the resulting object file (on success)</param> private static int LoadObjectFile(string path, ObjectFile obj) { try { obj.Load(path); return(0); } // things from CSX64 catch (TypeError) { Console.Error.WriteLine($"{path} is not a CSX64 object file"); return((int)AsmLnkErrorExt.FormatError); } catch (VersionError) { Console.Error.WriteLine($"Object file {path} is of an incompatible version of CSX64"); return((int)AsmLnkErrorExt.FormatError); } catch (FormatException) { Console.Error.WriteLine($"Object file {path} is of an unrecognized format"); return((int)AsmLnkErrorExt.FormatError); } // things from File.OpenRead catch (ArgumentNullException) { Console.Error.WriteLine("Path was null"); return((int)AsmLnkErrorExt.NullPath); } catch (ArgumentException ex) { Console.Error.WriteLine($"Path \"{path}\" was invalid\n{ex}"); return((int)AsmLnkErrorExt.InvalidPath); } catch (PathTooLongException) { Console.Error.WriteLine($"Path \"{path}\" was too long"); return((int)AsmLnkErrorExt.InvalidPath); } catch (DirectoryNotFoundException) { Console.Error.WriteLine($"Path \"{path}\" directory was not found"); return((int)AsmLnkErrorExt.DirectoryNotFound); } catch (UnauthorizedAccessException) { Console.Error.WriteLine($"You do not have permission to open \"{path}\" for reading"); return((int)AsmLnkErrorExt.AccessViolation); } catch (FileNotFoundException) { Console.Error.WriteLine($"File \"{path}\" could not be found"); return((int)AsmLnkErrorExt.FileNotFound); } catch (NotSupportedException) { Console.Error.WriteLine($"Path \"{path}\" was of an unsupported format"); return((int)AsmLnkErrorExt.PathFormatUnsupported); } catch (IOException) { Console.Error.WriteLine($"An error occurred while reading file \"{path}\""); return((int)AsmLnkErrorExt.IOError); } // things from casting after deserialization catch (InvalidCastException) { Console.Error.WriteLine($"file \"{path}\" was incorrectly-formatted"); return((int)AsmLnkErrorExt.FormatError); } // everything else that might happen for some reason catch (Exception ex) { Console.Error.WriteLine($"An error occurred while attempting to execute \"{path}\"\n-> {ex}"); return((int)AsmLnkErrorExt.UnknownError); } }
private void ReadSectionHeaderTable() { if (Layout.SizeOfSectionHeaderEntry == 0) { if (_sectionHeaderCount > 0) { Diagnostics.Error(DiagnosticId.ELF_ERR_InvalidZeroSectionHeaderTableEntrySize, $"Unable to read section header table as the size of section header entry ({nameof(ElfNative.Elf32_Ehdr.e_ehsize)}) == 0 in the Elf Header"); } return; } for (int i = 0; i < _sectionHeaderCount; i++) { var offset = Layout.OffsetOfSectionHeaderTable + (ulong)i * Layout.SizeOfSectionHeaderEntry; if (offset >= (ulong)Stream.Length) { Diagnostics.Error(DiagnosticId.ELF_ERR_InvalidSectionHeaderStreamOffset, $"Unable to read section [{i}] as its offset {offset} is out of bounds"); break; } // Seek to the header position Stream.Position = (long)offset; var section = ReadSectionTableEntry(i); ObjectFile.AddSection(section); } }
/// <summary> /// Accesses a file's contents as a stream for reading. /// </summary> /// <param name="objectFileOperations">The instance of <see cref="VaultObjectFileOperations"/> to use.</param> /// <param name="objectFile">The file to open for reading.</param> /// <param name="vault">The vault the file comes from.</param> /// <param name="fileFormat">The format of the file to read as.</param> /// <returns>The file opened as a <see cref="Stream"/>.</returns> public static Stream OpenFileForReading ( this VaultObjectFileOperations objectFileOperations, ObjectFile objectFile, Vault vault, MFFileFormat fileFormat = MFFileFormat.MFFileFormatNative ) { // Sanity. if (null == objectFileOperations) { throw new ArgumentNullException(nameof(objectFileOperations)); } if (null == objectFile) { throw new ArgumentNullException(nameof(objectFile)); } if (null == vault) { throw new ArgumentNullException(nameof(vault)); } // Return a file stream of the object. return(new FileDownloadStream(objectFile, vault, fileFormat)); }
ICompilationPolicy.Compile( ObjectFile sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString objectFilePath, Bam.Core.Module source) { if (!sender.PerformCompilation) { return; } if (sender.ReasonToExecute.Reason == Bam.Core.ExecuteReasoning.EReason.DeferredEvaluation) { if (!DeferredEvaluationRequiresBuild(sender)) { return; } } var objectFileDir = System.IO.Path.GetDirectoryName(objectFilePath.ToString()); Bam.Core.IOWrapper.CreateDirectoryIfNotExists(objectFileDir); var commandLine = new Bam.Core.StringArray(); (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine); commandLine.Add(source.GeneratedPaths[SourceFile.Key].ParseAndQuoteIfNecessary()); CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine); }
/// <summary> /// Writes the contents of the specified <see cref="ObjectFile"/> /// in the assembly language. /// </summary> /// <param name="objectfile">The <see cref="ObjectFile"/> to write.</param> public virtual void WriteObjectFile(ObjectFile objectfile) { foreach (Section s in objectfile) { WriteSection(objectfile, s); } }
static void ImportText(ObjectFile objectFile, string value, string openedFileDir, Parameters parameters) { if (objectFile.Object is PersonaEditorLib.FileStructure.Text.PTP ptp) { string path = value == "" ? Path.Combine(openedFileDir, Path.GetFileNameWithoutExtension(objectFile.Name) + ".TXT") : value; string[] importedtext; if (File.Exists(path)) { importedtext = File.ReadAllLines(path, parameters.Encode); if (parameters.LineByLine) { ptp.ImportTXT_LBL(importedtext, parameters.Map, parameters.Width, parameters.SkipEmpty, Static.OldEncoding(), Static.NewEncoding(), Static.NewFont()); } else { ptp.ImportTXT(importedtext, objectFile.Name, parameters.Map, parameters.Width, parameters.SkipEmpty, Static.OldEncoding(), Static.NewEncoding(), Static.NewFont()); } } } else if (objectFile.Object is PersonaEditorLib.FileStructure.Text.StringList strlst) { string path = value == "" ? Path.Combine(openedFileDir, Path.GetFileNameWithoutExtension(objectFile.Name) + ".TXT") : value; string[] importedtext; if (File.Exists(path)) { importedtext = File.ReadAllLines(path, parameters.Encode); strlst.ImportText(importedtext, parameters.Map, parameters.SkipEmpty); } } }
ICompilationPolicy.Compile( ObjectFile sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString objectFilePath, Bam.Core.Module source) { var commandLineArgs = new Bam.Core.StringArray(); (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs); var meta = new MakeFileBuilder.MakeFileMeta(sender); var rule = meta.AddRule(); rule.AddTarget(objectFilePath); rule.AddPrerequisite(source, C.SourceFile.Key); var tool = sender.Tool as Bam.Core.ICommandLineTool; var command = new System.Text.StringBuilder(); command.AppendFormat("{0} {1} $< {2}", CommandLineProcessor.Processor.StringifyTool(tool), commandLineArgs.ToString(' '), CommandLineProcessor.Processor.TerminatingArgs(tool)); rule.AddShellCommand(command.ToString()); var objectFileDir = System.IO.Path.GetDirectoryName(objectFilePath.ToString()); meta.CommonMetaData.Directories.AddUnique(objectFileDir); meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables); }
/// <summary> /// Replaces the contents of an existing <paramref name="objectFile"/> with data from <paramref name="fileContents"/>. /// </summary> /// <param name="objVerEx">The object version that contains the file. Must already be checked out.</param> /// <param name="objectFile">The file to update.</param> /// <param name="fileContents">The contents of the file.</param> /// <param name="blockSize">The block size to use for transfers.</param> public static void ReplaceFileContent ( this ObjVerEx objVerEx, ObjectFile objectFile, Stream fileContents, int blockSize = FileTransfers.DefaultBlockSize ) { // Sanity. if (null == objVerEx) { throw new ArgumentNullException(nameof(objVerEx)); } if (null == objectFile) { throw new ArgumentNullException(nameof(objectFile)); } if (null == fileContents) { throw new ArgumentNullException(nameof(fileContents)); } // Use the other extension method. objectFile.ReplaceFileContent ( objVerEx.Vault, fileContents, blockSize ); }
private void OpenNew(byte[] data) { using (BinaryReader reader = Utilities.IO.OpenReadFile(new MemoryStream(data), IsLittleEndian)) { int count = reader.ReadInt32(); if (count == 0) { throw new System.Exception("BIN: count is zero"); } for (int i = 0; i < count; i++) { string Name = Encoding.ASCII.GetString(reader.ReadBytes(0x20)).Trim('\0'); int Size = reader.ReadInt32(); byte[] Data = reader.ReadBytes(Size); ObjectFile objectFile = Utilities.PersonaFile.OpenFile(Name, Data, Utilities.PersonaFile.GetFileType(Name)); if (objectFile.Object == null) { objectFile = Utilities.PersonaFile.OpenFile(Name, Data, FileType.DAT); } SubFiles.Add(objectFile); } if (reader.BaseStream.Position != reader.BaseStream.Length) { throw new System.Exception("BIN: read error"); } } }
/// <summary> /// Downloads the file to disk. /// </summary> /// <param name="objectFile">The file to download.</param> /// <param name="vault">The vault to download from.</param> /// <param name="fileDownloadLocation">The location on disk to download to.</param> /// <param name="blockSize">The size of blocks to use to transfer the file from the M-Files vault to this machine.</param> /// <param name="fileFormat">The format of file to request from server.</param> /// <returns>A <see cref="TemporaryFileDownload"/> representing the completed file download.</returns> public static TemporaryFileDownload Download ( this ObjectFile objectFile, Vault vault, FileDownloadLocation fileDownloadLocation, int blockSize = FileTransfers.DefaultBlockSize, MFFileFormat fileFormat = MFFileFormat.MFFileFormatNative ) { // Sanity. if (null == objectFile) { throw new ArgumentNullException(nameof(objectFile)); } if (null == vault) { throw new ArgumentNullException(nameof(vault)); } if (null == fileDownloadLocation) { throw new ArgumentNullException(nameof(fileDownloadLocation)); } // Download the file. return(fileDownloadLocation .DownloadFile ( objectFile, vault, blockSize, fileFormat )); }
private void ReadProgramHeaders() { if (Layout.SizeOfProgramHeaderEntry == 0) { if (_programHeaderCount > 0) { Diagnostics.Error(DiagnosticId.ELF_ERR_InvalidZeroProgramHeaderTableEntrySize, $"Unable to read program header table as the size of program header entry ({nameof(ElfNative.Elf32_Ehdr.e_phentsize)}) == 0 in the Elf Header"); } return; } for (int i = 0; i < _programHeaderCount; i++) { var offset = Layout.OffsetOfProgramHeaderTable + (ulong)i * Layout.SizeOfProgramHeaderEntry; if (offset >= (ulong)Stream.Length) { Diagnostics.Error(DiagnosticId.ELF_ERR_InvalidProgramHeaderStreamOffset, $"Unable to read program header [{i}] as its offset {offset} is out of bounds"); break; } // Seek to the header position Stream.Position = (long)offset; var segment = (ObjectFile.FileClass == ElfFileClass.Is32) ? ReadProgramHeader32(i) : ReadProgramHeader64(i); ObjectFile.AddSegment(segment); } }
private unsafe void WriteSectionHeader64() { var hdr = new Elf64_Ehdr(); ObjectFile.CopyIdentTo(new Span <byte>(hdr.e_ident, EI_NIDENT)); _encoder.Encode(out hdr.e_type, (ushort)ObjectFile.FileType); _encoder.Encode(out hdr.e_machine, ObjectFile.Arch.Value); _encoder.Encode(out hdr.e_version, EV_CURRENT); _encoder.Encode(out hdr.e_entry, ObjectFile.EntryPointAddress); _encoder.Encode(out hdr.e_ehsize, Layout.SizeOfElfHeader); _encoder.Encode(out hdr.e_flags, (uint)ObjectFile.Flags); // program headers _encoder.Encode(out hdr.e_phoff, Layout.OffsetOfProgramHeaderTable); _encoder.Encode(out hdr.e_phentsize, Layout.SizeOfProgramHeaderEntry); _encoder.Encode(out hdr.e_phnum, (ushort)ObjectFile.Segments.Count); // entries for sections _encoder.Encode(out hdr.e_shoff, Layout.OffsetOfSectionHeaderTable); _encoder.Encode(out hdr.e_shentsize, (ushort)sizeof(Elf64_Shdr)); _encoder.Encode(out hdr.e_shnum, (ushort)ObjectFile.VisibleSectionCount); _encoder.Encode(out hdr.e_shstrndx, (ushort)(ObjectFile.SectionHeaderStringTable?.SectionIndex ?? (ushort)0)); Write(hdr); }
public static void SaveImageFile(ObjectFile objectFile, string path) { if (objectFile.Object is IImage image) { Imaging.SavePNG(image.GetImage(), path); } }
ICompilationPolicy.Compile( ObjectFile sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString objectFilePath, Bam.Core.Module source) { if (!sender.PerformCompilation) { return; } var commandLineArgs = new Bam.Core.StringArray(); (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs); var meta = new MakeFileBuilder.MakeFileMeta(sender); var rule = meta.AddRule(); rule.AddTarget(objectFilePath); rule.AddPrerequisite(source, C.SourceFile.Key); var tool = sender.Tool as Bam.Core.ICommandLineTool; var command = new System.Text.StringBuilder(); command.AppendFormat("{0} {1} $< {2}", CommandLineProcessor.Processor.StringifyTool(tool), commandLineArgs.ToString(' '), CommandLineProcessor.Processor.TerminatingArgs(tool)); rule.AddShellCommand(command.ToString()); var objectFileDir = System.IO.Path.GetDirectoryName(objectFilePath.ToString()); meta.CommonMetaData.AddDirectory(objectFileDir); meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables); // add dependencies, such as procedurally generated headers foreach (var dep in sender.Dependents) { if (null == dep.MetaData) { continue; } if (dep is C.SourceFile) { continue; } var depMeta = dep.MetaData as MakeFileBuilder.MakeFileMeta; foreach (var depRule in depMeta.Rules) { depRule.ForEachTarget(target => { if (!target.IsPhony) { rule.AddPrerequisite(target.Path); } }); } } }
static void ExportTable(ObjectFile objectFile, string value, string openedFileDir, Parameters parameters) { if (objectFile.Object is ITable table) { string path = Path.Combine(openedFileDir, Path.GetFileNameWithoutExtension(objectFile.Name) + ".XML"); table.GetTable().Save(path); } }
/// <summary> /// Initializes a new instance of the <see cref="BinObjectFileAssembler"/> class. /// </summary> /// <param name="objectFile">The object file that will be assembled.</param> public BinObjectFileAssembler(ObjectFile objectFile) : base(objectFile) { #region Contract Contract.Requires <ArgumentNullException>(objectFile != null); Contract.Requires <ArgumentException>(typeof(BinObjectFileFormat).IsAssignableFrom(objectFile.Format.GetType())); #endregion }
/// <summary> /// Initializes a new instance of the <see cref="BinObjectFileAssembler"/> class. /// </summary> /// <param name="objectFile">The object file that will be assembled.</param> public BinObjectFileAssembler(ObjectFile objectFile) : base(objectFile) { #region Contract Contract.Requires<ArgumentNullException>(objectFile != null); Contract.Requires<ArgumentException>(typeof(BinObjectFileFormat).IsAssignableFrom(objectFile.Format.GetType())); #endregion }
public static void replace_files(this OT_Document document, string singledoc_newfilepath = null, string[] multidoc_newfilespath = null) { Vault vault = document.objVerEx.Vault; var obj = document.objVerEx; bool isSingleFile = vault.ObjectOperations.IsSingleFileObject(obj.ObjVer); //singlefile document if (isSingleFile && string.IsNullOrEmpty(singledoc_newfilepath)) { throw new Exception("No file supplied for single-file document."); } //multifile document if (!isSingleFile && (multidoc_newfilespath == null || multidoc_newfilespath.Length == 0)) { throw new Exception("No file(s) supplied for multi-file document."); } ObjectVersion new_version = vault.ObjectOperations.CheckOut(obj.ObjID); try { ObjVerEx new_versionex = new ObjVerEx(vault, new_version); SourceObjectFiles files = new SourceObjectFiles(); if (isSingleFile) { FileInfo fi = new FileInfo(singledoc_newfilepath); files.AddFile(fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), fi.FullName); //change the file type IEnumerator obfile_enumerator = vault.ObjectFileOperations.GetFiles(new_version.ObjVer).GetEnumerator(); obfile_enumerator.MoveNext(); ObjectFile single_fileobj = obfile_enumerator.Current as ObjectFile; if (single_fileobj == null) { throw new Exception("Single file for this document not found."); } vault.ObjectFileOperations.RenameFile(new_versionex.ObjVer, single_fileobj.FileVer, fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), false); } else { foreach (string file in multidoc_newfilespath) { FileInfo fi = new FileInfo(file); files.AddFile(fi.Name.Replace(fi.Extension, ""), fi.Extension.Replace(".", ""), fi.FullName); } } new_versionex.ReplaceFiles(files); new_versionex.CheckIn(); document.objVerEx = new_versionex; } catch { if (new_version.ObjectCheckedOut) { vault.ObjectOperations.ForceUndoCheckout(new_version.ObjVer); } throw; } }
/// <summary> /// Opens a read-only stream to access the existing file contents. /// </summary> /// <param name="objectFile">The file to download.</param> /// <param name="vault">The vault to download from.</param> /// <param name="fileFormat">The format of file to request from server.</param> /// <returns>A <see cref="FileDownloadStream"/> that can be used to read the file from the vault.</returns> /// <remarks>Ensure that the stream is correctly closed and disposed of (e.g. with a <see langword="using"/> statement).</remarks> public static FileDownloadStream OpenRead ( this ObjectFile objectFile, Vault vault, MFFileFormat fileFormat = MFFileFormat.MFFileFormatNative ) { return(new FileDownloadStream(objectFile, vault, fileFormat)); }
/// <summary> /// Opens a write-only stream to replace the existing file contents. /// </summary> /// <param name="objectFile">The file to update.</param> /// <param name="vault">The vault to download from.</param> /// <param name="objectId">The object to which this file belongs.</param> /// <param name="automaticallyCommitOnDisposal">If true, will automatically save the file contents to the vault when this stream is disposed of.</param> /// <returns>A <see cref="FileUploadStream"/> that can be used to write file data to vault.</returns> /// <remarks>Ensure that the stream is correctly closed and disposed of (e.g. with a <see langword="using"/> statement).</remarks> public static FileUploadStream OpenWrite ( this ObjectFile objectFile, Vault vault, ObjID objectId, bool automaticallyCommitOnDisposal = true ) { return(new FileUploadStream(objectFile.FileVer, objectId, vault, automaticallyCommitOnDisposal)); }
static void ExportText(ObjectFile objectFile, string value, string openedFileDir, Parameters parameters) { if (objectFile.Object is PersonaEditorLib.FileStructure.Text.PTP ptp) { string path = value == "" ? Path.Combine(openedFileDir, Path.GetFileNameWithoutExtension(objectFile.Name) + ".TXT") : value; string[] exp = ptp.ExportTXT(parameters.Map, objectFile.Name, parameters.RemoveSplit, Static.OldEncoding(), Static.NewEncoding()); File.AppendAllLines(path, exp); } }
public ObjectFileEditor(ObjectFile file, AbstractObjectEditor editor) : base(file) { System.Windows.Forms.Control ed = editor.Control; ed.Dock = System.Windows.Forms.DockStyle.Fill; this.Controls.Add(ed); editor.DirtyChanged += new EventHandler(editor_DirtyChanged); editor.SelectedItem = file.Contents; }
public static void OpenImageFile(ObjectFile objectFile, string path) { if (objectFile.Object is IImage image) { if (File.Exists(path)) { image.SetImage(Imaging.OpenPNG(path)); } } }
/// <summary> /// Generates a unique (GUID-based) temporary file in <see cref="Directory"/> with the given <paramref name="objectFile"/>. /// </summary> /// <param name="objectFile">The file that will be downloaded. Uses the <see cref="ObjectFile.Extension"/>.</param> /// <returns>A <see cref="FileInfo"/> for the temporary file.</returns> protected FileInfo GenerateTemporaryFileInfo(ObjectFile objectFile) { // Sanity. if (null == objectFile) { throw new ArgumentNullException(nameof(objectFile)); } // Use the other overload. return(this.GenerateTemporaryFileInfo(objectFile.Extension)); }
static void ImportTable(ObjectFile objectFile, string value, string openedFileDir, Parameters parameters) { if (objectFile.Object is ITable table) { string path = value == "" ? Path.Combine(openedFileDir, Path.GetFileNameWithoutExtension(objectFile.Name) + ".XML") : value; if (File.Exists(path)) { table.SetTable(XDocument.Load(path)); } } }
public static void OpenPTPFile(ObjectFile objectFile, string path, PersonaEncoding.PersonaEncoding newEncoding) { if (objectFile.Object is FileStructure.Text.BMD bmd) { if (File.Exists(path)) { FileStructure.Text.PTP PTP = new FileStructure.Text.PTP(File.ReadAllBytes(path)); bmd.Open(PTP, newEncoding); } } }
/// <summary> /// Creates a <see cref="FileDownloadStream"/> but does not open the download session. /// </summary> /// <param name="fileToDownload">The file to download.</param> /// <param name="vault">The vault to download from.</param> /// <param name="fileFormat">The format to request the file in from the server.</param> public FileDownloadStream( ObjectFile fileToDownload, Vault vault, MFFileFormat fileFormat = MFFileFormat.MFFileFormatNative ) { // Set properties. this.FileToDownload = fileToDownload ?? throw new ArgumentNullException(nameof(fileToDownload)); this.Vault = vault ?? throw new ArgumentNullException(nameof(vault)); this.FileFormat = fileFormat; }
public void AddRange(IEnumerable<CodePart> parts) { ObjectFile objectFile; if (objectFiles.Count == 0) { objectFile = new ObjectFile(parts); objectFiles.Add(objectFile.Id, objectFile); } else { objectFile = objectFiles.First().Value; objectFile.Parts.AddRange(parts); } }
ICompilationPolicy.Compile( ObjectFile sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString objectFilePath, Bam.Core.Module source) { var encapsulating = sender.GetEncapsulatingReferencedModule(); var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta; var target = workspace.EnsureTargetExists(encapsulating); XcodeBuilder.FileReference.EFileType fileType; if (sender is C.ObjectFile) { fileType = XcodeBuilder.FileReference.EFileType.SourceCodeC; } else if (sender is C.Cxx.ObjectFile) { fileType = XcodeBuilder.FileReference.EFileType.SourceCodeCxx; } else if (sender is C.ObjC.ObjectFile) { fileType = XcodeBuilder.FileReference.EFileType.SourceCodeObjC; } else if (sender is C.ObjCxx.ObjectFile) { fileType = XcodeBuilder.FileReference.EFileType.SourceCodeObjCxx; } else { throw new Bam.Core.Exception("Unknown object file type, {0}", sender.GetType().ToString()); } sender.MetaData = target.EnsureSourceBuildFileExists(source.GeneratedPaths[C.SourceFile.Key], fileType); // this is for stand-alone object files if (encapsulating == sender || encapsulating == (sender as Bam.Core.IChildModule).Parent) { target.Type = XcodeBuilder.Target.EProductType.ObjFile; var configuration = target.GetConfiguration(sender); configuration.SetProductName(Bam.Core.TokenizedString.CreateVerbatim("${TARGET_NAME}")); (sender.Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration); } }
ICompilationPolicy.Compile( ObjectFile sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString objectFilePath, Bam.Core.Module source) { var encapsulating = sender.GetEncapsulatingReferencedModule(); var solution = Bam.Core.Graph.Instance.MetaData as VSSolutionBuilder.VSSolution; var project = solution.EnsureProjectExists(encapsulating); var config = project.GetConfiguration(encapsulating); var group = (sender is WinResource) ? VSSolutionBuilder.VSSettingsGroup.ESettingsGroup.Resource : VSSolutionBuilder.VSSettingsGroup.ESettingsGroup.Compiler; var settingsGroup = config.GetSettingsGroup( group, include: source.GeneratedPaths[C.SourceFile.Key], uniqueToProject: true); settingsGroup.AddSetting("ObjectFileName", "$(IntDir)" + sender.CreateTokenizedString("@trimstart(@relativeto($(0),$(packagebuilddir)/$(moduleoutputdir)),../)", objectFilePath).Parse()); sender.MetaData = settingsGroup; }
/// <summary> /// AIS COFF file Load command generation (loads all sections) /// </summary> /// <param name="cf">The COFFfile object that the section comes from.</param> /// <param name="devAISGen">The specific device AIS generator object.</param> /// <returns>retType enumerator indicating success or failure.</returns> private static retType AISSecureObjectFileLoad( AISGen devAISGen, ObjectFile file ) { UInt32 loadedSectionCount = 0; // Check if object file already loaded if (FindObjectFile(devAISGen,file.FileName) != null) { return retType.FAIL; } // Ii this is a new file, let's add it to our list devAISGen.objectFiles.Add(file); // Make sure we have an endianness match be // FIXME - Is this a good idea, what about binary files? if (!devAISGen.devEndian.ToString().Equals(file.Endianness)) { Console.WriteLine("Endianness mismatch. Device is {0} endian, Object file is {1} endian", devAISGen.devEndian.ToString(), file.Endianness); return retType.FAIL; } // Make sure the .TIBoot section is first (if it exists) ObjectSection firstSection = file.LoadableSections[0]; for (int i = 1; i < file.LoadableSectionCount; i++) { if ((file.LoadableSections[i].name).Equals(".TIBoot")) { file.LoadableSections[0] = file.LoadableSections[i]; file.LoadableSections[i] = firstSection; break; } } // Do all SECTION_LOAD commands for (Int32 i = 0; i < file.LoadableSectionCount; i++) { Boolean encryptSection = false; // Determine section encryption status if (devAISGen.sectionsToEncrypt != null) { if ( (devAISGen.sectionsToEncrypt.Length == 1) && devAISGen.sectionsToEncrypt[0].Equals("ALL")) { encryptSection = true; Console.WriteLine("Encrypting section {0}, since ALL was specified for encryptSections in ini file.",file.LoadableSections[i].name); } else { if ( Array.IndexOf(devAISGen.sectionsToEncrypt,file.LoadableSections[i].name) >= 0 ) { encryptSection = true; Console.WriteLine("Encrypting section {0}, since it was explicitly specified in encryptSections in ini file.",file.LoadableSections[i].name); } } } // Perform secure section load if (AISSecureSectionLoad(devAISGen, file, file.LoadableSections[i], encryptSection) != retType.SUCCESS) { return retType.FAIL; } // Check for need to do TIBoot initialization if ( (loadedSectionCount == 0) && ((file.LoadableSections[i].name).Equals(".TIBoot")) ) { devAISGen.InsertAISJump("_TIBootSetup"); InsertAISSecureSignature(devAISGen); } loadedSectionCount++; } // End of SECTION_LOAD commands // Now that we are done with file contents, we can close it file.Close(); return retType.SUCCESS; }
private static retType AISObjectFileLoad( AISGen devAISGen, ObjectFile file ) { UInt32 loadedSectionCount = 0; // Check if object file already loaded if (FindObjectFile(devAISGen,file.FileName) != null) { return retType.FAIL; } // If this is a new file, let's add it to our list devAISGen.objectFiles.Add(file); if (!devAISGen.devEndian.ToString().Equals(file.Endianness)) { Console.WriteLine("Endianness mismatch. Device is {0} endian, Object file is {1} endian", devAISGen.devEndian.ToString(), file.Endianness); return retType.FAIL; } // Make sure the .TIBoot section is first (if it exists) ObjectSection firstSection = file.LoadableSections[0]; for (Int32 i = 1; i < file.LoadableSectionCount; i++) { if ((file.LoadableSections[i].name).Equals(".TIBoot")) { file.LoadableSections[0] = file.LoadableSections[i]; file.LoadableSections[i] = firstSection; break; } } // Enable CRC if needed devAISGen.InsertAISEnableCRC(); // Do all SECTION_LOAD commands for (Int32 i = 0; i < file.LoadableSectionCount; i++) { if (AISSectionLoad(devAISGen, file, file.LoadableSections[i]) != retType.SUCCESS) { return retType.FAIL; } // Check for need to do TIBoot initialization if (loadedSectionCount == 0) { devAISGen.InsertAISJump("_TIBootSetup"); } loadedSectionCount++; } // End of SECTION_LOAD commands // Now that we are done with file contents, we can close it file.Close(); return retType.SUCCESS; }
private static retType AISSectionLoad( AISGen devAISGen, ObjectFile file, ObjectSection section) { Byte[] secData = file.secRead(section); Byte[] srcCRCData = new Byte[section.size + 8]; Debug.DebugMSG("AISSectionLoad for section " + section.name + " from file " + file.FileName + "."); // If we are doing section-by-section CRC, then zero out the CRC value if (devAISGen.aisCRCType == AisCRCCheckType.SECTION_CRC) { devAISGen.devCRC.ResetCRC(); } // Add section load to the output devAISGen.InsertAISSectionLoad((UInt32) section.loadAddr, (UInt32) section.size, secData); // Copy bytes to CRC byte array for future CRC calculation if (devAISGen.aisCRCType != AisCRCCheckType.NO_CRC) { if (devAISGen.devEndian != devAISGen.devAISEndian) { Endian.swapEndian(BitConverter.GetBytes(section.loadAddr)).CopyTo(srcCRCData, 0); Endian.swapEndian(BitConverter.GetBytes(section.size)).CopyTo(srcCRCData, 4); } else { BitConverter.GetBytes(section.loadAddr).CopyTo(srcCRCData, 0); BitConverter.GetBytes(section.size).CopyTo(srcCRCData, 4); } } // Now write contents to CRC array for (UInt32 k = 0; k < section.size; k+=4) { // Copy bytes to array for future CRC calculation if (devAISGen.aisCRCType != AisCRCCheckType.NO_CRC) { Byte[] temp = new Byte[4]; Array.Copy(secData,k,temp,0,4); if (devAISGen.devEndian != devAISGen.devAISEndian) { Endian.swapEndian(temp).CopyTo(srcCRCData, (8 + k)); } else { temp.CopyTo(srcCRCData, (8 + k)); } } } // Add this section's memory range, checking for overlap AddMemoryRange(devAISGen, (UInt32) section.loadAddr, (UInt32) (section.loadAddr+section.size-1)); // Perform CRC calculation of the section's contents if (devAISGen.aisCRCType != AisCRCCheckType.NO_CRC) { devAISGen.devCRC.CalculateCRC(srcCRCData); if (devAISGen.aisCRCType == AisCRCCheckType.SECTION_CRC) { // Write CRC request command, value, and jump value to temp AIS file devAISGen.InsertAISRequestCRC(((Int32)(-1) * (Int32)(section.size + 12 + 12))); } } return retType.SUCCESS; }
/// <summary> /// Creates a new ObjectFile with the parts provided /// </summary> /// <param name="parts">Collection of CodeParts generated by the compiler</param> /// <returns>Id of the new ObjectFile</returns> public Guid AddObjectFile(IEnumerable<CodePart> parts) { var objectFile = new ObjectFile(parts); objectFiles.Add(objectFile.Id, objectFile); return objectFile.Id; }
/// <summary> /// AIS Section Load command generation /// </summary> /// <param name="cf">The COFFfile object that the section comes from.</param> /// <param name="secHeader">The Hashtable object of the section header to load.</param> /// <param name="devAISGen">The specific device AIS generator object.</param> /// <returns>retType enumerator indicating success or failure.</returns> private static retType AISSecureSectionLoad( AISGen devAISGen, ObjectFile file, ObjectSection section, Boolean encryptSection) { Byte[] secData = file.secRead(section); // Write Section_Load AIS command, load address, and size if (encryptSection) { Byte[] encData = null; // Encrypt data using CTS algorithm try { encData = AesManagedUtil.AesCTSEncrypt(secData,devAISGen.customerEncryptionKey,devAISGen.CEKInitialValue); } catch(Exception e) { Console.WriteLine("Exception during encryption operation: {0}",e.Message); return retType.FAIL; } if (encData != null) { devAISGen.InsertAISEncSectionLoad((UInt32) section.loadAddr, (UInt32) section.size, secData, encData); } else { Console.WriteLine("Section encryption failed."); return retType.FAIL; } } else { devAISGen.InsertAISSectionLoad((UInt32) section.loadAddr, (UInt32) section.size, secData); } // Add this section's memory range, checking for overlap AddMemoryRange(devAISGen, (UInt32) section.loadAddr, (UInt32) (section.loadAddr+section.size-1)); return retType.SUCCESS; }
public Context CreateContext(ObjectFile objectfile) { Contract.Requires<ArgumentNullException>(objectfile != null); Contract.Ensures(Contract.Result<Context>() != null); return default(Context); }
private static void openObjFile(String file_name, out ObjectFile obj_file) { if (ElfFile.IsElfFile(file_name)) obj_file = new ElfFile(file_name); else if (CoffFile.IsCoffFile(file_name)) obj_file = new CoffFile(file_name); else throw new Exception("File " + file_name + " is not a valid object file."); }
/// <inheritdoc /> public override void VisitObjectFile(ObjectFile objectFile) { switch (objectFile.Architecture.AddressSize) { case DataSize.Bit16: Writer.WriteLine("[BITS 16]"); break; case DataSize.Bit32: Writer.WriteLine("[BITS 32]"); break; case DataSize.Bit64: Writer.WriteLine("[BITS 64]"); break; default: throw new LanguageException("The object file's architecture address size is not supported " + "by this language."); } // Visit the sections. base.VisitObjectFile(objectFile); }
/// <inheritdoc /> public ObjectFileAssembler CreateAssembler(ObjectFile objectFile) { return new BinObjectFileAssembler(objectFile); }
public ObjectFileAssembler CreateAssembler(ObjectFile objectFile) { Contract.Requires<ArgumentNullException>(objectFile != null); Contract.Ensures(Contract.Result<ObjectFileAssembler>() != null); return default(ObjectFileAssembler); }