thread.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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->comm = malloc(32);
  16. if (self->comm)
  17. snprintf(self->comm, 32, ":%d", self->pid);
  18. }
  19. return self;
  20. }
  21. void thread__delete(struct thread *self)
  22. {
  23. map_groups__exit(&self->mg);
  24. free(self->comm);
  25. free(self);
  26. }
  27. int thread__set_comm(struct thread *self, const char *comm)
  28. {
  29. int err;
  30. if (self->comm)
  31. free(self->comm);
  32. self->comm = strdup(comm);
  33. err = self->comm == NULL ? -ENOMEM : 0;
  34. if (!err) {
  35. self->comm_set = true;
  36. }
  37. return err;
  38. }
  39. int thread__comm_len(struct thread *self)
  40. {
  41. if (!self->comm_len) {
  42. if (!self->comm)
  43. return 0;
  44. self->comm_len = strlen(self->comm);
  45. }
  46. return self->comm_len;
  47. }
  48. static size_t thread__fprintf(struct thread *self, FILE *fp)
  49. {
  50. return fprintf(fp, "Thread %d %s\n", self->pid, self->comm) +
  51. map_groups__fprintf(&self->mg, verbose, fp);
  52. }
  53. void thread__insert_map(struct thread *self, struct map *map)
  54. {
  55. map_groups__fixup_overlappings(&self->mg, map, verbose, stderr);
  56. map_groups__insert(&self->mg, map);
  57. }
  58. int thread__fork(struct thread *self, struct thread *parent)
  59. {
  60. int i;
  61. if (parent->comm_set) {
  62. if (self->comm)
  63. free(self->comm);
  64. self->comm = strdup(parent->comm);
  65. if (!self->comm)
  66. return -ENOMEM;
  67. self->comm_set = true;
  68. }
  69. for (i = 0; i < MAP__NR_TYPES; ++i)
  70. if (map_groups__clone(&self->mg, &parent->mg, i) < 0)
  71. return -ENOMEM;
  72. return 0;
  73. }
  74. size_t machine__fprintf(struct machine *machine, FILE *fp)
  75. {
  76. size_t ret = 0;
  77. struct rb_node *nd;
  78. for (nd = rb_first(&machine->threads); nd; nd = rb_next(nd)) {
  79. struct thread *pos = rb_entry(nd, struct thread, rb_node);
  80. ret += thread__fprintf(pos, fp);
  81. }
  82. return ret;
  83. }