scoped-mock-context.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* RAII type to create a temporary mock context.
  2. Copyright (C) 2020-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef SCOPED_MOCK_CONTEXT_H
  15. #define SCOPED_MOCK_CONTEXT_H
  16. #include "inferior.h"
  17. #include "gdbthread.h"
  18. #include "progspace.h"
  19. #include "progspace-and-thread.h"
  20. #if GDB_SELF_TEST
  21. namespace selftests {
  22. /* RAII type to create (and switch to) a temporary mock context. An
  23. inferior with a thread, with a process_stratum target pushed. */
  24. template<typename Target>
  25. struct scoped_mock_context
  26. {
  27. /* Order here is important. */
  28. Target mock_target;
  29. ptid_t mock_ptid {1, 1};
  30. program_space mock_pspace {new_address_space ()};
  31. inferior mock_inferior {mock_ptid.pid ()};
  32. thread_info mock_thread {&mock_inferior, mock_ptid};
  33. scoped_restore_current_pspace_and_thread restore_pspace_thread;
  34. explicit scoped_mock_context (gdbarch *gdbarch)
  35. {
  36. /* Add the mock inferior to the inferior list so that look ups by
  37. target+ptid can find it. */
  38. inferior_list.push_back (mock_inferior);
  39. mock_inferior.thread_list.push_back (mock_thread);
  40. mock_inferior.ptid_thread_map[mock_ptid] = &mock_thread;
  41. mock_inferior.gdbarch = gdbarch;
  42. mock_inferior.aspace = mock_pspace.aspace;
  43. mock_inferior.pspace = &mock_pspace;
  44. /* Switch to the mock inferior. */
  45. switch_to_inferior_no_thread (&mock_inferior);
  46. /* Push the process_stratum target so we can mock accessing
  47. registers. */
  48. gdb_assert (mock_target.stratum () == process_stratum);
  49. mock_inferior.push_target (&mock_target);
  50. /* Switch to the mock thread. */
  51. switch_to_thread (&mock_thread);
  52. }
  53. ~scoped_mock_context ()
  54. {
  55. inferior_list.erase (inferior_list.iterator_to (mock_inferior));
  56. pop_all_targets_at_and_above (process_stratum);
  57. }
  58. };
  59. } // namespace selftests
  60. #endif /* GDB_SELF_TEST */
  61. #endif /* !defined (SCOPED_MOCK_CONTEXT_H) */