util.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * Copyright (C) 2002-2005 Roman Zippel <zippel@linux-m68k.org>
  3. * Copyright (C) 2002-2005 Sam Ravnborg <sam@ravnborg.org>
  4. *
  5. * Released under the terms of the GNU GPL v2.0.
  6. */
  7. #include <string.h>
  8. #include "lkc.h"
  9. /* file already present in list? If not add it */
  10. struct file *file_lookup(const char *name)
  11. {
  12. struct file *file;
  13. for (file = file_list; file; file = file->next) {
  14. if (!strcmp(name, file->name))
  15. return file;
  16. }
  17. file = malloc(sizeof(*file));
  18. memset(file, 0, sizeof(*file));
  19. file->name = strdup(name);
  20. file->next = file_list;
  21. file_list = file;
  22. return file;
  23. }
  24. /* write a dependency file as used by kbuild to track dependencies */
  25. int file_write_dep(const char *name)
  26. {
  27. struct file *file;
  28. FILE *out;
  29. if (!name)
  30. name = ".kconfig.d";
  31. out = fopen("..config.tmp", "w");
  32. if (!out)
  33. return 1;
  34. fprintf(out, "deps_config := \\\n");
  35. for (file = file_list; file; file = file->next) {
  36. if (file->next)
  37. fprintf(out, "\t%s \\\n", file->name);
  38. else
  39. fprintf(out, "\t%s\n", file->name);
  40. }
  41. fprintf(out,
  42. "\n"
  43. ".config include/autoconf.h: $(deps_config)\n"
  44. "\n"
  45. "include/autoconf.h: .config\n" /* bbox */
  46. "\n"
  47. "$(deps_config):\n");
  48. fclose(out);
  49. rename("..config.tmp", name);
  50. return 0;
  51. }
  52. /* Allocate initial growable string */
  53. struct gstr str_new(void)
  54. {
  55. struct gstr gs;
  56. gs.s = malloc(sizeof(char) * 64);
  57. gs.len = 16;
  58. strcpy(gs.s, "\0");
  59. return gs;
  60. }
  61. /* Allocate and assign growable string */
  62. struct gstr str_assign(const char *s)
  63. {
  64. struct gstr gs;
  65. gs.s = strdup(s);
  66. gs.len = strlen(s) + 1;
  67. return gs;
  68. }
  69. /* Free storage for growable string */
  70. void str_free(struct gstr *gs)
  71. {
  72. free(gs->s);
  73. gs->s = NULL;
  74. gs->len = 0;
  75. }
  76. /* Append to growable string */
  77. void str_append(struct gstr *gs, const char *s)
  78. {
  79. size_t l = strlen(gs->s) + strlen(s) + 1;
  80. if (l > gs->len) {
  81. gs->s = realloc(gs->s, l);
  82. gs->len = l;
  83. }
  84. strcat(gs->s, s);
  85. }
  86. /* Append printf formatted string to growable string */
  87. void str_printf(struct gstr *gs, const char *fmt, ...)
  88. {
  89. va_list ap;
  90. char s[10000]; /* big enough... */
  91. va_start(ap, fmt);
  92. vsnprintf(s, sizeof(s), fmt, ap);
  93. str_append(gs, s);
  94. va_end(ap);
  95. }
  96. /* Retrieve value of growable string */
  97. const char *str_get(struct gstr *gs)
  98. {
  99. return gs->s;
  100. }