instruction_utils.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2016 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. #ifndef COURGETTE_INSTRUCTION_UTILS_H_
  5. #define COURGETTE_INSTRUCTION_UTILS_H_
  6. #include <stdint.h>
  7. #include "base/callback.h"
  8. #include "courgette/image_utils.h"
  9. #include "courgette/memory_allocator.h"
  10. namespace courgette {
  11. // An interface to receive emitted instructions parsed from an executable.
  12. class InstructionReceptor {
  13. public:
  14. InstructionReceptor() = default;
  15. InstructionReceptor(const InstructionReceptor&) = delete;
  16. InstructionReceptor& operator=(const InstructionReceptor&) = delete;
  17. virtual ~InstructionReceptor() = default;
  18. // Generates an entire base relocation table.
  19. virtual CheckBool EmitPeRelocs() = 0;
  20. // Generates an ELF style relocation table for X86.
  21. virtual CheckBool EmitElfRelocation() = 0;
  22. // Following instruction will be assembled at address 'rva'.
  23. virtual CheckBool EmitOrigin(RVA rva) = 0;
  24. // Generates a single byte of data or machine instruction.
  25. virtual CheckBool EmitSingleByte(uint8_t byte) = 0;
  26. // Generates multiple bytes of data or machine instructions.
  27. virtual CheckBool EmitMultipleBytes(const uint8_t* bytes, size_t len) = 0;
  28. // Generates a 4-byte relative reference to address of 'label'.
  29. virtual CheckBool EmitRel32(Label* label) = 0;
  30. // Generates a 4-byte absolute reference to address of 'label'.
  31. virtual CheckBool EmitAbs32(Label* label) = 0;
  32. // Generates an 8-byte absolute reference to address of 'label'.
  33. virtual CheckBool EmitAbs64(Label* label) = 0;
  34. };
  35. // A rerunable callback that emit instructions to a provided receptor. Returns
  36. // true on success, and false otherwise.
  37. using InstructionGenerator =
  38. base::RepeatingCallback<CheckBool(InstructionReceptor*)>;
  39. // A counter that increments via .push_back(), so it can be passed via template
  40. // to substitute std::vector<T>, to count elements instead of storing them.
  41. template <typename T>
  42. class CountingVector {
  43. public:
  44. CountingVector() {}
  45. void push_back(const T& /* unused */) { ++size_; }
  46. size_t size() const { return size_; }
  47. private:
  48. size_t size_ = 0;
  49. };
  50. } // namespace courgette
  51. #endif // COURGETTE_INSTRUCTION_UTILS_H_