stream.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. // Copyright © 2018-2019 Ariadne Devos
  3. /* sHT -- keeping track of a stream's resources */
  4. #include <stddef.h>
  5. #include <sHT/compiler.h>
  6. #include <sHT/paper.h>
  7. #include <sHT/resource.h>
  8. #include <sHT/stream.h>
  9. #include <sHT/test.h>
  10. _Bool
  11. sHT_init_stream(struct sHT_objcache *papers, struct sHT_stream *stream)
  12. {
  13. sHT_paper write_paper, read_paper;
  14. write_paper = sHT_alloc(papers);
  15. if (sHT_null_p(write_paper))
  16. goto enomem;
  17. read_paper = sHT_alloc(papers);
  18. if (sHT_null_p(read_paper))
  19. goto write_paper;
  20. *stream = (struct sHT_stream) {
  21. /* Try to provoke crashes when @code{stream->fd} is used before
  22. initialisation. No one uses -2 for invalid file descriptors,
  23. sHT uses it for undefined file descriptors (not the same
  24. thing). */
  25. .fd = -2,
  26. .flags = 0,
  27. .to_write = {
  28. .first = write_paper,
  29. .offset = 0,
  30. .length = 0,
  31. },
  32. .has_read = {
  33. .first = read_paper,
  34. .offset = 0,
  35. .length = 0,
  36. },
  37. };
  38. sHT_depend(stream, write_paper);
  39. sHT_depend(stream, read_paper);
  40. _Bool ret = 0;
  41. sHT_depend(ret, stream);
  42. return ret;
  43. write_paper:
  44. /* write_paper may speculatively be NULL, but sHT_free allows that. */
  45. sHT_free(papers, write_paper);
  46. enomem:
  47. /* TODO: compile this out on release builds */
  48. /* Try to provoke a crash when @var{stream} is used, even though it is
  49. uninitialised. */
  50. /* No one uses -2 for invalid file descriptors, sHT uses it for
  51. undefined file descriptors (not the same thing). */
  52. stream->fd = -2;
  53. /* NULL papers in buffers of initialised structures are always
  54. incorrect (in sHT, not necessarily elsewhere). So we can try to
  55. provoke a segfault. */
  56. stream->has_read = stream->to_write = (struct sHT_buffer) {
  57. .first = NULL,
  58. .offset = 0,
  59. .length = sHT_PAPER_SIZE,
  60. };
  61. /* TODO: inform Valgrind of all this undefinedness with
  62. VALGRIND_MAKE_MEM_UNDEFINED. */
  63. return 1;
  64. }
  65. void
  66. sHT_free_stream(struct sHT_objcache *papers, struct sHT_stream *stream)
  67. {
  68. sHT_free(papers, stream->has_read.first);
  69. sHT_free(papers, stream->to_write.first);
  70. /* TODO: consider tainting @var{stream}'s buffers, see
  71. @var{sHT_init_stream}. */
  72. }