thread.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "../perf.h"
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "session.h"
  6. #include "thread.h"
  7. #include "util.h"
  8. #include "debug.h"
  9. struct thread *thread__new(pid_t pid)
  10. {
  11. struct thread *self = zalloc(sizeof(*self));
  12. if (self != NULL) {
  13. map_groups__init(&self->mg);
  14. self->pid = pid;
  15. self->ppid = -1;
  16. self->comm = malloc(32);
  17. if (self->comm)
  18. snprintf(self->comm, 32, ":%d", self->pid);
  19. }
  20. return self;
  21. }
  22. void thread__delete(struct thread *self)
  23. {
  24. map_groups__exit(&self->mg);
  25. free(self->comm);
  26. free(self);
  27. }
  28. int thread__set_comm(struct thread *self, const char *comm)
  29. {
  30. int err;
  31. if (self->comm)
  32. free(self->comm);
  33. self->comm = strdup(comm);
  34. err = self->comm == NULL ? -ENOMEM : 0;
  35. if (!err) {
  36. self->comm_set = true;
  37. }
  38. return err;
  39. }
  40. int thread__comm_len(struct thread *self)
  41. {
  42. if (!self->comm_len) {
  43. if (!self->comm)
  44. return 0;
  45. self->comm_len = strlen(self->comm);
  46. }
  47. return self->comm_len;
  48. }
  49. size_t thread__fprintf(struct thread *thread, FILE *fp)
  50. {
  51. return fprintf(fp, "Thread %d %s\n", thread->pid, thread->comm) +
  52. map_groups__fprintf(&thread->mg, verbose, fp);
  53. }
  54. void thread__insert_map(struct thread *self, struct map *map)
  55. {
  56. map_groups__fixup_overlappings(&self->mg, map, verbose, stderr);
  57. map_groups__insert(&self->mg, map);
  58. }
  59. int thread__fork(struct thread *self, struct thread *parent)
  60. {
  61. int i;
  62. if (parent->comm_set) {
  63. if (self->comm)
  64. free(self->comm);
  65. self->comm = strdup(parent->comm);
  66. if (!self->comm)
  67. return -ENOMEM;
  68. self->comm_set = true;
  69. }
  70. for (i = 0; i < MAP__NR_TYPES; ++i)
  71. if (map_groups__clone(&self->mg, &parent->mg, i) < 0)
  72. return -ENOMEM;
  73. self->ppid = parent->pid;
  74. return 0;
  75. }