1 // Copyright 2017 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef COMPONENTS_ZUCCHINI_ELEMENT_DETECTION_H_ 6 #define COMPONENTS_ZUCCHINI_ELEMENT_DETECTION_H_ 7 8 #include <stddef.h> 9 10 #include <memory> 11 #include <optional> 12 13 #include "base/callback.h" 14 #include "components/zucchini/buffer_view.h" 15 #include "components/zucchini/image_utils.h" 16 17 namespace zucchini { 18 19 class Disassembler; 20 21 // Attempts to detect an executable located at start of |image|. If found, 22 // returns the corresponding disassembler. Otherwise returns null. 23 std::unique_ptr<Disassembler> MakeDisassemblerWithoutFallback( 24 ConstBufferView image); 25 26 // Attempts to create a disassembler corresponding to |exe_type| and initialize 27 // it with |image|, On failure, returns null. 28 std::unique_ptr<Disassembler> MakeDisassemblerOfType(ConstBufferView image, 29 ExecutableType exe_type); 30 31 // Returns the version associated with disassembler of type |exe_type|. 32 uint16_t DisassemblerVersionOfType(ExecutableType exe_type); 33 34 // Attempts to detect an element associated with |image| and returns it, or 35 // returns nullopt if no element is detected. 36 using ElementDetector = 37 base::RepeatingCallback<std::optional<Element>(ConstBufferView image)>; 38 39 // Implementation of ElementDetector using disassemblers. 40 std::optional<Element> DetectElementFromDisassembler(ConstBufferView image); 41 42 // A class to scan through an image and iteratively detect elements. 43 class ElementFinder { 44 public: 45 ElementFinder(ConstBufferView image, ElementDetector&& detector); 46 ElementFinder(const ElementFinder&) = delete; 47 const ElementFinder& operator=(const ElementFinder&) = delete; 48 ~ElementFinder(); 49 50 // Scans for the next executable using |detector|. Returns the next element 51 // found, or nullopt if no more element can be found. 52 std::optional<Element> GetNext(); 53 54 private: 55 ConstBufferView image_; 56 ElementDetector detector_; 57 offset_t pos_ = 0; 58 }; 59 60 } // namespace zucchini 61 62 #endif // COMPONENTS_ZUCCHINI_ELEMENT_DETECTION_H_ 63