util.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * nmrpflash - Netgear Unbrick Utility
  3. * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
  4. *
  5. * nmrpflash is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * nmrpflash is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. #include <stdio.h>
  20. #include <errno.h>
  21. #include <time.h>
  22. #include <math.h>
  23. #include "nmrpd.h"
  24. #ifdef NMRPFLASH_OSX
  25. #include <mach/mach_time.h>
  26. #endif
  27. volatile sig_atomic_t g_interrupted = 0;
  28. time_t time_monotonic()
  29. {
  30. #ifndef NMRPFLASH_WINDOWS
  31. #ifndef NMRPFLASH_OSX
  32. struct timespec ts;
  33. clock_gettime(CLOCK_MONOTONIC, &ts);
  34. return ts.tv_sec;
  35. #else
  36. static double factor = 0.0;
  37. mach_timebase_info_data_t timebase;
  38. if (factor == 0.0) {
  39. mach_timebase_info(&timebase);
  40. factor = (double)timebase.numer / timebase.denom;
  41. }
  42. return round(mach_absolute_time() * factor / 1e9);
  43. #endif
  44. #else
  45. return round(GetTickCount() / 1000.0);
  46. #endif
  47. }
  48. char *lltostr(long long ll, int base)
  49. {
  50. static char buf[32];
  51. snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll);
  52. return buf;
  53. }
  54. uint32_t bitcount(uint32_t n)
  55. {
  56. uint32_t c;
  57. for (c = 0; n; ++c) {
  58. n &= n - 1;
  59. }
  60. return c;
  61. }
  62. uint32_t netmask(uint32_t count)
  63. {
  64. return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0);
  65. }
  66. void xperror(const char *msg)
  67. {
  68. if (errno != EINTR) {
  69. perror(msg);
  70. } else {
  71. printf("\n");
  72. }
  73. }