util.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 "win.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. strcpy(u, s);
  38. strcat(u, t);
  39. return u;
  40. }
  41. char*
  42. estrstrstrdup(char *r, char *s, char *t)
  43. {
  44. char *u;
  45. u = emalloc(strlen(r)+strlen(s)+strlen(t)+1);
  46. strcpy(u, r);
  47. strcat(u, s);
  48. strcat(u, t);
  49. return u;
  50. }
  51. char*
  52. eappend(char *s, char *sep, char *t)
  53. {
  54. char *u;
  55. if(t == nil)
  56. u = estrstrdup(s, sep);
  57. else{
  58. u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
  59. strcpy(u, s);
  60. strcat(u, sep);
  61. strcat(u, t);
  62. }
  63. free(s);
  64. return u;
  65. }
  66. char*
  67. egrow(char *s, char *sep, char *t)
  68. {
  69. s = eappend(s, sep, t);
  70. free(t);
  71. return s;
  72. }
  73. void
  74. error(char *fmt, ...)
  75. {
  76. va_list arg;
  77. char buf[256];
  78. Fmt f;
  79. fmtfdinit(&f, 2, buf, sizeof buf);
  80. fmtprint(&f, "%s: ", argv0);
  81. va_start(arg, fmt);
  82. fmtprint(&f, fmt, arg);
  83. va_end(arg);
  84. fmtprint(&f, "\n");
  85. fmtfdflush(&f);
  86. threadexitsall(fmt);
  87. }
  88. void
  89. ctlprint(int fd, char *fmt, ...)
  90. {
  91. int n;
  92. va_list arg;
  93. char buf[256];
  94. va_start(arg, fmt);
  95. n = vfprint(fd, fmt, arg);
  96. va_end(arg);
  97. if(n < 0)
  98. error("control file write(%s) error: %r", buf);
  99. }