packets.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (C) 2021 Ant Group. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_platform.h"
  6. #include "packets.h"
  7. #include "gdbserver.h"
  8. void
  9. write_data_raw(WASMGDBServer *gdbserver, const uint8 *data, ssize_t len)
  10. {
  11. ssize_t nwritten;
  12. nwritten = os_socket_send(gdbserver->socket_fd, data, len);
  13. if (nwritten < 0) {
  14. LOG_ERROR("Write error\n");
  15. exit(-2);
  16. }
  17. }
  18. void
  19. write_hex(WASMGDBServer *gdbserver, unsigned long hex)
  20. {
  21. char buf[32];
  22. size_t len;
  23. len = snprintf(buf, sizeof(buf) - 1, "%02lx", hex);
  24. write_data_raw(gdbserver, (uint8 *)buf, len);
  25. }
  26. void
  27. write_packet_bytes(WASMGDBServer *gdbserver, const uint8 *data,
  28. size_t num_bytes)
  29. {
  30. uint8 checksum;
  31. size_t i;
  32. write_data_raw(gdbserver, (uint8 *)"$", 1);
  33. for (i = 0, checksum = 0; i < num_bytes; ++i)
  34. checksum += data[i];
  35. write_data_raw(gdbserver, (uint8 *)data, num_bytes);
  36. write_data_raw(gdbserver, (uint8 *)"#", 1);
  37. write_hex(gdbserver, checksum);
  38. }
  39. void
  40. write_packet(WASMGDBServer *gdbserver, const char *data)
  41. {
  42. LOG_VERBOSE("send replay:%s", data);
  43. write_packet_bytes(gdbserver, (const uint8 *)data, strlen(data));
  44. }
  45. void
  46. write_binary_packet(WASMGDBServer *gdbserver, const char *pfx,
  47. const uint8 *data, ssize_t num_bytes)
  48. {
  49. uint8 *buf;
  50. ssize_t pfx_num_chars = strlen(pfx);
  51. ssize_t buf_num_bytes = 0, total_size;
  52. int32 i;
  53. total_size = 2 * num_bytes + pfx_num_chars;
  54. buf = wasm_runtime_malloc(total_size);
  55. if (!buf) {
  56. LOG_ERROR("Failed to allocate memory for binary packet");
  57. return;
  58. }
  59. memset(buf, 0, total_size);
  60. memcpy(buf, pfx, pfx_num_chars);
  61. buf_num_bytes += pfx_num_chars;
  62. for (i = 0; i < num_bytes; ++i) {
  63. uint8 b = data[i];
  64. switch (b) {
  65. case '#':
  66. case '$':
  67. case '}':
  68. case '*':
  69. buf[buf_num_bytes++] = '}';
  70. buf[buf_num_bytes++] = b ^ 0x20;
  71. break;
  72. default:
  73. buf[buf_num_bytes++] = b;
  74. break;
  75. }
  76. }
  77. write_packet_bytes(gdbserver, buf, buf_num_bytes);
  78. wasm_runtime_free(buf);
  79. }