ptrace.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/LogStream.h>
  27. #include <Kernel/API/Syscall.h>
  28. #include <errno.h>
  29. #include <sys/ptrace.h>
  30. extern "C" {
  31. int ptrace(int request, pid_t tid, void* addr, int data)
  32. {
  33. // PT_PEEK needs special handling since the syscall wrapper
  34. // returns the peeked value as an int, which can be negative because of the cast.
  35. // When using PT_PEEK, the user can check if an error occured
  36. // by looking at errno rather than the return value.
  37. u32 out_data;
  38. Syscall::SC_ptrace_peek_params peek_params;
  39. if (request == PT_PEEK) {
  40. peek_params.address = reinterpret_cast<u32*>(addr);
  41. peek_params.out_data = &out_data;
  42. addr = &peek_params;
  43. }
  44. Syscall::SC_ptrace_params params {
  45. request,
  46. tid,
  47. reinterpret_cast<u8*>(addr),
  48. data
  49. };
  50. int rc = syscall(SC_ptrace, &params);
  51. if (request == PT_PEEK) {
  52. if (rc < 0) {
  53. errno = -rc;
  54. return -1;
  55. }
  56. errno = 0;
  57. return static_cast<int>(out_data);
  58. }
  59. __RETURN_WITH_ERRNO(rc, rc, -1);
  60. }
  61. }