util.c 1.5 KB

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