summaryrefslogtreecommitdiff
path: root/view/sharedcache/core/SharedCache.h
AgeCommit message (Collapse)Author
2026-02-24[DSC] Simplify file mapping to fix intermittent unrelocated pointersMark Rowe
The `FileAccessorCache`'s LRU eviction could discard a file's mapped data after slide info had already been applied to it. Future accesses to the file produced a fresh mapping, but failed to reapply the slide info. This could result in pointers not correctly being slid, such as in https://github.com/Vector35/binaryninja-api/issues/7689. The LRU cache existed to stay within OS file descriptor limits, since the old `MappedFile` held its fd open for the lifetime of the mapping. There's no real reason for it to hold the file descriptor open like this. Closing it after `mmap` is sufficient to avoid the file descriptor limits. `MappedFileRegion` replaces the combination of `FileAccessorCache`, `WeakFileAccessor`, and `MappedFileAccessor`. It closes the fd immediately after mmap, so all files can stay mapped without consuming descriptors, making the cache unnecessary. `MappedFileRegion` is owned directly by the `CacheEntry` for its full lifetime. Slide info is applied exactly once to each `MappedFileRegion`.
2026-02-13[DSC] Correctly mark symbols as having local, global, or weak bindingMark Rowe
2025-09-17[DSC] Rework handling of .symbols files to be compatible with iOS 15Mark Rowe
In some iOS 15 caches, the .symbols file's mapping has an address of 0. This would cause it to be returned by `SharedCache::GetEntryContaining` and loaded into the view. The .symbols file contains the local symbol tables for images in the shared cache. It is not intended to be mapped into the same address space as the rest of the shared cache. `SharedCache` now tracks the symbols cache entry separately from other entries. A dedicated `VirtualMemory` region is used when accessing the data it contains. This could be a `FileAccessor`, but that would require additional changes within `SharedCacheMachOHeader`. `SharedCacheMachOProcessor` now directly accesses the local symbols cache entry rather than needing to search for it.
2025-04-14[SharedCache] Misc cleanupMason Reed
- Make `SharedCache::m_entries` a simple std::vector we never lookup based off the entry ID - Remove some old comments - Rename some old variables so that they are accurate - Fix compiler warnings - Remove some unneeded copying
2025-04-14[SharedCache] Bubble up errors in `CacheEntry::FromFile` to the userMason Reed
Prior to this we would not have meaningful errors shown to the user when we fail to construct a CacheEntry from a file. Apart of trying to make the opening of shared caches clearer.
2025-04-14[SharedCache] Apply .symbols file information when applying an imageMason Reed
This improves symbol recovery drastically on newer shared caches Related PR: https://github.com/Vector35/binaryninja-api/pull/6210
2025-04-10[SharedCache] Make the shared cache file lookup more straightforwardMason Reed
We already had separated this part out into the `CacheProcessor` but its more like a builder than anything, so this refactors that out into a `SharedCacheBuilder`. - Separate out the `CacheProcessor` and simplify its implementation - Move more implementation specific stuff to the shared cache view - Prepare for more validation of the shared cache to detect irregular or incomplete shared cache information - Deduplicate a lot of file vs. project file lookup stuff - Stop copying all images when getting the number of images to log - Allow user to select another directory to scan for shared cache files, might make this a warning instead to prevent users from relying on this behavior We will likely follow this commit up soon with better open behavior, maybe open with options can specify a list of cache entry files? Shouldn't be too much effort aside from making the UI modal for that.
2025-04-08[SharedCache] Apply demangled names and types more broadlyMason Reed
Fixes the case of stub functions being applied with mangled names.
2025-04-06[SharedCache] Add mutex to guard `m_namedSymbols`Mason Reed
It is modified on a worker thread so if a user tries to call `GetSymbolWithName` after view init but before the processing on the worker thread finishes, there would have been issues!
2025-04-06[SharedCache] Prevent some unneeded copies when processingMason Reed
Also swapped out CacheEntry::m_images to a vector as its never actually used as a lookup
2025-04-06[SharedCache] Replace write log with callback registration for reapplying ↵Mason Reed
slide info This improves performance by ~10x with the only real issue being a copy of the cache entry existing for each weak ref. Also fixes - Some old TODO's that are no longer relevant - Some function signatures not being const - FileAccessorCache not evicting enough accessors to fit under an adjusted cache size - Added a warning if we are over the global cache size in view initialization - Logger name not having a `.` in `SlideInfoProcessor::SlideInfoProcessor` - Re-added the accessor dirty check before applying slide info to fix https://github.com/Vector35/binaryninja-api/issues/6570
2025-04-06[SharedCache] Add a named symbol mapMason Reed
Fixes https://github.com/Vector35/binaryninja-api/issues/6561 - Also tightens the SharedCache class to move only, to prevent accidental copies. - Also removes some extra copies in FFI when should pass by ref - Also adds `get_symbol_with_name` to python API The current named symbol map is populated in a worker thread spawned in the view init. This is because populating the map can take about 1 second. If we are fine with another 1 second added to the view init time then we can add it serially but I don't think this way is _that_ bad, no analysis consults this, however a user might add a workflow that would be racing this. So we need to add a mutex.
2025-04-02[SharedCache] Fix some bugsMason Reed
2025-04-02[SharedCache] Refactor Shared CacheMason Reed
In absence of a better name, this commit refactors the shared cache code.
2025-04-02[SharedCache] Optimize parsing of slide infoMark Rowe
Slide info is parsed and applied on the main thread, below the `SharedCache` constructor, when a shared cache is opened. Time spent applying the slide is time that the main thread is blocked. These changes eliminate some unnecessary overhead so what work remains is dominated by kernel work (paging in data, copying pages when the first modification is made). The changes are: 1. Read slide pointers via `ReadULong` rather than the variable-length `Read` method. The compiler isn't able to eliminate the call to `memcpy` in the variable-length `Read` function, and the function call overhead is noticeable given the small size of the read and number of times it is called. 2. Remove the file member from `MappingInfo`. Slide info is applied for a single file at a time so there's no reason to track the file it belongs to. This removes unnecesssary reference counting on the `std::shared_ptr` that holds the `MMappedFileAccessor`.
2025-04-02[SharedCache] Make it faster to look up which image contains an addressMark Rowe
`MemoryRegion` now tracks the start address of the image to which it belongs. `SharedCache::HeaderForAddress` uses the existing address range map to quickly find the `MemoryRegion` for a given address, and from there can look up the image via its start address. Some extra logic is added to `CacheInfo::Load` to populate the image start address on `MemoryRegion` when loading from metadata that predates this change. The result is that `HeaderForAddress` is no longer the most expensive part of `FindSymbolAtAddrAndApplyToAddr`.
2025-04-02[SharedCache] Don't crash if we have a different metadata versionMason Reed
Also we now initialize m_cacheInfo when calling `DeserializeFromRawView` the responsibility is on the caller to handle
2025-04-02[SharedCache] Warn when loading BNDB with different shared cache metadata ↵Mason Reed
version This does not actually give the user control to exit early, that looks to need core changes.
2025-02-19[SharedCache] Don't capture `this` within lambda passed to ↵Mark Rowe
MMappedFileAccessor::Open Nothing guarantees that the `SharedCache` lives long enough.
2025-02-17[SharedCache] Remove using namespace statement from headersMason Reed
2025-02-17[SharedCache] Split out symbol processing into own functionMason Reed
Split out from https://github.com/WeiN76LQh/binaryninja-api/tree/process-local-symbols
2025-02-17[SharedCache] Define BackingCacheTypeWeiN76LQh
Split out from https://github.com/WeiN76LQh/binaryninja-api/tree/process-local-symbols
2025-02-17[SharedCache] Split state into initial, loaded, and modifiedMark Rowe
The initial state is initialized during `PerformInitialLoad` and is immutable after that point. This required some slight restructuring of how information about memory regions is tracked as that was previously modified as regions were loaded. Memory regions are now stored in a map from their address range to the `MemoryRegion` object. This makes it cheap to look them up by address which is a common operation. The modified state consists of changes since the last save to the `DSCView` / `ViewSpecificState`. This means it is no longer necessary to copy any state when mutating a `SharedCache` instance for the first time. Instead, its data structures start off empty and are populated as images, sections, or symbol information is loaded. The loaded state consists of all modified state that has since been saved. It lives on the `ViewSpecificState`. Saving modified state merges it into the the existing loaded state. This pattern is carried over to the `Metadata` stored on the `DSCView`. The initial state is stored under its own metadata key, and each modified state is stored under a key with an incrementing number. This means each save of the state only needs to serialize the state that changed, rather than reserializing all of the state all of the time. There are two huge benefits from these changes: 1. At no point does `SharedCache` have to copy its in memory state. The basic copy-on-write approach introduced in #6129 reduced how often these copies are made, but they're still frequent and very expensive. 1. At no point does `SharedCache` have to re-serialize state to JSON that it has already serialized. JSON serialization previously added hundreds of milliseconds to any mutating operation on `SharedCache`. As a result, this speeds up the initial load of the shared cache by around 2x and loading of subsequent images improves by about the same. One trade-off is that the serialization / deserialization logic is more complicated. There are two reasons for this: 1. The state is now split across multiple metadata keys and needs to be merged when it is loaded. 2. The in-memory representation uses pointers to identify memory regions. These relationships have to be re-established after the JSON is deserialized. As a future direction it is worth considering whether the logic owned by `SharedCache` could be split in a similar manner to the data. The initial loading of the cache header, loading of images, and handling of symbol information are all mostly independent and work on separate data. If the logic were split into separate classes it would be easier to reason about which data is valid when, and would easily permit concurrent loading of multiple images from the shared library in a thread-safe manner.
2025-02-12[SharedCache] Remove designator initializationMason Reed
Fixes MSVC C++17 failing to compile, hopefully.
2025-02-12[SharedCache] Fix crash when trying to deserialize a `routines_command_64` ↵Mason Reed
which had not been serialized. We will just return early, this is fine as the previous code would effectively do the same thing.
2025-02-12[SharedCache] Fix misc compiler warningsMason Reed
These are from clang so there are still a bunch of warnings on GCC and MSVC
2025-02-12[SharedCache] Fix designator order for fieldsMason Reed
This apparently is not an issue on LLVM, but GCC and MSVC both seem to dislike this.
2025-02-12[SharedCache] Rework how file accessors are handledMark Rowe
Previously, `MMappedFileAccessor::Open` attempted to impose a fixed limit on the number of file accessors that were live at one time. This was done because the default file descriptor limit on some platforms is relatively low (256 on macOS). Given that recent iOS shared caches can contain 60+ files it is easy to tie up a large percentage of this limit by opening one or two shared caches. This is problematic as if the limit imposed by `MMappedFileAccessor::Open` is reached, the attempt to access the file will block waiting for another file accessor to be closed. This can lead to a deadlock. This commit makes three changes to this strategy: 1. It attempts to raise the file descriptor limit to 1024. Unix systems support both soft and hard file descriptor limits. The soft file descriptor limit is what is enforced, but a process can explicitly raise the limit to any value below the hard limit if it wishes. 2. The fixed limit on open files accessors is changed to a soft limit. `FileAccessorCache` is introduced to manage the caching of file accessors. It provides a basic LRU cache. Whenever a new file is opened, the cache of open accessors is pruned to stay below the target limit (50% of the soft file descriptor limit). This limiting is primarily done to allow files containing dirty pages to be unmapped if they're no longer being used. LRU isn't the optimal strategy for this, but it is simple to implement and understand. Ideally there'd be some access time component to the cache so files that haven't been accessed can be released. 3. File accessors are cached even for sessions corresponding to views that have been closed. The "Open Selection with Options..." context menu hits this case as a view is created and destroyed as part of populating the options dialog, and the real view is then created in the same session. The most significant benefit of this change is that the logic around opening / closing file accessors is simpler and can no longer deadlock. While working on this I noticed that `SharedCache` opened some files via `MMappedFileAccessor::Open` without specifying a post-open operation to apply slide information. Instead, it would explicitly apply the slide information after opening the file. This works fine so long as the file accessor limit is never hit. If it is hit and the accessor is closed, the next time the file is opened it will not have any slide information applied. This would lead to very confusing bugs.
2025-02-12[SharedCache] Make MetadataSerializable::Load staticMark Rowe
`MetadataSerializable` is updated to allow a subclass to optionally specify the return type of `Load`. If not specified it defaults to the subclass itself. `SharedCache` specifies `std::optional` to represent the case where the serialized metadata is in a format or version it does not recognize. By making `Load` a static member function and having it return a new object it becomes easier to reason about the state of objects when a deserialization failure occurs. It can return `std::optional` to indicate failure and there is no object left in an unknown state. Prior to this, `Load` worked on an existing instance of an object. It was unclear what state the object would be in if a deserialization failure occurred (its original state prior to `Load`? some partially-loaded state? a null state?). The failure itself also had to be communicated out of band.
2025-02-10[SharedCache] Make `m_exportInfos` map's values a `shared_ptr`WeiN76LQh
This avoids expensive copying when returning a value from the map in `SharedCache::GetExportListForHeader`. Additionally it ensures that the value stays alive and at the same location in memory if `m_exportInfos` is modified and requires its storage to be re-allocated. I was unable to use a `unique_ptr` instead of a `shared_ptr` because of copy semantics with `m_exportInfos` in `ViewStateCacheStore`. I don't see things being any worse using `shared_ptr` instead of `unique_ptr` anyway and it means less code changes.
2025-02-10[SharedCache] Improve the types for `m_exportInfos`WeiN76LQh
This commit changes 2 things; 1. `m_exportInfos` is now a map where its values are also a map rather than a vector of pairs. The reason for this is that `SharedCache::FindSymbolAtAddrAndApplyToAddr` is a hot path which does by far the most accesses to `m_exportInfos`. In that function it must find the correct symbol for a given address so a map lookup will be much quicker than iterating a vector. The other use cases of `m_exportInfos` would prefer a vector but they are executed very infrequently. 2. The symbols are stored in `m_exportInfos` as references to the `Symbol` type. This makes more sense because otherwise there is a lot of time spent converting to and from a `Symbol` type and a pair of `BNSymbolType` + a `std::string`.
2025-02-10[SharedCache] Add parameter to `SharedCache::InitializeHeader` to check if ↵WeiN76LQh
`m_exportInfos` was modified This probably makes more sense than the current solution of using execution of the callback parameter to determine if `m_exportInfos` was modified.
2025-02-10[SharedCache] Use `m_exportInfos` as an export list cacheWeiN76LQh
`SharedCache::ParseExportTrie` is getting called a lot during DSC library loading and analysis. In large part due to the hot path `SharedCache::FindSymbolAtAddrAndApplyToAddr`. Its unnecessary for it to be being called more than once per DSC header as the export list symbol information is stored in `SharedCache::m_exportInfos`. This commit adds the function `SharedCache::GetExportListForHeader`, which will either return the header's list of symbol information cached in `SharedCache::m_exportInfos` or call `SharedCache::ParseExportTrie` and cache the results in `SharedCache::m_exportInfos`. This should also improve the execution time of `SharedCache::LoadAllSymbolsAndWait`. Further improvement here would be to add locking to `SharedCache::GetExportListForHeader` so that races don't result in redundant parsing of the export trie for the same header if multiple threads call `SharedCache::GetExportListForHeader` at the same time for the same header. This only really matters during initial loading because from what I can tell that parses all the export trie's anyway.
2025-01-30[SharedCache] Vision Pro, tvOS, iOS Simulator supportkat
2025-01-27[SharedCache] Optimize `ReadExportNode`Mark Rowe
`ReadExportNode` is called a lot during the initial load of the shared cache and thus impacts how long it takes for the UI to become responsive. This is a collection of optimizations that cut the time spent within `ReadExportNode` by 50%: 1. Pass iterators to `ReadExportNode` rather than a `DataBuffer` + offset. The lack of inlining in `DataBuffer`'s `operator[]` kills performance. Ideally this would have used `std::span`, but that would require bumping the minimum C++ version to C++20. 2. Add `MMappedFileAccessor::ReadSpan` so that `ReadExportNode` can operate directly on the mapped data without first copying it. 3. Removes a call to `GetAnalysisFunctionsForAddress` whose result was unused. 4. Use `std::find` to find the nul at the end of strings rather than assembling the string a character at a time. This avoids repeatedly growing the string. 5. Avoid the usual `Symbol` constructor in favor of `BNCreateSymbol`. The `Symbol` constructor has over head in two forms: 1. It has a `NameSpace` as an argument. Creating / destroying this allocates and deallocates memory We could create a single instance and reuse it for all calls, but... 2. The constructor copies all fields of the `NameSpace` to the heap before calling `BNCreateSymbol` and then deallocates them afterwards. This seems unnecessary, and adds a non-trivial amount of overhead. This can go back to directly constructing the `Symbol` once the constructors are improved.
2025-01-10[SharedCache] Fix handling of relative selectors in macOS shared cachesMark Rowe
Find the relative selector base address in the Objective-C optimization data pointed to by the shared cache header, rather than via `__objc_scoffs`. This is only present on iOS, and not for every iOS version that encodes selectors via direct offsets. This also includes some related improvements: 1. Direct selectors get their own pointer type so they're rendered correctly in the view. 2. Method lists encoded as lists of lists are now handled. 3. The `dyld_cache_header` type added to the view is truncated to the length in the loaded cache. This ensures it is applied to the view. 4. A couple of methods that process method IMPs and selectors are updated to check whether the address is valid before attempting to process them. They would otherwise fail by throwing an exception if they proceed, but checking for validity is quicker and makes exception breakpoints usable.
2025-01-10[SharedCache] Track whether non-image regions are data vs codeMark Rowe
`BackingCache` now tracks the `dyld_cache_mapping_info` for its mappings so it has access to the memory protections for the region. This means it can avoid marking some regions as containing code when they don't, reducing the amount of analysis work that has to be done. Using `dyld_cache_mapping_info` also makes references to mappings easier to understand due to its named fields vs the nested `std::pair`s that were previously in use.
2025-01-10[SharedCache] Cache type libraries in the view-specific stateMark Rowe
They're surprisingly expensive to look up.
2025-01-10[SharedCache] Split view-specific state into a separate structMark Rowe
The existing view-specific state was stored in several global unordered maps. Many of these were accessed without locking, including `viewSpecificMutexes`, which is racy in the face of multiple threads. View-specific state is stored in a new heap-allocated `ViewSpecificState` struct that is reference counted via `std::shared_ptr`. A static map holds a `std::weak_ptr` to each view-specific state, keyed by session id. `SharedCache` retrieves its view-specific state during its constructor. Since `ViewSpecificState` is reference counted it will naturally be deallocated when the last `SharedCache` instance that references it goes away. Its corresponding entry will remain in the static map, though since it only holds a `std::weak_ptr` rather than any state it will not use much memory. The next time view-specific state is retrieved any expired entries will be removed from the map.
2025-01-08[SharedCache] Fix uninitialized `loaded` field for mappings returned by ↵WeiN76LQh
`BNDSCViewGetAllImages`
2024-12-26[SharedCache] Add the ability to manually trigger Objective-C processingWeiN76LQh
A problem with processing Objective-C sections at the time a library is loaded is that some of the references within those sections may refer to unload sections. This results in things like selectors not being correctly typed and named. This commit provides a way for users to manually trigger Objective-C parsing against sections for a specific library or all libraries, via the API. Combined with the previous commit a user can use the API to batch load a number of libraries and skip Objective-C processing for each one and then run it across the entire of the DSC once they are all loaded. Further improvement would be to provide a way to trigger Objective-C processing through the UI.
2024-12-26[SharedCache] Add the ability to skip Objective-C processing when loading a ↵WeiN76LQh
library This is useful when batch loading libraries to avoid extra processing (once the next commit has landed).
2024-12-10[SharedCache] Fix slide info parsing and complete v2 supportWeiN76LQh
There seem to be a number of issues with slide info parsing. I decided the simplest fix was to largely mimick what `dyld` is doing. Part of this process was to remove creating a vector of page starts and processing them in another loop below the one where they were read out. It wasn't clear to me the original design decision to separate it into 2 loops like that. I think this was part of the problem that was causing issues. By adding rewrites in the same loop where page starts are being read out, it was much easier to mimick the code in `dyld` which I assume has to be correct. So as long as my copying was correct then I believe this should work as intended. Not everything has been thoroughly tested but I'm pretty confident v3 and v5 are now working as intended. v2 should be but less testing of it has been done.
2024-12-10[SharedCache] Fix padding issue with v5 slide infoWeiN76LQh
The issue this commit fixes was causing `SharedCache::ParseAndApplySlideInfoForFile` to completely fail to work with v5 slide info, which had a lot of knock on effects, i.e. lots of Objective-C analysis was failing due to invalid pointers which hadn't been fixed up. `dyld_cache_slide_info5` has 4 bytes of padding before `value_add`. Whilst `value_add` is not actually being read from, `SharedCache::ParseAndApplySlideInfoForFile` will read at a location in the file based on the size of the structure `dyld_cache_slide_info5`. This being off by 4 bytes basically broke v5 slide info fixups. With this fix many more Objective-C functions have names and a lot more `msgSend` calls are fixed up.
2024-12-10[SharedCache] Use basic copy-on-write for viewStateCacheMark Rowe
Copying the state from the cache into a new `SharedCache` object is done with a global lock held and is so expensive that it results in much of the shared cache analysis running on a single thread, with others blocked waiting to acquire the lock. The cache now holds a `std::shared_ptr` to the state. New `SharedCache` objects take a reference to the cached state and only create their own copy of it the first time they perform an operation that would mutate it. The cached copy is never mutated, only replaced, so there is no danger of modifying the state out from under a `SharedCache` object. Since the copy happens at first mutation, it is performed without any global locks held. This avoids blocking other threads. This cuts the initial load time of a macOS shared cache from 3 minutes to 70 seconds, and cuts the time taken to load and analyze AppKit from multiple hours to around 14 minutes.
2024-12-10[SharedCache] Switch to SAX-based writer API for JSON serializationAuthor: Mark Rowe
2024-12-10[SharedCache] Rework metadata serialization to reduce memory overheadMark Rowe
api/MetadataSerializable.hpp is removed in favor of including core/MetadataSerializable.hpp. Both headers defined types with the same name leading to One Definition Rule violations and surprising behavior. The serialization and deserialization context are now created on-demand during serialization rather than being a member of `MetadataSerializable`. This reduces the size of every serializable object by ~220 bytes. The context is passed explicitly as an argument to `Serialize` / `Deserialize`. As a result, `Serialize` / `Deserialize` can now be free functions rather than member functions. Since `MetadataSerializable` is not used for dynamic dispatch, the virtual methods are removed and the class is updated to be a class template using CRTP. This allows delegating to the derived class's `Load` and `Store` methods without the additional size overhead of the vtable pointer in every serializable object. These changes reduce the memory footprint of Binary Ninja after loading the macOS shared cache and loading a single dylib from it from 8.3GB to 4.6GB.
2024-11-13[SharedCache] Fix a bndb deserialization error caused by last commitkat
2024-11-13Append export and symbol info to correct arraysMark Rowe
This is both a correctness fix and avoids leaking a massive amount of memory.
2024-11-06normalize Shared Cache nameJordan Wiens