/// <summary>
        /// Checks for changes in the dependency file.
        /// </summary>
        /// <returns><c>true</c> if a file has been updated, <c>false</c> otherwise</returns>
        public bool CheckForChanges()
        {
            // No files? Then it is considered as changed.
            if (Count == 0)
            {
                return(true);
            }

            foreach (var fileItem in this)
            {
                if (!File.Exists(fileItem.Key))
                {
                    return(true);
                }

                var fileTime = NativeFile.GetLastWriteTime(fileItem.Key);

                if (fileItem.Value != fileTime)
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #2
0
        public void DeleteBundles(Func <string, bool> bundleFileDeletePredicate)
        {
            var bundleFiles = VirtualFileSystem.ListFiles(vfsBundleDirectory, "*" + BundleExtension, VirtualSearchOption.TopDirectoryOnly).Result;

            // Group incremental bundles together
            var bundleFilesGroups = bundleFiles.GroupBy(bundleUrl =>
            {
                // Remove incremental ID from bundle url
                ObjectId incrementalId;
                var filename = VirtualFileSystem.GetFileName(bundleUrl);
                var bundleExtensionLength = filename.EndsWith(BundleExtension) ? BundleExtension.Length : 0;
                if (filename.Length - bundleExtensionLength >= ObjectId.HashStringLength + 1 && filename[filename.Length - bundleExtensionLength - ObjectId.HashStringLength - 1] == '.' &&
                    ObjectId.TryParse(filename.Substring(filename.Length - bundleExtensionLength - ObjectId.HashStringLength, ObjectId.HashStringLength), out incrementalId))
                {
                    bundleUrl = bundleUrl.Remove(bundleUrl.Length - bundleExtensionLength - ObjectId.HashStringLength - 1, 1 + ObjectId.HashStringLength);
                }

                return(bundleUrl);
            });

            foreach (var bundleFilesInGroup in bundleFilesGroups)
            {
                var bundleMainFile = VirtualFileSystem.GetAbsolutePath(bundleFilesInGroup.Key);

                if (bundleFileDeletePredicate(bundleMainFile))
                {
                    foreach (var bundleRealFile in bundleFilesInGroup)
                    {
                        NativeFile.FileDelete(VirtualFileSystem.GetAbsolutePath(bundleRealFile));
                    }
                }
            }
        }
Beispiel #3
0
        /// <inheritdoc/>
        public override void Initialize(EffectContext effectContext, TransformGraph transformGraph)
        {
            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            effectContext.LoadPixelShader(GUID_RipplePixelShader, NativeFile.ReadAllBytes(path + "\\Ripple.cso"));
            transformGraph.SetSingleTransformNode(this);
        }
        public void InitializeView()
        {
            if (!NativeFile.Exists(this.Filename))
            {
                MessageBox.Show(
                    String.Format("{0:s} is not present on the disk", this.Filename),
                    "Invalid PE",
                    MessageBoxButton.OK
                    );

                return;
            }

            this.Pe = (Application.Current as App).LoadBinary(this.Filename);
            if (this.Pe == null || !this.Pe.LoadSuccessful)
            {
                MessageBox.Show(
                    String.Format("{0:s} is not a valid PE-COFF file", this.Filename),
                    "Invalid PE",
                    MessageBoxButton.OK
                    );

                return;
            }

            this.SymPrv                = new PhSymbolProvider();
            this.RootFolder            = Path.GetDirectoryName(this.Filename);
            this.SxsEntriesCache       = SxsManifest.GetSxsEntries(this.Pe);
            this.ProcessedModulesCache = new ModulesCache();
            this.ApiSetmapCache        = Phlib.GetApiSetSchema();
            this._SelectedModule       = null;
            this._DisplayWarning       = false;

            // TODO : Find a way to properly bind commands instead of using this hack
            this.ModulesList.Items.Clear();
            this.ModulesList.DoFindModuleInTreeCommand   = DoFindModuleInTree;
            this.ModulesList.ConfigureSearchOrderCommand = ConfigureSearchOrderCommand;

            var RootFilename = Path.GetFileName(this.Filename);
            var RootModule   = new DisplayModuleInfo(RootFilename, this.Pe, ModuleSearchStrategy.ROOT);

            this.ProcessedModulesCache.Add(new ModuleCacheKey(RootFilename, this.Filename), RootModule);

            ModuleTreeViewItem    treeNode             = new ModuleTreeViewItem();
            DependencyNodeContext childTreeInfoContext = new DependencyNodeContext()
            {
                ModuleInfo = new WeakReference(RootModule),
                IsDummy    = false
            };

            treeNode.DataContext = childTreeInfoContext;
            treeNode.Header      = treeNode.GetTreeNodeHeaderName(Dependencies.Properties.Settings.Default.FullPath);
            treeNode.IsExpanded  = true;

            this.DllTreeView.Items.Clear();
            this.DllTreeView.Items.Add(treeNode);

            // Recursively construct tree of dll imports
            ConstructDependencyTree(treeNode, this.Pe);
        }
 public void AddDependencyPath(string filePath)
 {
     if (!ContainsKey(filePath))
     {
         Add(filePath, NativeFile.GetLastWriteTime(filePath));
     }
 }
            static void Main(string[] args)
            {
                bool            is_verbose     = false;
                bool            show_help      = false;
                CLRPH_DEMANGLER demangler_name = CLRPH_DEMANGLER.Default;

                OptionSet opts = new OptionSet()
                {
                    { "v|verbose", "redirect debug traces to console", v => is_verbose = v != null },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                    { "d=|demangler=", "Choose demangler name", v => demangler_name = ParseDemanglerName(v) },
                };

                List <string> eps = opts.Parse(args);

                if (show_help)
                {
                    ShowHelp(opts);
                    return;
                }

                if (is_verbose)
                {
                    // Redirect debug log to the console
                    Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
                    Debug.AutoFlush = true;
                }

                // always the first call to make
                Phlib.InitializePhLib();
                Demangler demangler;

                switch (args.Length)
                {
                case 0:
                    demangler = new Demangler(CLRPH_DEMANGLER.Microsoft);
                    TestKnownInputs(demangler);
                    break;

                default:
                case 1:
                    demangler = new Demangler(demangler_name);
                    string Filepath = args[1];

                    if (NativeFile.Exists(Filepath))
                    {
                        TestFilepath(Filepath, demangler);
                    }
                    else
                    {
                        string undecoratedName = demangler.UndecorateName(args[1]).Item2;
                        Console.WriteLine(undecoratedName);
                    }

                    break;
                }

                // Force flushing out buffer
                Console.Out.Flush();
            }
Beispiel #7
0
        public IList <DirectoryEntry> GetDirectoryEntries(FullPath path)
        {
            var list = NativeFile.GetDirectoryEntries(path.Value);

            // Skip any entry that is longer than MAX_PATH.
            // Fix this once we fully support the long path syntax ("\\?\" prefix)
            if (list.Any(entry => PathHelpers.IsPathTooLong(path.Value, entry.Name)))
            {
                return(list.Where(entry => {
                    if (PathHelpers.IsPathTooLong(path.Value, entry.Name))
                    {
                        // Note: The condition is unsafe from a pure concurrency point of view,
                        //       but is ok in this case because the field is incrementally increasing.
                        //       This is just an optimization to avoid an Interlocked call.
                        if (_pathTooLongErrorCount <= MaxPathTooLogLogCount)
                        {
                            var logCount = Interlocked.Increment(ref _pathTooLongErrorCount);
                            if (logCount <= MaxPathTooLogLogCount)
                            {
                                Logger.LogInfo("Skipping directory entry because path is too long: \"{0}\"",
                                               path.Combine(new RelativePath(entry.Name)));
                            }
                            if (logCount == MaxPathTooLogLogCount)
                            {
                                Logger.LogInfo("  (Note: No more message abount path too long will be logged, because the maximum number of occurrences has been reached)");
                            }
                        }
                        return false;
                    }
                    return true;
                }).ToList());
            }
            return(list);
        }
Beispiel #8
0
        public static void Main(string[] args)
        {
            string inputFile         = "http://www.dev-c.com/nativedb/natives.json";
            string outputFile        = "NativeHashes.txt";
            bool   withUnnamedHashes = false;

            if (args.Length == 1)
            {
                outputFile = args[0];
            }
            if (args.Length == 2)
            {
                inputFile  = args[0];
                outputFile = args[1];
            }

            using (var wc = new WebClient())
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                Console.WriteLine("Downloading natives.json");
                wc.Headers.Add("Accept-Encoding: gzip, deflate, sdch");

                string nativeFileRaw  = Decompress(wc.DownloadData(inputFile));
                string nativeTemplate = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NativeTemplate.txt"));

                NativeFile    nativeFile    = JsonConvert.DeserializeObject <NativeFile>(nativeFileRaw);
                StringBuilder resultBuilder = new StringBuilder();

                foreach (string nativeNamespaceKey in nativeFile.Keys)
                {
                    Console.WriteLine("Processing " + nativeNamespaceKey);
                    NativeNamespace nativeNamespace = nativeFile[nativeNamespaceKey];

                    resultBuilder.AppendLine("			/*");
                    resultBuilder.AppendLine("				"+ nativeNamespaceKey);
                    resultBuilder.AppendLine("			*/");

                    foreach (string nativeFuncKey in nativeNamespace.Keys)
                    {
                        NativeFunction nativeFunction = nativeNamespace[nativeFuncKey];

                        if (!string.IsNullOrEmpty(nativeFunction.Name))
                        {
                            resultBuilder.AppendLine("			"+ nativeFunction.Name + " = " + nativeFuncKey + ", // " + nativeFunction.JHash);
                        }
                        else if (withUnnamedHashes)
                        {
                            resultBuilder.AppendLine("			_"+ nativeFuncKey + " = " + nativeFuncKey + ", // " + nativeFunction.JHash);
                        }
                    }
                }

                File.WriteAllText(outputFile, string.Format(nativeTemplate, resultBuilder));

                Console.WriteLine("Finished generating native hash enum");
            }
        }
Beispiel #9
0
        public PE GetBinary(string PePath)
        {
            Debug.WriteLine(String.Format("Attempt to load : {0:s}", PePath), "BinaryCache");

            if (!NativeFile.Exists(PePath))
            {
                Debug.WriteLine(String.Format("File not present on the filesystem : {0:s} ", PePath), "BinaryCache");
                return(null);
            }

            string Fullpath = Path.GetFullPath(PePath);

            if (FilepathDatabase.ContainsKey(Fullpath))
            {
                // TODO : update LRU cache
                PE sShadowBinary = FilepathDatabase[Fullpath];
                sShadowBinary.Filepath = Fullpath;
                return(sShadowBinary);
            }

            string PeHash = GetBinaryHash(PePath);

            Debug.WriteLine(String.Format("File {0:s} hash : {1:s} ", PePath, PeHash), "BinaryCache");

            // A sync lock is mandatory here in order not to load twice the
            // same binary from two differents workers
            lock (BinaryDatabaseLock)
            {
                bool hit = BinaryDatabase.ContainsKey(PeHash);

                // Cache "miss"
                if (!hit)
                {
                    string DestFilePath = Path.Combine(BinaryCacheFolderPath, PeHash);
                    if (!File.Exists(DestFilePath) && (DestFilePath != PePath))
                    {
                        Debug.WriteLine(String.Format("FileCopy from {0:s} to {1:s}", PePath, DestFilePath), "BinaryCache");
                        NativeFile.Copy(PePath, DestFilePath);
                    }

                    PE NewShadowBinary = new PE(DestFilePath);
                    NewShadowBinary.Load();

                    LruCache.Add(PeHash);
                    BinaryDatabase.Add(PeHash, NewShadowBinary);
                    FilepathDatabase.Add(Fullpath, NewShadowBinary);
                }
            }

            // Cache "Hit"
            UpdateLru(PeHash);
            PE ShadowBinary = BinaryDatabase[PeHash];

            ShadowBinary.Filepath = Path.GetFullPath(PePath); // convert any paths to an absolute one.

            Debug.WriteLine(String.Format("File {0:s} loaded from {1:s}", PePath, Path.Combine(BinaryCacheFolderPath, PeHash)), "BinaryCache");
            return(ShadowBinary);
        }
        public static bool IsChromiumSourceDirectory(FullPathName path, IPathPatternsFile chromiumEnlistmentPatterns)
        {
            // We need to ensure that all pattern lines are covered by at least one file/directory of |path|.
            IList <string> directories;
            IList <string> files;

            NativeFile.GetDirectoryEntries(path.FullName, out directories, out files);
            return(chromiumEnlistmentPatterns.GetPathMatcherLines()
                   .All(item => MatchFileOrDirectory(item, directories, files)));
        }
Beispiel #11
0
        public void CheckFileExists()
        {
            var testFile = "test.txt";

            File.Delete(testFile);
            Assert.False(NativeFile.Exists(testFile));
            File.WriteAllText(testFile, string.Empty);
            Assert.True(NativeFile.Exists(testFile));
            File.Delete(testFile);
        }
Beispiel #12
0
        public void TestLoadVtfImage()
        {
            //var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\mudground001_height-ssbump.vtf");
            //var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\dirtroad001a.vtf");
            //var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\rockground001.vtf");
            //var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\class_demo_dudv.vtf");
            var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\cubemap_gold001.hdr.vtf");
            //var file = new NativeFile(@"D:\Github\Chisel\_Resources\VTF\800corner.vtf");
            var image = VtfProvider.GetImage(file);

            image.Save(@"D:\Github\Chisel\_Resources\VTF\_test2.png");
        }
        public Stream Open(IncludeType type, string fileName, Stream parentStream)
        {
            Debug.WriteLine(fileName);

            // Include dynamic (:D) constants
            if (fileName.ToLower().Equals("raymarchengine"))
            {
                return(GetShaderConstantsStream());
            }

            string currentDirectory = CurrentDirectory.Peek();

            if (currentDirectory == null)
            {
#if NETFX_CORE
                currentDirectory = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
#else
                currentDirectory = Environment.CurrentDirectory;
#endif
            }

            string filePath = fileName;

            if (!Path.IsPathRooted(filePath))
            {
                var directoryToSearch = new List <string> {
                    currentDirectory
                };
                directoryToSearch.AddRange(IncludeDirectories);
                foreach (string dirPath in directoryToSearch)
                {
                    string selectedFile = Path.GetFullPath(Path.Combine(dirPath, fileName));
                    if (NativeFile.Exists(selectedFile))
                    {
                        filePath = selectedFile;
                        break;
                    }
                }
            }

            if (filePath == null || !NativeFile.Exists(filePath))
            {
                throw new FileNotFoundException(String.Format("Unable to find file [{0}]", filePath ?? fileName));
            }

            NativeFileStream fs = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read);
            CurrentDirectory.Push(Path.GetDirectoryName(filePath));
            return(fs);
        }
Beispiel #14
0
        public static void Start()
        {
            MapProvider.Register(new RmfProvider());
            MapProvider.Register(new VmfProvider());
            GameDataProvider.Register(new FgdProvider());
            TextureProvider.Register(new WadProvider());

            // var editor = new Editor.Editor();
            // editor.Load += (sender, e) => PostStart(sender as Editor.Editor);
            // Application.Run(editor);
            // var settings = Context.DBContext.GetAllSettings().ToDictionary(x => x.Key, x => x.Value);
            // Serialise.DeserialiseSettings(settings);
            // var settingsform = new Editor.Settings.SettingsForm();
            // Application.Run(settingsform);

            // var map = MapProvider.GetMapFromFile(MapFile);
            // Document.Game = Game;
            // Document.Map = map;
            // Document.GameData = GameDataProvider.GetGameDataFromFiles(Game.Fgds.Select(f => f.Path));
            // var entity = new EntityEditor();
            // entity.Objects.AddRange(map.WorldSpawn.Children.OfType<Entity>().Take(1));
            // Application.Run(entity);

            /*
             * var nat = new NativeFile(new DirectoryInfo(@"F:\Steam\steamapps\common\Half-Life"));
             * var gcf1 = new GcfFile(@"F:\Steam\steamapps\half-life.gcf");
             * var gcf2 = new GcfFile(@"F:\Steam\steamapps\half-life engine.gcf");
             * //var gcf3 = new GcfFile(@"F:\Steam\steamapps\half-life base content.gcf");
             * var gcf4 = new GcfFile(@"F:\Steam\steamapps\platform.gcf");
             * var com = new CompositeFile(null, new IFile[] { nat, gcf1, gcf2, gcf4 });
             */
            var nat = new NativeFile(new DirectoryInfo(@"F:\Half-Life WON"));
            var com = new CompositeFile(null, new[]
            {
                new NativeFile(new DirectoryInfo(@"F:\Half-Life WON\valve")),
                new NativeFile(new DirectoryInfo(@"F:\Half-Life WON\tfc")),
            });
            //var pak = new PakFile(@"F:\Half-Life WON\valve\pak0.pak");
            // var vir = new VirtualFile(null, "valve", new[] {pak});
            //var com = new CompositeFile(null, new IFile[] { nat, vir });
            var fsb = new FileSystemBrowserControl {
                Dock = DockStyle.Fill, File = com
            };                                                                         //, FilterText = "WAD Files", Filter = "*.wad"};
            var form = new Form {
                Controls = { fsb }, Width = 500, Height = 500
            };

            Application.Run(form);
        }
        private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            if (this.DllTreeView.SelectedItem == null)
            {
                UpdateImportExportLists(null, null);
                return;
            }

            DependencyNodeContext childTreeContext = ((DependencyNodeContext)(this.DllTreeView.SelectedItem as ModuleTreeViewItem).DataContext);
            DisplayModuleInfo     SelectedModule   = childTreeContext.ModuleInfo.Target as DisplayModuleInfo;

            if (SelectedModule == null)
            {
                return;
            }

            // Selected Pe has not been found on disk : unvalidate current module
            SelectedModule.HasErrors = !NativeFile.Exists(SelectedModule.Filepath);
            if (SelectedModule.HasErrors)
            {
                // TODO : do a proper refresh instead of asking the user to do it
                System.Windows.MessageBox.Show(String.Format("We could not find {0:s} file on the disk anymore, please fix this problem and refresh the window via F5", SelectedModule.Filepath));
            }

            // Root Item : no parent
            ModuleTreeViewItem TreeRootItem = this.DllTreeView.Items[0] as ModuleTreeViewItem;
            ModuleTreeViewItem SelectedItem = this.DllTreeView.SelectedItem as ModuleTreeViewItem;

            if (SelectedItem == TreeRootItem)
            {
                // Selected Pe has not been found on disk : unvalidate current module
                if (SelectedModule.HasErrors)
                {
                    UpdateImportExportLists(null, null);
                }
                else
                {
                    SelectedModule.HasErrors = false;
                    UpdateImportExportLists(SelectedModule, null);
                }

                return;
            }

            // Tree Item
            DisplayModuleInfo parentModule = SelectedItem.ParentModule.ModuleInfo;

            UpdateImportExportLists(SelectedModule, parentModule);
        }
Beispiel #16
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string Filepath = (string)value;
            Icon   icon     = ShellIcon.GetSmallIcon(Filepath);

            if (NativeFile.Exists(Filepath) && (icon != null))
            {
                return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                           icon.Handle,
                           new Int32Rect(0, 0, icon.Width, icon.Height),
                           BitmapSizeOptions.FromEmptyOptions()));
            }

            return("Images/Question.png");
        }
Beispiel #17
0
        protected string GetBinaryHash(string PePath)
        {
            // Compute checksum only on first 1 KB of file data
            // in order not to spend too much CPU cycles here.
            // Hopefully there is enough entropy in PE headers
            // not to trigger too many collisions.
            //using (FileStream stream = File.OpenRead(PePath))
            //{
            //    var sha = new SHA256Managed();
            //    byte[] buffer = new byte[1024];

            //    stream.Read(buffer, 0, buffer.Length);
            //    byte[] checksum = sha.ComputeHash(buffer, 0, buffer.Length);
            //    return BitConverter.ToString(checksum).Replace("-", String.Empty);
            //}
            return(NativeFile.GetPartialHashFile(PePath, 1024));
        }
Beispiel #18
0
        protected virtual void Initialize()
        {
            const string filePath   = Global.DataPath + "System.yaml";
            const string references = "EngineReferences";

            if (!NativeFile.Exists(filePath))
            {
                throw new InvalidOperationException(string.Format("Odyssey System Data not found: check if {0} exists", filePath));
            }

            contentManager.LoadAssetList(filePath);

            var refData = contentManager.Load <EngineReferenceCollection>(references);

            services.AddService(typeof(IReferenceService), refData);
            SetupDeviceEvents();
        }
        public Stream Resolve(string assetName)
        {
            try
            {
                var assetPath = GetAssetPath(assetName);
                if (!NativeFile.Exists(assetPath))
                {
                    assetPath = GetAssetPath(assetName, true);
                }

                return(new NativeFileStream(assetPath, NativeFileMode.Open, NativeFileAccess.Read));
            }
            catch
            {
                return(null);
            }
        }
Beispiel #20
0
        private void InitTextWindow()
        {
            UIScrollWindow textWindow = new UIScrollWindow();

            textWindow.Position = new Vector2(300, 300);
            textWindow.ScrollPanel.Restriction = ScrollRestriction.Vertical;
            textWindow.Size = new Vector2(0, 180);
            textWindow.AddConstraint(Edge.Bottom, null, Edge.Bottom, 5);
            textWindow.AddConstraint(Edge.Horizontal, null, Edge.Horizontal, 5);

            string  text  = NativeFile.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Lorem Ipsum.txt"));
            UILabel label = new UILabel(text, true);

            label.AddConstraint(Edge.TopLeft, textWindow.ScrollPanel, Edge.TopLeft, ConstraintCategory.Initialization);
            label.AddConstraint(Edge.Right, textWindow.ScrollPanel, Edge.Right, ConstraintCategory.Initialization);
            textWindow.AddChild(label);

            uiManager.Add(textWindow);
        }
Beispiel #21
0
        //EffectContext _effectContext;
        public override void Initialize(EffectContext effectContext, TransformGraph transformGraph)
        {
            //WARNING : as soon as TransformGraph.SetSingleTransformNode is called it chain calls the
            //SetDrawInformation via a callbac. Unfortunately this is too early because the code below
            //within this method is used to populate stateful data needed by the SetDrawInformation call.
            //transformGraph.SetSingleTransformNode(this);

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            byte[] vertexShaderBytecode = NativeFile.ReadAllBytes(path + "\\WaveEffect.cso");
            effectContext.LoadVertexShader(GUID_WaveVertexShader, vertexShaderBytecode);

            // Only generate the vertex buffer if it has not already been initialized.
            vertexBuffer = effectContext.FindVertexBuffer(GUID_WaveVertexBuffer);

            if (vertexBuffer == null)
            {
                //InitializeVertexBuffer(effectContext);

                var mesh = GenerateMesh();

                // Updating geometry every time the effect is rendered can be costly, so it is
                // recommended that vertex buffer remain static if possible (which it is in this
                // sample effect).
                using (var stream = DataStream.Create(mesh, true, true))
                {
                    var vbProp = new VertexBufferProperties(1, VertexUsage.Static, stream);

                    var cvbProp = new CustomVertexBufferProperties(vertexShaderBytecode, new[] {
                        new InputElement("MESH_POSITION", 0, SharpDX.DXGI.Format.R32G32_Float, 0, 0),
                    }, Utilities.SizeOf <Vector2>());

                    // The GUID is optional, and is provided here to register the geometry globally.
                    // As mentioned above, this avoids duplication if multiple versions of the effect
                    // are created.
                    vertexBuffer = new VertexBuffer(effectContext, GUID_WaveVertexBuffer, vbProp, cvbProp);
                }
            }

            PrepareForRender(ChangeType.Properties | ChangeType.Context);
            transformGraph.SetSingleTransformNode(this);
        }
        public static void Main(string[] args)
        {
            using (WebClient wc = new WebClient())
            {
                Console.WriteLine("Downloading natives.json");
                wc.Headers.Add("Accept-Encoding: gzip, deflate, sdch");

                string nativeFileRaw  = Decompress(wc.DownloadData("http://www.dev-c.com/nativedb/natives.json"));
                string nativeTemplate = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NativeTemplate.txt"));

                NativeFile    nativeFile    = JsonConvert.DeserializeObject <NativeFile>(nativeFileRaw);
                StringBuilder resultBuilder = new StringBuilder();

                foreach (string nativeNamespaceKey in nativeFile.Keys)
                {
                    Console.WriteLine("Processing " + nativeNamespaceKey);
                    NativeNamespace nativeNamespace = nativeFile[nativeNamespaceKey];

                    resultBuilder.AppendLine("			/*");
                    resultBuilder.AppendLine("				"+ nativeNamespaceKey);
                    resultBuilder.AppendLine("			*/");

                    foreach (string nativeFuncKey in nativeNamespace.Keys)
                    {
                        NativeFunction nativeFunction = nativeNamespace[nativeFuncKey];

                        if (!string.IsNullOrEmpty(nativeFunction.Name))
                        {
                            resultBuilder.AppendLine("			"+ nativeFunction.Name + " = " + nativeFuncKey + ", // " + nativeFunction.JHash);
                        }
                    }
                }

                string outputFile = args.Length > 0 ? args[0] : "NativeHashes.hpp";

                File.WriteAllText(outputFile, string.Format(nativeTemplate, resultBuilder));

                Console.WriteLine("Finished generating native hash enum");
            }
        }
        public PE GetBinary(string PePath)
        {
            if (!NativeFile.Exists(PePath))
            {
                return(null);
            }

            string PeHash = GetBinaryHash(PePath);


            // A sync lock is mandatory here in order not to load twice the
            // same binary from two differents workers
            lock (BinaryDatabaseLock)
            {
                bool hit = BinaryDatabase.ContainsKey(PeHash);

                // Cache "miss"
                if (!hit)
                {
                    string DestFilePath = Path.Combine(BinaryCacheFolderPath, PeHash);
                    if (!File.Exists(DestFilePath) && (DestFilePath != PePath))
                    {
                        NativeFile.Copy(PePath, DestFilePath);
                    }

                    PE NewShadowBinary = new PE(DestFilePath);
                    NewShadowBinary.Load();

                    LruCache.Add(PeHash);
                    BinaryDatabase.Add(PeHash, NewShadowBinary);
                }
            }

            // Cache "Hit"
            UpdateLru(PeHash);
            PE ShadowBinary = BinaryDatabase[PeHash];

            ShadowBinary.Filepath = Path.GetFullPath(PePath); // convert any paths to an absolute one.
            return(ShadowBinary);
        }
Beispiel #24
0
        public Stream Open(IncludeType type, string fileName, Stream parentStream)
        {
            var currentDirectory = CurrentDirectory.Peek();

            if (currentDirectory == null)
#if NETFX_CORE
            { currentDirectory = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; }
#else
            { currentDirectory = Environment.CurrentDirectory; }
#endif

            var filePath = fileName;

            if (!Path.IsPathRooted(filePath))
            {
                var directoryToSearch = new List <string> {
                    currentDirectory
                };
                directoryToSearch.AddRange(IncludeDirectories);
                foreach (var dirPath in directoryToSearch)
                {
                    var selectedFile = Path.Combine(dirPath, fileName);
                    if (NativeFile.Exists(selectedFile))
                    {
                        filePath = selectedFile;
                        break;
                    }
                }
            }

            if (filePath == null || !NativeFile.Exists(filePath))
            {
                throw new FileNotFoundException(String.Format("Unable to find file [{0}]", filePath ?? fileName));
            }

            NativeFileStream fs = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read);
            CurrentDirectory.Push(Path.GetDirectoryName(filePath));
            return(fs);
        }
Beispiel #25
0
            static void Main(string[] args)
            {
                // always the first call to make
                Phlib.InitializePhLib();

                Demangler demangler;

                switch (args.Length)
                {
                case 0:
                    demangler = new Demangler("Microsoft");
                    TestKnownInputs(demangler);
                    break;

                case 1:
                    demangler = new Demangler();
                    TestFilepath(args[0], demangler);

                    break;

                default:
                case 2:
                    string demanglerName = args[0].TrimStart(new char[] { '-' });
                    string Filepath      = args[1];

                    demangler = new Demangler(demanglerName);
                    if (NativeFile.Exists(Filepath))
                    {
                        TestFilepath(Filepath, demangler);
                    }
                    else
                    {
                        Console.WriteLine(demangler.UndecorateName(args[1]));
                    }

                    break;
                }
            }
Beispiel #26
0
        public PE LoadBinary(string path)
        {
            StatusBarMessage = String.Format("Loading module {0:s} ...", path);

            if (!NativeFile.Exists(path))
            {
                StatusBarMessage = String.Format("Loading PE file \"{0:s}\" failed : file not present on disk.", path);
                return(null);
            }

            PE pe = BinaryCache.LoadPe(path);

            if (pe == null || !pe.LoadSuccessful)
            {
                StatusBarMessage = String.Format("Loading module {0:s} failed.", path);
            }
            else
            {
                StatusBarMessage = String.Format("Loading PE file \"{0:s}\" successful.", pe.Filepath);
            }

            return(pe);
        }
Beispiel #27
0
        private static string GetApplicationCacheDirectory()
        {
#if SILICONSTUDIO_PLATFORM_ANDROID
            var directory = Path.Combine(PlatformAndroid.Context.FilesDir.AbsolutePath, "cache");
            Directory.CreateDirectory(directory);
            return(directory);
#elif SILICONSTUDIO_PLATFORM_WINDOWS_STORE
            var directory = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "cache");
            NativeFile.DirectoryCreate(directory);
            return(directory);
#elif SILICONSTUDIO_PLATFORM_WINDOWS_PHONE
            return(Windows.Storage.ApplicationData.Current.LocalCacheFolder.Path);
#elif SILICONSTUDIO_PLATFORM_IOS
            var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Library", "Caches");
            Directory.CreateDirectory(directory);
            return(directory);
#else
            // TODO: Should we add "local" ?
            var directory = Path.Combine(GetApplicationBinaryDirectory(), "cache");
            Directory.CreateDirectory(directory);
            return(directory);
#endif
        }
Beispiel #28
0
        protected List <ModelReference> LoadAllModels(IEnumerable <string> modelDirs)
        {
            List <ModelReference> models = new List <ModelReference>();

            foreach (string dir in modelDirs)
            {
                string[] files = Directory.GetFiles(dir);
                foreach (string modelPath in files)
                {
                    NativeFile file = null;
                    if (!string.IsNullOrEmpty(modelPath))
                    {
                        file = new NativeFile(modelPath);
                    }
                    if (file == null || !ModelProvider.CanLoad(file))
                    {
                        continue;
                    }

#if !DEBUG
                    try
                    {
#endif
                    var mr = ModelProvider.CreateModelReference(file);
                    models.Add(mr);
#if !DEBUG
                }
                catch (Exception)
                {
                    // Couldn't load
                    continue;
                }
#endif
                }
            }
            return(models);
        }
Beispiel #29
0
        public void DeleteBundles(Func <string, bool> bundleFileDeletePredicate)
        {
            var bundleFiles = VirtualFileSystem.ListFiles(vfsBundleDirectory, "*.bundle", VirtualSearchOption.TopDirectoryOnly).Result;

            // Obsolete: Android used to have .bundle.mp3 to avoid compression. Still here so that they get deleted on next build.
            // This can be removed later.
            bundleFiles = bundleFiles.Union(VirtualFileSystem.ListFiles(vfsBundleDirectory, "*.mp3", VirtualSearchOption.TopDirectoryOnly).Result).ToArray();

            foreach (var bundleFile in bundleFiles)
            {
                var bundleRealFile = VirtualFileSystem.GetAbsolutePath(bundleFile);

                // Remove ".mp3" (Android only)
                if (bundleRealFile.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase))
                {
                    bundleRealFile = bundleRealFile.Substring(0, bundleRealFile.Length - 4);
                }

                if (bundleFileDeletePredicate(bundleRealFile))
                {
                    NativeFile.FileDelete(bundleRealFile);
                }
            }
        }
Beispiel #30
0
        private FileContents ReadFile(FullPathName fullName)
        {
            try {
                var       fileInfo          = new SlimFileInfo(fullName);
                const int trailingByteCount = 2;
                var       block             = NativeFile.ReadFileNulTerminated(fileInfo, trailingByteCount);
                var       contentsByteCount = (int)block.ByteLength - trailingByteCount; // Padding added by ReadFileNulTerminated
                var       kind = NativeMethods.Text_GetKind(block.Pointer, contentsByteCount);

                switch (kind)
                {
                case NativeMethods.TextKind.Ascii:
                    return(new AsciiFileContents(new FileContentsMemory(block, 0, contentsByteCount), fileInfo.LastWriteTimeUtc));

                case NativeMethods.TextKind.AsciiWithUtf8Bom:
                    const int utf8BomSize = 3;
                    return(new AsciiFileContents(new FileContentsMemory(block, utf8BomSize, contentsByteCount - utf8BomSize), fileInfo.LastWriteTimeUtc));

                case NativeMethods.TextKind.Utf8WithBom:
                    var utf16Block = Conversion.UTF8ToUnicode(block);
                    block.Dispose();
                    return(new UTF16FileContents(new FileContentsMemory(utf16Block, 0, utf16Block.ByteLength), fileInfo.LastWriteTimeUtc));

                case NativeMethods.TextKind.Unknown:
                default:
                    // TODO(rpaquay): Figure out a better way to detect encoding.
                    //Logger.Log("Text Encoding of file \"{0}\" is not recognized.", fullName);
                    return(new AsciiFileContents(new FileContentsMemory(block, 0, contentsByteCount), fileInfo.LastWriteTimeUtc));
                    //throw new NotImplementedException(string.Format("Text Encoding of file \"{0}\" is not recognized.", fullName));
                }
            }
            catch (Exception e) {
                Logger.LogException(e, "Error reading content of text file \"{0}\", skipping file.", fullName);
                return(StringFileContents.Empty);
            }
        }
Beispiel #31
0
    private void DoInterfaces(StringBuilder buffer, NativeFile file)
    {
        for (int i = 0; i < file.Interfaces.Count; ++i)
        {
            m_interface = file.Interfaces[i];

            if (m_interface.Name != "NSOpenGLLayer")	// NSOpenGLLayer relies on CAOpenGLLayer whichis in quartz, not appkit...
            {
                m_buffer = new StringBuilder();
                if (i > 0)
                    DoWrite();

                if (m_objects.KnownType(m_interface.Name))
                {
                    DoWriteInterfaceHeader();
                    DoGenerateMethods();
                    DoWriteInterfaceTrailer();

                    buffer.Append(m_buffer.ToString());
                }
                else
                    Console.Error.WriteLine("Ignoring {0} ({1} isn't a known type)", m_interface, m_interface.Name);
            }
        }
    }
Beispiel #32
0
    private void DoEnums(StringBuilder buffer, NativeFile file)
    {
        m_buffer = buffer;

        for (int k = 0; k < file.Enums.Count; ++k)
        {
            NativeEnum value = file.Enums[k];

            if (value.Name != null)
            {
                DoWrite("	/// <exclude/>");
                DoWrite("	[Serializable]");
                string backing = value.Values.Any(v => v.Contains("1U ")) ? " : uint" : string.Empty;
                DoWrite("	public enum {0}{1}", value.Name, backing);
                DoWrite("	{");
                for (int i = 0; i < value.Names.Length; ++i)
                {
                    Blacklist black = m_blacklist.SingleOrDefault(b => b.Enum == value.Names[i]);
                    if (black == null)
                    {
                        if (value.Values[i].Length > 0)
                            DoWrite("		{0} = {1},", value.Names[i], DoMapEnumValue(value.Values[i]));
                        else
                            DoWrite("		{0},", value.Names[i]);
                    }
                }
            }
            else
            {
                DoWrite("	/// <exclude/>");
                DoWrite("	public partial class Enums");
                DoWrite("	{");

                int? v = 0;
                for (int i = 0; i < value.Names.Length; ++i)
                {
                    Blacklist black = m_blacklist.SingleOrDefault(b => b.Enum == value.Names[i]);
                    if (black == null)
                    {
                        if (value.Values[i].Length > 0)
                        {
                            string vv = DoMapEnumValue(value.Values[i].Trim());

                            int tmp;
                            if (vv.StartsWith("0x") && vv.Contains("ULL"))
                            {
                                DoWrite("		public const ulong {0} = {1};", value.Names[i], vv);
                                v = null;
                            }
                            else if (vv.StartsWith("0x") && vv.Length >= 10 && vv[2] >= '8')
                            {
                                if (vv.EndsWith("UL"))
                                    vv = vv.Substring(0, vv.Length - 2);

                                DoWrite("		public const uint {0} = {1};", value.Names[i], vv);
                                v = null;
                            }
                            else if (vv.Contains("0L") || vv.Contains("1L") || vv.Contains("2L") || vv.Contains("3L") || vv.Contains("4L") || vv.Contains("5L"))
                            {
                                DoWrite("		public const long {0} = {1};", value.Names[i], vv);
                            }
                            else if (vv.Contains("0UL") || vv.Contains("1UL") || vv.Contains("2UL") || vv.Contains("3UL") || vv.Contains("4UL") || vv.Contains("5UL"))
                            {
                                DoWrite("		public const ulong {0} = {1};", value.Names[i], vv);
                            }
                            else if (vv.Contains("0U") || vv.Contains("1U") || vv.Contains("2U") || vv.Contains("3U") || vv.Contains("4U") || vv.Contains("5U"))
                            {
                                DoWrite("		public const uint {0} = {1};", value.Names[i], vv);
                            }
                            else if (vv == "NSIntegerMax")
                            {
                                DoWrite("		public const int {0} = int.MaxValue;", value.Names[i]);
                                v = null;
                            }
                            else if (vv == "NSUIntegerMax")
                            {
                                DoWrite("		public const uint {0} = uint.MaxValue;", value.Names[i]);
                                v = null;
                            }
                            else if (value.Names[i] == "NSXMLNodePreserveAll")
                            {
                                DoWrite("		public const uint {0} = {1};", value.Names[i], vv);
                                v = null;
                            }
                            else
                            {
                                DoWrite("		public const int {0} = {1};", value.Names[i], vv);

                                if (int.TryParse(vv, out tmp))
                                    v = tmp + 1;
                                else
                                    v = null;
                            }
                        }
                        else if (v.HasValue)
                        {
                            DoWrite("		public const int {0} = {1};", value.Names[i], v.Value);
                            v = v.Value + 1;
                        }
                        else
                            throw new Exception(string.Format("Couldn't compute a value for {0} in {1}", value.Names[i], m_inPath));
                    }
                }
            }

            DoWrite("	}");
            DoWrite("	");
        }
    }
Beispiel #33
0
    private void DoAddMethods(NativeFile file)
    {
        foreach (NativeInterface ni in file.Interfaces)
        {
            NativeInterface ri = ni;

            if (ni.Category == null)
            {
                m_objects.AddMethods(ri, ni.Methods);
            }
            else
            {
                if (m_objects.KnownType(ni.Name))
                {
                    ri = m_objects.FindInterface(ni.Name);
                    m_objects.AddMethods(ri, ni.Methods);
                }
                else
                    Console.Error.WriteLine("Ignoring the {0} category for interface {1} (can't find the interface).", ni.Category, ni.Name);
            }

            foreach (string p in ni.Protocols)
            {
                try
                {
                    NativeProtocol pp = m_objects.FindProtocol(p);
                    m_objects.AddMethods(ri, pp.Methods);
                }
                catch (ArgumentException)
                {
                    Console.Error.WriteLine("Not adding the {0} protocol methods to {1} (can't find the protocol).", p.Normalize(), ni.Name);
                }
            }
        }
    }
Beispiel #34
0
    // Header := S (ForwardReference / Enum / Extern / Inline / Interface / Protocol / Struct / Typedef)*;
    public void Header(XmlNode node, string path, bool emitting)
    {
        m_enums = new List<NativeEnum>();
        m_interfaces = new List<NativeInterface>();

        foreach (XmlNode child in node.ChildNodes)
        {
            // TODO: Would be nice to also handle extern and struct (here and in DoAnalyzeInterface).
            if ("Enum" == child.Name)
            {
                DoAnalyzeEnum(child);
            }
            else if ("Interface" == child.Name)
            {
                DoAnalyzeInterface(child);
            }
            else if ("Preprocessor" == child.Name && child.Attributes["alternative"].Value == "1")
            {
                DoAnalyzePreprocessor(child);
            }
            else if ("Protocol" == child.Name)
            {
                DoAnalyzeProtocol(child);
            }
            else if ("Struct" == child.Name)
            {
                DoAnalyzeStruct(child);
            }
            else if ("Typedef" == child.Name)
            {
                DoAnalyzeTypedef(child);
            }
        }

        var file = new NativeFile(path, m_enums, m_interfaces);
        if (m_knownFiles.Exists(f => f.Path == path))
            throw new Exception(path + " has already been parsed.");

        m_knownFiles.Add(file);
        if (emitting)
            m_objects.AddFile(file, m_interfaces);
    }