util.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <bio.h>
  4. #include <thread.h>
  5. #include <plumb.h>
  6. #include "dat.h"
  7. void*
  8. emalloc(uint n)
  9. {
  10. void *p;
  11. p = malloc(n);
  12. if(p == nil)
  13. error("can't malloc: %r");
  14. memset(p, 0, n);
  15. setmalloctag(p, getcallerpc(&n));
  16. return p;
  17. }
  18. void*
  19. erealloc(void *p, uint n)
  20. {
  21. p = realloc(p, n);
  22. if(p == nil)
  23. error("can't realloc: %r");
  24. setmalloctag(p, getcallerpc(&n));
  25. return p;
  26. }
  27. char*
  28. estrdup(char *s)
  29. {
  30. char *t;
  31. t = emalloc(strlen(s)+1);
  32. strcpy(t, s);
  33. return t;
  34. }
  35. char*
  36. estrstrdup(char *s, char *t)
  37. {
  38. char *u;
  39. u = emalloc(strlen(s)+strlen(t)+1);
  40. strcpy(u, s);
  41. strcat(u, t);
  42. return u;
  43. }
  44. char*
  45. eappend(char *s, char *sep, char *t)
  46. {
  47. char *u;
  48. if(t == nil)
  49. u = estrstrdup(s, sep);
  50. else{
  51. u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
  52. strcpy(u, s);
  53. strcat(u, sep);
  54. strcat(u, t);
  55. }
  56. free(s);
  57. return u;
  58. }
  59. char*
  60. egrow(char *s, char *sep, char *t)
  61. {
  62. s = eappend(s, sep, t);
  63. free(t);
  64. return s;
  65. }
  66. void
  67. error(char *fmt, ...)
  68. {
  69. Fmt f;
  70. char buf[64];
  71. va_list arg;
  72. fmtfdinit(&f, 2, buf, sizeof buf);
  73. fmtprint(&f, "Mail: ");
  74. va_start(arg, fmt);
  75. fmtvprint(&f, fmt, arg);
  76. va_end(arg);
  77. fmtprint(&f, "\n");
  78. fmtfdflush(&f);
  79. threadexitsall(fmt);
  80. }
  81. void
  82. ctlprint(int fd, char *fmt, ...)
  83. {
  84. int n;
  85. va_list arg;
  86. va_start(arg, fmt);
  87. n = vfprint(fd, fmt, arg);
  88. va_end(arg);
  89. if(n <= 0)
  90. error("control file write error: %r");
  91. }