Skip to content

Commit 3b69ca7

Browse files
committed
Shared Cache: Add dependency files on bndb save
Fixes #8337
1 parent efbf4b4 commit 3b69ca7

4 files changed

Lines changed: 102 additions & 35 deletions

File tree

‎view/sharedcache/core/SharedCacheController.cpp‎

Lines changed: 80 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "SharedCacheController.h"
2+
#include "SharedCacheView.h"
23
#include "MachOProcessor.h"
34
#include "ObjC.h"
45

@@ -18,14 +19,14 @@ std::map<ViewId, DSCRef<SharedCacheController>>& GlobalControllers()
1819
return g_controllers;
1920
}
2021

21-
ViewId GetViewIdFromFileMetadata(const FileMetadata& file)
22+
ViewId GetViewIdFromFileMetadata(FileMetadata* file)
2223
{
2324
// Currently the view id is just the views session id.
2425
// NOTE: If we want more than one shared cache controller per view we would need to make this more unique.
25-
return file.GetSessionId();
26+
return file->GetSessionId();
2627
}
2728

28-
void DeleteController(const FileMetadata& file)
29+
void DeleteController(FileMetadata* file)
2930
{
3031
const auto id = GetViewIdFromFileMetadata(file);
3132
std::unique_lock<std::shared_mutex> lock(GlobalControllersMutex);
@@ -39,24 +40,16 @@ void DeleteController(const FileMetadata& file)
3940
LogWarnF("Deleting SharedCacheController for view {:#x}, but there are still {} references", id,
4041
controller->m_refs.load());
4142

43+
file->UnregisterNotification(controller);
4244
controllers.erase(it);
43-
LogDebugF("Deleted SharedCacheController for view {:?}", file.GetFilename().c_str());
45+
LogDebugF("Deleted SharedCacheController for view {:?}", file->GetFilename().c_str());
4446
}
4547
}
4648

47-
void RegisterSharedCacheControllerDestructor()
48-
{
49-
BNObjectDestructionCallbacks callbacks = {};
50-
callbacks.destructFileMetadata = [](void* ctx, BNFileMetadata* obj) -> void {
51-
const auto file = FileMetadata(obj);
52-
DeleteController(file);
53-
};
54-
BNRegisterObjectDestructionCallbacks(&callbacks);
55-
}
56-
57-
SharedCacheController::SharedCacheController(SharedCache&& cache, Ref<Logger> logger) : m_cache(std::move(cache))
49+
SharedCacheController::SharedCacheController(SharedCacheView* view, SharedCache&& cache, Ref<Logger> logger) : m_cache(std::move(cache))
5850
{
5951
INIT_DSC_API_OBJECT();
52+
m_view = view;
6053
m_logger = std::move(logger);
6154
m_loadedRegions = {};
6255
m_loadedImages = {};
@@ -65,42 +58,53 @@ SharedCacheController::SharedCacheController(SharedCache&& cache, Ref<Logger> lo
6558
m_regionFilter = std::regex(".*LINKEDIT.*");
6659
}
6760

68-
DSCRef<SharedCacheController> SharedCacheController::Initialize(BinaryView& view, SharedCache&& cache)
61+
DSCRef<SharedCacheController> SharedCacheController::Initialize(SharedCacheView* view, SharedCache&& cache)
6962
{
70-
auto id = GetViewIdFromFileMetadata(*view.GetFile());
63+
auto id = GetViewIdFromFileMetadata(view->GetFile());
7164
std::unique_lock<std::shared_mutex> lock(GlobalControllersMutex);
72-
auto logger = new Logger("SharedCache.Controller", view.GetFile()->GetSessionId());
73-
DSCRef<SharedCacheController> controller = new SharedCacheController(std::move(cache), logger);
65+
auto logger = new Logger("SharedCache.Controller", view->GetFile()->GetSessionId());
66+
DSCRef<SharedCacheController> controller = new SharedCacheController(view, std::move(cache), logger);
7467

7568
// Pull the settings from the view.
76-
if (Ref<Settings> settings = view.GetLoadSettings(VIEW_NAME))
69+
if (Ref<Settings> settings = view->GetLoadSettings(VIEW_NAME))
7770
{
7871
if (settings->Contains("loader.dsc.processObjC"))
79-
controller->m_processObjC = settings->Get<bool>("loader.dsc.processObjC", &view);
72+
controller->m_processObjC = settings->Get<bool>("loader.dsc.processObjC", view);
8073
if (settings->Contains("loader.dsc.processCFStrings"))
81-
controller->m_processCFStrings = settings->Get<bool>("loader.dsc.processCFStrings", &view);
74+
controller->m_processCFStrings = settings->Get<bool>("loader.dsc.processCFStrings", view);
8275
if (settings->Contains("loader.dsc.regionFilter"))
83-
controller->m_regionFilter = std::regex(settings->Get<std::string>("loader.dsc.regionFilter", &view));
76+
controller->m_regionFilter = std::regex(settings->Get<std::string>("loader.dsc.regionFilter", view));
8477
}
8578

8679
// TODO: Support old shared cache metadata
8780
// TODO: Not strictly necessary as the user has already loaded the information into the database, this would just
8881
// TODO: prevent incidental extra work from being done when loading a region or image.
89-
// const uint64_t oldStateCount = view.GetUIntMetadata(OLD_METADATA_KEY_COUNT);
82+
// const uint64_t oldStateCount = view->GetUIntMetadata(OLD_METADATA_KEY_COUNT);
9083

9184
// Check the view auto metadata for shared cache information.
9285
// This effectively restores the state of the opened database to when it was last saved.
9386
// NOTE: We store on the parent view because hilariously, the metadata is not present until after view init.
94-
if (const auto metadata = view.GetParentView()->QueryMetadata(METADATA_KEY))
87+
if (const auto metadata = view->GetParentView()->QueryMetadata(METADATA_KEY))
9588
controller->LoadMetadata(*metadata);
9689

90+
if (auto oldController = GlobalControllers().find(id); oldController != GlobalControllers().end())
91+
{
92+
// Remove old controller registration (likely due to rebase)
93+
if (oldController->second->m_refs > 2)
94+
LogWarnF("Deleting SharedCacheController for view {:#x}, but there are still {} references", id,
95+
oldController->second->m_refs.load());
96+
97+
view->GetFile()->UnregisterNotification(oldController->second);
98+
GlobalControllers().erase(oldController);
99+
}
100+
view->GetFile()->RegisterNotification(controller);
97101
GlobalControllers().insert({id, controller});
98102
return controller;
99103
}
100104

101105
DSCRef<SharedCacheController> SharedCacheController::FromView(const BinaryView& view)
102106
{
103-
auto id = GetViewIdFromFileMetadata(*view.GetFile());
107+
auto id = GetViewIdFromFileMetadata(view.GetFile());
104108
std::shared_lock<std::shared_mutex> lock(GlobalControllersMutex);
105109
auto& dscViews = GlobalControllers();
106110
auto dscView = dscViews.find(id);
@@ -316,3 +320,53 @@ std::unique_ptr<CacheStringScanner> SharedCacheController::CreateStringScanner()
316320
{
317321
return std::make_unique<CacheStringScanner>(m_cache, m_regionFilter, m_logger);
318322
}
323+
324+
void SharedCacheController::OnBeforeFileClosed(FileMetadata* file)
325+
{
326+
DeleteController(file);
327+
}
328+
329+
void SharedCacheController::OnAfterSnapshotSaved(FileMetadata* file, bool success)
330+
{
331+
if (!success)
332+
return;
333+
334+
try
335+
{
336+
auto projectFile = file->GetProjectFile();
337+
if (!projectFile)
338+
return;
339+
340+
auto project = projectFile->GetProject();
341+
auto projectFolder = projectFile->GetFolder();
342+
343+
// The shared cache might be pointing as a primary file outside of our current folder
344+
// In that case, the dependencies should be relative to the primary file
345+
auto primaryFilePath = m_view->GetPrimaryFilePath();
346+
if (primaryFilePath.has_value())
347+
{
348+
auto primaryFile = project->GetFileByPathOnDisk(*primaryFilePath);
349+
if (primaryFile)
350+
{
351+
projectFolder = primaryFile->GetFolder();
352+
}
353+
}
354+
355+
std::set<std::string> dependencyFileNames = m_view->GetDependencyFileNames();
356+
for (const auto& dependencyFile : project->GetFilesInFolder(projectFolder))
357+
{
358+
if (!dependencyFileNames.contains(dependencyFile->GetName()))
359+
{
360+
continue;
361+
}
362+
363+
LogDebugF("Shared cache adding dependency {} -> {}", dependencyFile->GetName(), file->GetDisplayName());
364+
projectFile->AddDependency(dependencyFile);
365+
}
366+
}
367+
catch (std::exception e)
368+
{
369+
LogErrorForExceptionF(e, "SharedCacheController::OnAfterSnapshotSaved");
370+
}
371+
}
372+

‎view/sharedcache/core/SharedCacheController.h‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,16 @@
1111

1212
DECLARE_DSC_API_OBJECT(BNSharedCacheController, SharedCacheController);
1313

14-
void RegisterSharedCacheControllerDestructor();
14+
class SharedCacheView;
1515

1616
namespace BinaryNinja::DSC {
1717
// Represents the view state for a given `DSCache`
18-
class SharedCacheController : public DSCRefCountObject
18+
class SharedCacheController : public DSCRefCountObject, public FileMetadataNotification
1919
{
2020
IMPLEMENT_DSC_API_OBJECT(BNSharedCacheController);
2121
Ref<Logger> m_logger;
2222
SharedCache m_cache;
23+
SharedCacheView* m_view;
2324

2425
// Locks on load attempts (region or image).
2526
std::shared_mutex m_loadMutex;
@@ -34,11 +35,11 @@ namespace BinaryNinja::DSC {
3435
bool m_processObjC;
3536
bool m_processCFStrings;
3637

37-
explicit SharedCacheController(SharedCache&& cache, Ref<Logger> logger);
38+
explicit SharedCacheController(SharedCacheView* view, SharedCache&& cache, Ref<Logger> logger);
3839

3940
public:
4041
// Initialize the DSCacheView, this should be called from the view initialize function only!
41-
static DSCRef<SharedCacheController> Initialize(BinaryView& view, SharedCache&& cache);
42+
static DSCRef<SharedCacheController> Initialize(SharedCacheView* view, SharedCache&& cache);
4243

4344
// NOTE: This will not create one if it does not exist. To create one for the view call `Initialize`.
4445
static DSCRef<SharedCacheController> FromView(const BinaryView& view);
@@ -71,5 +72,8 @@ namespace BinaryNinja::DSC {
7172
void ProcessObjCForLoadedImagesIfNeeded(BinaryView& view);
7273

7374
std::unique_ptr<CacheStringScanner> CreateStringScanner();
75+
76+
void OnBeforeFileClosed(FileMetadata*) override;
77+
void OnAfterSnapshotSaved(FileMetadata*, bool) override;
7478
};
7579
} // namespace BinaryNinja::DSC

‎view/sharedcache/core/SharedCacheView.cpp‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@ SharedCacheViewType::SharedCacheViewType() : BinaryViewType(VIEW_NAME, VIEW_NAME
4747
// We register all our one-shot stuff here, such as the object destructor.
4848
void SharedCacheViewType::Register()
4949
{
50-
RegisterSharedCacheControllerDestructor();
51-
5250
static SharedCacheViewType type;
5351
BinaryViewType::Register(&type);
5452
}
@@ -978,7 +976,7 @@ bool SharedCacheView::InitController()
978976
// TODO: Here we should have all the regions and what not for the virtual memory populated, I think it might be a good idea
979977
// TODO: To verify the regions are here and pointing at valid file accessor mappings, to make diagnosing issues quicker.
980978

981-
auto cacheController = SharedCacheController::Initialize(*this, std::move(sharedCache));
979+
auto cacheController = SharedCacheController::Initialize(this, std::move(sharedCache));
982980

983981
{
984982
auto logger = m_logger;
@@ -1034,15 +1032,15 @@ void SharedCacheView::SetPrimaryFileName(std::string primaryFileName)
10341032
{
10351033
m_primaryFilePath.clear();
10361034
m_primaryFileName = std::move(primaryFileName);
1037-
GetParentView()->StoreMetadata(VIEW_METADATA_KEY, GetMetadata());
1035+
GetParentView()->StoreMetadata(VIEW_METADATA_KEY, GetMetadata(), MetadataStorePersistent);
10381036
}
10391037

10401038

10411039
void SharedCacheView::SetPrimaryFileLocation(std::string primaryFilePath, std::string primaryFileName)
10421040
{
10431041
m_primaryFilePath = std::move(primaryFilePath);
10441042
m_primaryFileName = std::move(primaryFileName);
1045-
GetParentView()->StoreMetadata(VIEW_METADATA_KEY, GetMetadata());
1043+
GetParentView()->StoreMetadata(VIEW_METADATA_KEY, GetMetadata(), MetadataStorePersistent);
10461044
}
10471045

10481046
void SharedCacheView::LogSecondaryFileName(std::string secondaryFileName)
@@ -1338,6 +1336,14 @@ std::optional<std::string> SharedCacheView::GetPrimaryFilePath()
13381336
return newPrimaryFilePath;
13391337
}
13401338

1339+
std::set<std::string> SharedCacheView::GetDependencyFileNames() const
1340+
{
1341+
std::set<std::string> dependencyFileNames = m_secondaryFileNames;
1342+
if (!m_primaryFileName.empty())
1343+
dependencyFileNames.insert(m_primaryFileName);
1344+
return dependencyFileNames;
1345+
}
1346+
13411347
Ref<Metadata> SharedCacheView::GetMetadata() const
13421348
{
13431349
std::map<std::string, Ref<Metadata>> viewMeta;

‎view/sharedcache/core/SharedCacheView.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ class SharedCacheView : public BinaryNinja::BinaryView
4848
// Get the path to the primary file.
4949
std::optional<std::string> GetPrimaryFilePath();
5050

51+
// Get the names of the relevant dependency files for this view
52+
std::set<std::string> GetDependencyFileNames() const;
53+
5154
// Get the metadata for saving the state of the shared cache.
5255
BinaryNinja::Ref<BinaryNinja::Metadata> GetMetadata() const;
5356

0 commit comments

Comments
 (0)