util.c 1.3 KB

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