util.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include <thread.h>
  13. #include <plumb.h>
  14. #include "dat.h"
  15. void*
  16. emalloc(uint n)
  17. {
  18. void *p;
  19. p = malloc(n);
  20. if(p == nil)
  21. error("can't malloc: %r");
  22. memset(p, 0, n);
  23. setmalloctag(p, getcallerpc(&n));
  24. return p;
  25. }
  26. void*
  27. erealloc(void *p, uint n)
  28. {
  29. p = realloc(p, n);
  30. if(p == nil)
  31. error("can't realloc: %r");
  32. setmalloctag(p, getcallerpc(&n));
  33. return p;
  34. }
  35. char*
  36. estrdup(char *s)
  37. {
  38. char *t;
  39. t = emalloc(strlen(s)+1);
  40. strcpy(t, s);
  41. return t;
  42. }
  43. char*
  44. estrstrdup(char *s, char *t)
  45. {
  46. char *u;
  47. u = emalloc(strlen(s)+strlen(t)+1);
  48. strcpy(u, s);
  49. strcat(u, t);
  50. return u;
  51. }
  52. char*
  53. eappend(char *s, char *sep, char *t)
  54. {
  55. char *u;
  56. if(t == nil)
  57. u = estrstrdup(s, sep);
  58. else{
  59. u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
  60. strcpy(u, s);
  61. strcat(u, sep);
  62. strcat(u, t);
  63. }
  64. free(s);
  65. return u;
  66. }
  67. char*
  68. egrow(char *s, char *sep, char *t)
  69. {
  70. s = eappend(s, sep, t);
  71. free(t);
  72. return s;
  73. }
  74. void
  75. error(char *fmt, ...)
  76. {
  77. Fmt f;
  78. char buf[64];
  79. va_list arg;
  80. fmtfdinit(&f, 2, buf, sizeof buf);
  81. fmtprint(&f, "Mail: ");
  82. va_start(arg, fmt);
  83. fmtvprint(&f, fmt, arg);
  84. va_end(arg);
  85. fmtprint(&f, "\n");
  86. fmtfdflush(&f);
  87. threadexitsall(fmt);
  88. }
  89. void
  90. ctlprint(int fd, char *fmt, ...)
  91. {
  92. int n;
  93. va_list arg;
  94. va_start(arg, fmt);
  95. n = vfprint(fd, fmt, arg);
  96. va_end(arg);
  97. if(n <= 0)
  98. error("control file write error: %r");
  99. }