shim_random.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. /* Copyright (C) 2014 Stony Brook University
  4. This file is part of Graphene Library OS.
  5. Graphene Library OS is free software: you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public License
  7. as published by the Free Software Foundation, either version 3 of the
  8. License, or (at your option) any later version.
  9. Graphene Library OS is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  15. /*
  16. * shim_random.c
  17. *
  18. * This file contains codes for generating random numbers.
  19. */
  20. #include <shim_internal.h>
  21. #include <shim_utils.h>
  22. #include <shim_checkpoint.h>
  23. #include <pal.h>
  24. static LOCKTYPE randgen_lock;
  25. static unsigned long randval;
  26. int init_randgen (void)
  27. {
  28. if (DkRandomBitsRead (&randval, sizeof(randval)) < sizeof(randval))
  29. return -EACCES;
  30. debug("initial random value: %08llx\n", randval);
  31. create_lock(randgen_lock);
  32. return 0;
  33. }
  34. int getrand (void * buffer, size_t size)
  35. {
  36. unsigned long old_randval = randval;
  37. int bytes = 0;
  38. lock(randgen_lock);
  39. while (bytes + sizeof(unsigned long) <= size) {
  40. *(unsigned long *) (buffer + bytes) = randval;
  41. bytes += sizeof(unsigned long);
  42. randval = hash64(randval);
  43. }
  44. if (bytes < size) {
  45. switch (size - bytes) {
  46. case 4:
  47. *(uint32_t *) (buffer + bytes) = randval & 0xffffffff;
  48. bytes += 4;
  49. break;
  50. case 2:
  51. *(uint16_t *) (buffer + bytes) = randval & 0xffff;
  52. bytes += 2;
  53. break;
  54. case 1:
  55. *(uint8_t *) (buffer + bytes) = randval & 0xff;
  56. bytes++;
  57. break;
  58. default: break;
  59. }
  60. randval = hash64(randval);
  61. }
  62. unlock(randgen_lock);
  63. return bytes;
  64. }
  65. extern_alias(getrand);