public void Unload() { // cut off the LRU cache LruCache = LruCache.GetRange(0, Math.Min(LruCache.Count, MaxBinaryCount)); foreach (var CachedBinary in Directory.EnumerateFiles(BinaryCacheFolderPath)) { string PeHash = GetBinaryHash(CachedBinary); if (LruCache.Find(Hash => (Hash == PeHash)) == null) { // Force map unloading before deleting file if (BinaryDatabase.ContainsKey(PeHash)) { BinaryDatabase[PeHash].Unload(); } try { File.Delete(CachedBinary); } catch (System.UnauthorizedAccessException uae) { // The BinaryCache is shared among serveral Dependencies.exe instance // so only the last one alive can clear the cache. Debug.WriteLine("[BinaryCache] Could not unload file {0:s} : {1:s} ", CachedBinary, uae); } } } // flush the cache BinaryDatabase.Clear(); FilepathDatabase.Clear(); }
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); }