2011-08-26 Pedro Alves <pedro@codesourcery.com>
[platform/upstream/binutils.git] / gdb / common / linux-osdata.c
1 /* Linux-specific functions to retrieve OS data.
2    
3    Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #ifdef GDBSERVER
21 #include "server.h"
22 #else
23 #include "defs.h"
24 #endif
25
26 #include "linux-osdata.h"
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <dirent.h>
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <utmp.h>
35 #include <time.h>
36 #include <unistd.h>
37 #include <pwd.h>
38 #include <grp.h>
39 #include <netdb.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42
43 #include "xml-utils.h"
44 #include "buffer.h"
45 #include "gdb_assert.h"
46 #include "gdb_dirent.h"
47
48 int
49 linux_common_core_of_thread (ptid_t ptid)
50 {
51   char filename[sizeof ("/proc//task//stat")
52                  + 2 * 20 /* decimal digits for 2 numbers, max 2^64 bit each */
53                  + 1];
54   FILE *f;
55   char *content = NULL;
56   char *p;
57   char *ts = 0;
58   int content_read = 0;
59   int i;
60   int core;
61
62   sprintf (filename, "/proc/%d/task/%ld/stat",
63            ptid_get_pid (ptid), ptid_get_lwp (ptid));
64   f = fopen (filename, "r");
65   if (!f)
66     return -1;
67
68   for (;;)
69     {
70       int n;
71       content = xrealloc (content, content_read + 1024);
72       n = fread (content + content_read, 1, 1024, f);
73       content_read += n;
74       if (n < 1024)
75         {
76           content[content_read] = '\0';
77           break;
78         }
79     }
80
81   p = strchr (content, '(');
82
83   /* Skip ")".  */
84   if (p != NULL)
85     p = strchr (p, ')');
86   if (p != NULL)
87     p++;
88
89   /* If the first field after program name has index 0, then core number is
90      the field with index 36.  There's no constant for that anywhere.  */
91   if (p != NULL)
92     p = strtok_r (p, " ", &ts);
93   for (i = 0; p != NULL && i != 36; ++i)
94     p = strtok_r (NULL, " ", &ts);
95
96   if (p == NULL || sscanf (p, "%d", &core) == 0)
97     core = -1;
98
99   xfree (content);
100   fclose (f);
101
102   return core;
103 }
104
105 static void
106 command_from_pid (char *command, int maxlen, pid_t pid)
107 {
108   char *stat_path = xstrprintf ("/proc/%d/stat", pid); 
109   FILE *fp = fopen (stat_path, "r");
110   
111   command[0] = '\0';
112  
113   if (fp)
114     {
115       /* sizeof (cmd) should be greater or equal to TASK_COMM_LEN (in
116          include/linux/sched.h in the Linux kernel sources) plus two
117          (for the brackets).  */
118       char cmd[32]; 
119       pid_t stat_pid;
120       int items_read = fscanf (fp, "%d %32s", &stat_pid, cmd);
121           
122       if (items_read == 2 && pid == stat_pid)
123         {
124           cmd[strlen (cmd) - 1] = '\0'; /* Remove trailing parenthesis.  */
125           strncpy (command, cmd + 1, maxlen); /* Ignore leading parenthesis.  */
126         }
127
128       fclose (fp);
129     }
130   else
131     {
132       /* Return the PID if a /proc entry for the process cannot be found.  */
133       snprintf (command, maxlen, "%d", pid);
134     }
135
136   command[maxlen - 1] = '\0'; /* Ensure string is null-terminated.  */
137         
138   xfree (stat_path);
139 }
140
141 /* Returns the command-line of the process with the given PID. The returned
142    string needs to be freed using xfree after use.  */
143
144 static char *
145 commandline_from_pid (pid_t pid)
146 {
147   char *pathname = xstrprintf ("/proc/%d/cmdline", pid);
148   char *commandline = NULL;
149   FILE *f = fopen (pathname, "r");
150
151   if (f)
152     {
153       size_t len = 0;
154
155       while (!feof (f))
156         {
157           char buf[1024];
158           size_t read_bytes = fread (buf, 1, sizeof (buf), f);
159      
160           if (read_bytes)
161             {
162               commandline = (char *) xrealloc (commandline, len + read_bytes + 1);
163               memcpy (commandline + len, buf, read_bytes);
164               len += read_bytes;
165             }
166         }
167
168       fclose (f);
169
170       if (commandline)
171         {
172           size_t i;
173
174           /* Replace null characters with spaces.  */
175           for (i = 0; i < len; ++i)
176             if (commandline[i] == '\0')
177               commandline[i] = ' ';
178
179           commandline[len] = '\0';
180         }
181       else
182         {
183           /* Return the command in square brackets if the command-line is empty.  */
184           commandline = (char *) xmalloc (32);
185           commandline[0] = '[';
186           command_from_pid (commandline + 1, 31, pid);
187
188           len = strlen (commandline);
189           if (len < 31)
190             strcat (commandline, "]");
191         }
192     }
193
194   xfree (pathname);
195
196   return commandline;
197 }
198
199 static void
200 user_from_uid (char *user, int maxlen, uid_t uid)
201 {
202   struct passwd *pwentry = getpwuid (uid);
203   
204   if (pwentry)
205     {
206       strncpy (user, pwentry->pw_name, maxlen);
207       user[maxlen - 1] = '\0'; /* Ensure that the user name is null-terminated.  */
208     }
209   else
210     user[0] = '\0';
211 }
212
213 static int
214 get_process_owner (uid_t *owner, pid_t pid)
215 {
216   struct stat statbuf;
217   char procentry[sizeof ("/proc/4294967295")];
218
219   sprintf (procentry, "/proc/%d", pid);
220   
221   if (stat (procentry, &statbuf) == 0 && S_ISDIR (statbuf.st_mode))
222     {
223       *owner = statbuf.st_uid;
224       return 0;
225     }
226   else
227     return -1;
228 }
229
230 static int
231 get_number_of_cpu_cores (void)
232 {
233   int cores = 0;
234   FILE *f = fopen ("/proc/cpuinfo", "r");
235
236   while (!feof (f))
237     {
238       char buf[512];
239       char *p = fgets (buf, sizeof (buf), f);
240
241       if (p && strncmp (buf, "processor", 9) == 0)
242         ++cores;
243     }
244
245   fclose (f);
246
247   return cores;
248 }
249
250 /* CORES points to an array of at least get_number_of_cpu_cores () elements.  */
251
252 static int
253 get_cores_used_by_process (pid_t pid, int *cores)
254 {
255   char taskdir[sizeof ("/proc/4294967295/task")];
256   DIR *dir;
257   struct dirent *dp;
258   int task_count = 0;
259
260   sprintf (taskdir, "/proc/%d/task", pid);
261   dir = opendir (taskdir);
262   if (dir)
263     {
264       while ((dp = readdir (dir)) != NULL)
265         {
266           pid_t tid;
267           int core;
268
269           if (!isdigit (dp->d_name[0])
270               || NAMELEN (dp) > sizeof ("4294967295") - 1)
271             continue;
272
273           tid = atoi (dp->d_name);
274           core = linux_common_core_of_thread (ptid_build (pid, tid, 0));
275
276           if (core >= 0)
277             {
278               ++cores[core];
279               ++task_count;
280             }
281         }
282
283       closedir (dir);
284     }
285
286   return task_count;
287 }
288
289 static LONGEST
290 linux_xfer_osdata_processes (gdb_byte *readbuf,
291                              ULONGEST offset, LONGEST len)
292 {
293   /* We make the process list snapshot when the object starts to be read.  */
294   static const char *buf;
295   static LONGEST len_avail = -1;
296   static struct buffer buffer;
297
298   if (offset == 0)
299     {
300       DIR *dirp;
301
302       if (len_avail != -1 && len_avail != 0)
303         buffer_free (&buffer);
304       len_avail = 0;
305       buf = NULL;
306       buffer_init (&buffer);
307       buffer_grow_str (&buffer, "<osdata type=\"processes\">\n");
308
309       dirp = opendir ("/proc");
310       if (dirp)
311         {
312           const int num_cores = get_number_of_cpu_cores ();
313           struct dirent *dp;
314
315           while ((dp = readdir (dirp)) != NULL)
316             {
317               pid_t pid;
318               uid_t owner;
319               char user[UT_NAMESIZE];
320               char *command_line;
321               int *cores;
322               int task_count;
323               char *cores_str;
324               int i;
325
326               if (!isdigit (dp->d_name[0])
327                   || NAMELEN (dp) > sizeof ("4294967295") - 1)
328                 continue;
329
330               sscanf (dp->d_name, "%d", &pid);
331               command_line = commandline_from_pid (pid);
332
333               if (get_process_owner (&owner, pid) == 0)
334                 user_from_uid (user, sizeof (user), owner);
335               else
336                 strcpy (user, "?");
337
338               /* Find CPU cores used by the process.  */
339               cores = (int *) xcalloc (num_cores, sizeof (int));
340               task_count = get_cores_used_by_process (pid, cores);
341               cores_str = (char *) xcalloc (task_count, sizeof ("4294967295") + 1);
342
343               for (i = 0; i < num_cores && task_count > 0; ++i)
344                 if (cores[i])
345                   {
346                     char core_str[sizeof ("4294967205")];
347
348                     sprintf (core_str, "%d", i);
349                     strcat (cores_str, core_str);
350
351                     task_count -= cores[i];
352                     if (task_count > 0)
353                       strcat (cores_str, ",");
354                   }
355
356               xfree (cores);
357               
358               buffer_xml_printf (
359                   &buffer,
360                   "<item>"
361                   "<column name=\"pid\">%d</column>"
362                   "<column name=\"user\">%s</column>"
363                   "<column name=\"command\">%s</column>"
364                   "<column name=\"cores\">%s</column>"
365                   "</item>",
366                   pid,
367                   user,
368                   command_line ? command_line : "",
369                   cores_str);
370
371               xfree (command_line);     
372               xfree (cores_str);
373             }
374           
375           closedir (dirp);
376         }
377
378       buffer_grow_str0 (&buffer, "</osdata>\n");
379       buf = buffer_finish (&buffer);
380       len_avail = strlen (buf);
381     }
382
383   if (offset >= len_avail)
384     {
385       /* Done.  Get rid of the buffer.  */
386       buffer_free (&buffer);
387       buf = NULL;
388       len_avail = 0;
389       return 0;
390     }
391
392   if (len > len_avail - offset)
393     len = len_avail - offset;
394   memcpy (readbuf, buf + offset, len);
395
396   return len;
397 }
398
399 static LONGEST
400 linux_xfer_osdata_threads (gdb_byte *readbuf,
401                            ULONGEST offset, LONGEST len)
402 {
403   /* We make the process list snapshot when the object starts to be read.  */
404   static const char *buf;
405   static LONGEST len_avail = -1;
406   static struct buffer buffer;
407
408   if (offset == 0)
409     {
410       DIR *dirp;
411
412       if (len_avail != -1 && len_avail != 0)
413         buffer_free (&buffer);
414       len_avail = 0;
415       buf = NULL;
416       buffer_init (&buffer);
417       buffer_grow_str (&buffer, "<osdata type=\"threads\">\n");
418
419       dirp = opendir ("/proc");
420       if (dirp)
421         {
422           struct dirent *dp;
423
424           while ((dp = readdir (dirp)) != NULL)
425             {
426               struct stat statbuf;
427               char procentry[sizeof ("/proc/4294967295")];
428
429               if (!isdigit (dp->d_name[0])
430                   || NAMELEN (dp) > sizeof ("4294967295") - 1)
431                 continue;
432
433               sprintf (procentry, "/proc/%s", dp->d_name);
434               if (stat (procentry, &statbuf) == 0
435                   && S_ISDIR (statbuf.st_mode))
436                 {
437                   DIR *dirp2;
438                   char *pathname;
439                   pid_t pid;
440                   char command[32];
441
442                   pathname = xstrprintf ("/proc/%s/task", dp->d_name);
443                   
444                   pid = atoi (dp->d_name);
445                   command_from_pid (command, sizeof (command), pid);
446
447                   dirp2 = opendir (pathname);
448
449                   if (dirp2)
450                     {
451                       struct dirent *dp2;
452
453                       while ((dp2 = readdir (dirp2)) != NULL)
454                         {
455                           pid_t tid;
456                           int core;
457
458                           if (!isdigit (dp2->d_name[0])
459                               || NAMELEN (dp2) > sizeof ("4294967295") - 1)
460                             continue;
461
462                           tid = atoi (dp2->d_name);
463                           core = linux_common_core_of_thread (ptid_build (pid, tid, 0));
464
465                           buffer_xml_printf (
466                             &buffer,
467                             "<item>"
468                             "<column name=\"pid\">%d</column>"
469                             "<column name=\"command\">%s</column>"
470                             "<column name=\"tid\">%d</column>"
471                             "<column name=\"core\">%d</column>"
472                             "</item>",
473                             pid,
474                             command,
475                             tid,
476                             core);
477                         }
478
479                       closedir (dirp2);
480                     }
481
482                   xfree (pathname);
483                 }
484             }
485
486           closedir (dirp);
487         }
488
489       buffer_grow_str0 (&buffer, "</osdata>\n");
490       buf = buffer_finish (&buffer);
491       len_avail = strlen (buf);
492     }
493
494   if (offset >= len_avail)
495     {
496       /* Done.  Get rid of the buffer.  */
497       buffer_free (&buffer);
498       buf = NULL;
499       len_avail = 0;
500       return 0;
501     }
502
503   if (len > len_avail - offset)
504     len = len_avail - offset;
505   memcpy (readbuf, buf + offset, len);
506
507   return len;
508 }
509
510 struct osdata_type {
511   char *type;
512   char *description;
513   LONGEST (*getter) (gdb_byte *readbuf, ULONGEST offset, LONGEST len);
514 } osdata_table[] = {
515   { "processes", "Listing of all processes", linux_xfer_osdata_processes },
516   { "threads", "Listing of all threads", linux_xfer_osdata_threads },
517   { NULL, NULL, NULL }
518 };
519
520 LONGEST
521 linux_common_xfer_osdata (const char *annex, gdb_byte *readbuf,
522                           ULONGEST offset, LONGEST len)
523 {
524   if (!annex || *annex == '\0')
525     {
526       static const char *buf;
527       static LONGEST len_avail = -1;
528       static struct buffer buffer;
529
530       if (offset == 0)
531         {
532           int i;
533
534           if (len_avail != -1 && len_avail != 0)
535             buffer_free (&buffer);
536           len_avail = 0;
537           buf = NULL;
538           buffer_init (&buffer);
539           buffer_grow_str (&buffer, "<osdata type=\"types\">\n");
540
541           for (i = 0; osdata_table[i].type; ++i)
542             buffer_xml_printf (
543                                &buffer,
544                                "<item>"
545                                "<column name=\"Type\">%s</column>"
546                                "<column name=\"Description\">%s</column>"
547                                "</item>",
548                                osdata_table[i].type,
549                                osdata_table[i].description);
550
551           buffer_grow_str0 (&buffer, "</osdata>\n");
552           buf = buffer_finish (&buffer);
553           len_avail = strlen (buf);
554         }
555
556       if (offset >= len_avail)
557         {
558           /* Done.  Get rid of the buffer.  */
559           buffer_free (&buffer);
560           buf = NULL;
561           len_avail = 0;
562           return 0;
563         }
564
565       if (len > len_avail - offset)
566         len = len_avail - offset;
567       memcpy (readbuf, buf + offset, len);
568
569       return len;
570     }
571   else
572     {
573       int i;
574
575       for (i = 0; osdata_table[i].type; ++i)
576         {
577           if (strcmp (annex, osdata_table[i].type) == 0)
578             {
579               gdb_assert (readbuf);
580               
581               return (osdata_table[i].getter) (readbuf, offset, len);
582             }
583         }
584
585       return 0;
586     }
587 }
588