util.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Copyright StrongLoop, Inc. All rights reserved.
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to
  5. * deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  7. * sell copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  19. * IN THE SOFTWARE.
  20. */
  21. #include "defs.h"
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. static void pr_do(FILE *stream,
  26. const char *label,
  27. const char *fmt,
  28. va_list ap);
  29. void *xmalloc(size_t size) {
  30. void *ptr;
  31. ptr = malloc(size);
  32. if (ptr == NULL) {
  33. pr_err("out of memory, need %lu bytes", (unsigned long) size);
  34. exit(1);
  35. }
  36. return ptr;
  37. }
  38. void pr_info(const char *fmt, ...) {
  39. va_list ap;
  40. va_start(ap, fmt);
  41. pr_do(stdout, "info", fmt, ap);
  42. va_end(ap);
  43. }
  44. void pr_warn(const char *fmt, ...) {
  45. va_list ap;
  46. va_start(ap, fmt);
  47. pr_do(stderr, "warn", fmt, ap);
  48. va_end(ap);
  49. }
  50. void pr_err(const char *fmt, ...) {
  51. va_list ap;
  52. va_start(ap, fmt);
  53. pr_do(stderr, "error", fmt, ap);
  54. va_end(ap);
  55. }
  56. static void pr_do(FILE *stream,
  57. const char *label,
  58. const char *fmt,
  59. va_list ap) {
  60. char fmtbuf[1024];
  61. vsnprintf(fmtbuf, sizeof(fmtbuf), fmt, ap);
  62. fprintf(stream, "%s:%s: %s\n", _getprogname(), label, fmtbuf);
  63. }