bpf-helper.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Seccomp BPF helper functions
  3. *
  4. * Copyright (c) 2012 The Chromium OS Authors <chromium-os-dev@chromium.org>
  5. * Author: Will Drewry <wad@chromium.org>
  6. *
  7. * The code may be used by anyone for any purpose,
  8. * and can serve as a starting point for developing
  9. * applications using prctl(PR_ATTACH_SECCOMP_FILTER).
  10. */
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include "bpf-helper.h"
  15. int bpf_resolve_jumps(struct bpf_labels *labels,
  16. struct sock_filter *filter, size_t count)
  17. {
  18. struct sock_filter *begin = filter;
  19. __u8 insn = count - 1;
  20. if (count < 1)
  21. return -1;
  22. /*
  23. * Walk it once, backwards, to build the label table and do fixups.
  24. * Since backward jumps are disallowed by BPF, this is easy.
  25. */
  26. filter += insn;
  27. for (; filter >= begin; --insn, --filter) {
  28. if (filter->code != (BPF_JMP+BPF_JA))
  29. continue;
  30. switch ((filter->jt<<8)|filter->jf) {
  31. case (JUMP_JT<<8)|JUMP_JF:
  32. if (labels->labels[filter->k].location == 0xffffffff) {
  33. fprintf(stderr, "Unresolved label: '%s'\n",
  34. labels->labels[filter->k].label);
  35. return 1;
  36. }
  37. filter->k = labels->labels[filter->k].location -
  38. (insn + 1);
  39. filter->jt = 0;
  40. filter->jf = 0;
  41. continue;
  42. case (LABEL_JT<<8)|LABEL_JF:
  43. if (labels->labels[filter->k].location != 0xffffffff) {
  44. fprintf(stderr, "Duplicate label use: '%s'\n",
  45. labels->labels[filter->k].label);
  46. return 1;
  47. }
  48. labels->labels[filter->k].location = insn;
  49. filter->k = 0; /* fall through */
  50. filter->jt = 0;
  51. filter->jf = 0;
  52. continue;
  53. }
  54. }
  55. return 0;
  56. }
  57. /* Simple lookup table for labels. */
  58. __u32 seccomp_bpf_label(struct bpf_labels *labels, const char *label)
  59. {
  60. struct __bpf_label *begin = labels->labels, *end;
  61. int id;
  62. if (labels->count == BPF_LABELS_MAX) {
  63. fprintf(stderr, "Too many labels\n");
  64. exit(1);
  65. }
  66. if (labels->count == 0) {
  67. begin->label = label;
  68. begin->location = 0xffffffff;
  69. labels->count++;
  70. return 0;
  71. }
  72. end = begin + labels->count;
  73. for (id = 0; begin < end; ++begin, ++id) {
  74. if (!strcmp(label, begin->label))
  75. return id;
  76. }
  77. begin->label = label;
  78. begin->location = 0xffffffff;
  79. labels->count++;
  80. return id;
  81. }
  82. void seccomp_bpf_print(struct sock_filter *filter, size_t count)
  83. {
  84. struct sock_filter *end = filter + count;
  85. for ( ; filter < end; ++filter)
  86. printf("{ code=%u,jt=%u,jf=%u,k=%u },\n",
  87. filter->code, filter->jt, filter->jf, filter->k);
  88. }