draft
[gdbmicli.git] / libmigdb / src / connect.c
1 /**[txh]********************************************************************
2
3   Copyright (c) 2004-2009 by Salvador E. Tropea.
4   Covered by the GPL license.
5
6   Module: Connect.
7   Comments:
8   This module handles the dialog with gdb, including starting and stopping
9 gdb.@p
10
11 GDB Bug workaround for "file -readnow": I tried to workaround a bug using
12 it but looks like this option also have bugs!!!! so I have to use the
13 command line option --readnow.
14 It also have a bug!!!! when the binary is changed and gdb must reload it
15 this option is ignored. So it looks like we have no solution but 3 gdb bugs
16 in a row.
17
18 ***************************************************************************/
19
20 #define _GNU_SOURCE
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <sys/wait.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <stdarg.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <signal.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include "mi_gdb.h"
35
36 #ifndef TEMP_FAILURE_RETRY
37  #define TEMP_FAILURE_RETRY(a) (a)
38 #endif
39
40 int mi_error=MI_OK;
41 char *mi_error_from_gdb=NULL;
42 static char *gdb_exe=NULL;
43 static char *xterm_exe=NULL;
44 static char *gdb_start=NULL;
45 static char *gdb_conn=NULL;
46 static char *main_func=NULL;
47 static char  disable_psym_search_workaround=0;
48
49 mi_h *mi_alloc_h()
50 {
51  mi_h *h=(mi_h *)calloc(1,sizeof(mi_h));
52  if (!h)
53    {
54     mi_error=MI_OUT_OF_MEMORY;
55     return NULL;
56    }
57  h->to_gdb[0]=h->to_gdb[1]=h->from_gdb[0]=h->from_gdb[1]=-1;
58  h->pid=-1;
59  return h;
60 }
61
62 int mi_check_running_pid(pid_t pid)
63 {
64  int status;
65
66  if (pid<=0)
67     return 0;
68  /* If waitpid returns the number of our child means it communicated
69     to as a termination status. */
70  if (waitpid(pid,&status,WNOHANG)==pid)
71    {
72     pid=0;
73     return 0;
74    }
75  return 1;
76 }
77
78 int mi_check_running(mi_h *h)
79 {
80  return !h->died && mi_check_running_pid(h->pid);
81 }
82
83 void mi_kill_child(pid_t pid)
84 {
85  kill(pid,SIGTERM);
86  usleep(100000);
87  if (mi_check_running_pid(pid))
88    {
89     int status;
90     kill(pid,SIGKILL);
91     waitpid(pid,&status,0);
92    }
93 }
94
95 void mi_free_h(mi_h **handle)
96 {
97  mi_h *h=*handle;
98  if (h->to_gdb[0]>=0)
99     close(h->to_gdb[0]);
100  if (h->to)
101     fclose(h->to);
102  else if (h->to_gdb[1]>=0)
103     close(h->to_gdb[1]);
104  if (h->from)
105     fclose(h->from);
106  else if (h->from_gdb[0]>=0)
107     close(h->from_gdb[0]);
108  if (h->from_gdb[1]>=0)
109     close(h->from_gdb[1]);
110  if (mi_check_running(h))
111    {/* GDB is running! */
112     mi_kill_child(h->pid);
113    }
114  if (h->line)
115     free(h->line);
116  mi_free_output(h->po);
117  free(h->catched_console);
118  free(h);
119  *handle=NULL;
120 }
121
122 void mi_set_nonblk(int h)
123 {
124  int flf;
125  flf=fcntl(h,F_GETFL,0);
126  flf=flf | O_NONBLOCK;
127 // fcntl(h,F_SETFL,flf);
128 }
129
130 int mi_getline(mi_h *h)
131 {
132  char c;
133
134  while (read(h->from_gdb[0],&c,1)==1)
135    {
136     if (h->lread>=h->llen)
137       {
138        h->llen=h->lread+128;
139        h->line=(char *)realloc(h->line,h->llen);
140        if (!h->line)
141          {
142           h->llen=0;
143           h->lread=0;
144           return -1;
145          }
146       }
147     if (c=='\n')
148       {
149        int ret=h->lread;
150        h->line[ret]=0;
151        h->lread=0;
152        return ret;
153       }
154     if (c!='\r')
155       {
156        h->line[h->lread]=c;
157        h->lread++;
158       }
159    }
160  return 0;
161 }
162
163 char *get_cstr(mi_output *o)
164 {
165  if (!o->c || o->c->type!=t_const)
166     return NULL;
167  return o->c->v.cstr;
168 }
169
170 int mi_get_response(mi_h *h)
171 {
172  int l=mi_getline(h);
173  if (!l)
174     return 0;
175
176  if (h->from_gdb_echo)
177     h->from_gdb_echo(h->line,h->from_gdb_echo_data);
178  if (strncmp(h->line,"(gdb)",5)==0)
179    {/* End of response. */
180     return 1;
181    }
182  else
183    {/* Add to the response. */
184     mi_output *o;
185     int add=1, is_exit=0;
186     o=mi_parse_gdb_output(h->line);
187
188     if (!o)
189        return 0;
190     /* Tunneled streams callbacks. */
191     if (o->type==MI_T_OUT_OF_BAND && o->stype==MI_ST_STREAM)
192       {
193        char *aux;
194        add=0;
195        switch (o->sstype)
196          {
197           case MI_SST_CONSOLE:
198                aux=get_cstr(o);
199                if (h->console)
200                   h->console(aux,h->console_data);
201                if (h->catch_console && aux)
202                  {
203                   h->catch_console--;
204                   if (!h->catch_console)
205                     {
206                      free(h->catched_console);
207                      h->catched_console=strdup(aux);
208                     }
209                  }
210                break;
211           case MI_SST_TARGET:
212                /* This one seems to be useless. */
213                if (h->target)
214                   h->target(get_cstr(o),h->target_data);
215                break;
216           case MI_SST_LOG:
217                if (h->log)
218                   h->log(get_cstr(o),h->log_data);
219                break;
220          }
221       }
222     else if (o->type==MI_T_OUT_OF_BAND && o->stype==MI_ST_ASYNC)
223       {
224        if (h->async)
225           h->async(o,h->async_data);
226       }
227     else if (o->type==MI_T_RESULT_RECORD && o->tclass==MI_CL_ERROR)
228       {/* Error from gdb, record it. */
229        mi_error=MI_FROM_GDB;
230        free(mi_error_from_gdb);
231        mi_error_from_gdb=NULL;
232        if (o->c && strcmp(o->c->var,"msg")==0 && o->c->type==t_const)
233           mi_error_from_gdb=strdup(o->c->v.cstr);
234       }
235     is_exit=(o->type==MI_T_RESULT_RECORD && o->tclass==MI_CL_EXIT);
236     /* Add to the list of responses. */
237     if (add)
238       {
239        if (h->last)
240           h->last->next=o;
241        else
242           h->po=o;
243        h->last=o;
244       }
245     else
246        mi_free_output(o);
247     /* Exit RR means gdb exited, we won't get a new prompt ;-) */
248     if (is_exit)
249        return 1;
250    }
251
252  return 0;
253 }
254
255 mi_output *mi_retire_response(mi_h *h)
256 {
257  mi_output *ret=h->po;
258  h->po=h->last=NULL;
259  return ret;
260 }
261
262 mi_output *mi_get_response_blk(mi_h *h)
263 {
264  int r;
265  /* Sometimes gdb dies. */
266  if (!mi_check_running(h))
267    {
268     h->died=1;
269     mi_error=MI_GDB_DIED;
270     return NULL;
271    }
272  do
273    {
274     if (1)
275       {
276        /*
277         That's a must. If we just keep trying to read and failing things
278         become really sloooowwww. Instead we try and if it fails we wait
279         until something is available.
280         TODO: Implement something with the time out, a callback to ask the
281         application is we have to wait or not could be a good thing.
282        */
283        fd_set set;
284        struct timeval timeout;
285        int ret;
286
287        r=mi_get_response(h);
288        if (r)
289           return mi_retire_response(h);
290
291        FD_ZERO(&set);
292        FD_SET(h->from_gdb[0],&set);
293        timeout.tv_sec=h->time_out;
294        timeout.tv_usec=0;
295        ret=TEMP_FAILURE_RETRY(select(FD_SETSIZE,&set,NULL,NULL,&timeout));
296        if (!ret)
297          {
298           if (!mi_check_running(h))
299             {
300              h->died=1;
301              mi_error=MI_GDB_DIED;
302              return NULL;
303             }
304           if (h->time_out_cb)
305              ret=h->time_out_cb(h->time_out_cb_data);
306           if (!ret)
307             {
308              mi_error=MI_GDB_TIME_OUT;
309              return NULL;
310             }
311          }
312       }
313     else
314       {
315        r=mi_get_response(h);
316        if (r)
317           return mi_retire_response(h);
318        else
319           usleep(100);
320       }
321    }
322  while (!r);
323
324  return NULL;
325 }
326
327 void mi_send_commands(mi_h *h, const char *file)
328 {
329  FILE *f;
330  char b[PATH_MAX];
331
332  //printf("File: %s\n",file);
333  if (!file)
334     return;
335  f=fopen(file,"rt");
336  if (!f)
337     return;
338  while (!feof(f))
339    {
340     if (fgets(b,PATH_MAX,f))
341       {
342        //printf("Send: %s\n",b);
343        mi_send(h,b);
344        mi_res_simple_done(h);
345       }
346    }
347  fclose(f);
348 }
349
350 void mi_send_target_commands(mi_h *h)
351 {
352  mi_send_commands(h,gdb_conn);
353 }
354
355 /**[txh]********************************************************************
356
357   Description:
358   Connect to a local copy of gdb. Note that the mi_h structure is something
359 similar to a "FILE *" for stdio.
360   
361   Return: A new mi_h structure or NULL on error.
362   
363 ***************************************************************************/
364
365 mi_h *mi_connect_local()
366 {
367  mi_h *h;
368  const char *gdb=mi_get_gdb_exe();
369
370  /* Start without error. */
371  mi_error=MI_OK;
372  /* Verify we have a GDB binary. */
373  if (access(gdb,X_OK))
374    {
375     mi_error=MI_MISSING_GDB;
376     return NULL;
377    }
378  /* Alloc the handle structure. */
379  h=mi_alloc_h();
380  if (!h)
381     return h;
382  h->time_out=MI_DEFAULT_TIME_OUT;
383  /* Create the pipes to connect with the child. */
384  if (pipe(h->to_gdb) || pipe(h->from_gdb))
385    {
386     mi_error=MI_PIPE_CREATE;
387     mi_free_h(&h);
388     return NULL;
389    }
390  mi_set_nonblk(h->to_gdb[1]);
391  mi_set_nonblk(h->from_gdb[0]);
392  /* Associate streams to the file handles. */
393  h->to=fdopen(h->to_gdb[1],"w");
394  h->from=fdopen(h->from_gdb[0],"r");
395  if (!h->to || !h->from)
396    {
397     mi_error=MI_PIPE_CREATE;
398     mi_free_h(&h);
399     return NULL;
400    }
401  /* Create the child. */
402  h->pid=fork();
403  if (h->pid==0)
404    {/* We are the child. */
405     char *argv[5];
406     /* Connect stdin/out to the pipes. */
407     dup2(h->to_gdb[0],STDIN_FILENO);
408     dup2(h->from_gdb[1],STDOUT_FILENO);
409     /* Pass the control to gdb. */
410     argv[0]=(char *)gdb; /* Is that OK? */
411     argv[1]="--interpreter=mi";
412     argv[2]="--quiet";
413     argv[3]=disable_psym_search_workaround ? 0 : "--readnow";
414     argv[4]=0;
415     execvp(argv[0],argv);
416     /* We get here only if exec failed. */
417     _exit(127);
418    }
419  /* We are the parent. */
420  if (h->pid==-1)
421    {/* Fork failed. */
422     mi_error=MI_FORK;
423     mi_free_h(&h);
424     return NULL;
425    }
426  if (!mi_check_running(h))
427    {
428     mi_error=MI_DEBUGGER_RUN;
429     mi_free_h(&h);
430     return NULL;
431    }
432  /* Wait for the prompt. */
433  mi_get_response_blk(h);
434  /* Send the start-up commands */
435  mi_send_commands(h,gdb_start);
436
437  return h;
438 }
439
440 /**[txh]********************************************************************
441
442   Description:
443   Close connection. You should ask gdb to quit first @x{gmi_gdb_exit}.
444   
445 ***************************************************************************/
446
447 void mi_disconnect(mi_h *h)
448 {
449  mi_free_h(&h);
450  free(mi_error_from_gdb);
451  mi_error_from_gdb=NULL;
452 }
453
454 void mi_set_console_cb(mi_h *h, stream_cb cb, void *data)
455 {
456  h->console=cb;
457  h->console_data=data;
458 }
459
460 void mi_set_target_cb(mi_h *h, stream_cb cb, void *data)
461 {
462  h->target=cb;
463  h->target_data=data;
464 }
465
466 void mi_set_log_cb(mi_h *h, stream_cb cb, void *data)
467 {
468  h->log=cb;
469  h->log_data=data;
470 }
471
472 stream_cb mi_get_console_cb(mi_h *h, void **data)
473 {
474  if (data)
475     *data=h->console_data;
476  return h->console;
477 }
478
479 stream_cb mi_get_target_cb(mi_h *h, void **data)
480 {
481  if (data)
482     *data=h->target_data;
483  return h->target;
484 }
485
486 stream_cb mi_get_log_cb(mi_h *h, void **data)
487 {
488  if (data)
489     *data=h->log_data;
490  return h->log;
491 }
492
493 void mi_set_async_cb(mi_h *h, async_cb cb, void *data)
494 {
495  h->async=cb;
496  h->async_data=data;
497 }
498
499 async_cb mi_get_async_cb(mi_h *h, void **data)
500 {
501  if (data)
502     *data=h->async_data;
503  return h->async;
504 }
505
506 void mi_set_to_gdb_cb(mi_h *h, stream_cb cb, void *data)
507 {
508  h->to_gdb_echo=cb;
509  h->to_gdb_echo_data=data;
510 }
511
512 void mi_set_from_gdb_cb(mi_h *h, stream_cb cb, void *data)
513 {
514  h->from_gdb_echo=cb;
515  h->from_gdb_echo_data=data;
516 }
517
518 stream_cb mi_get_to_gdb_cb(mi_h *h, void **data)
519 {
520  if (data)
521     *data=h->to_gdb_echo_data;
522  return h->to_gdb_echo;
523 }
524
525 stream_cb mi_get_from_gdb_cb(mi_h *h, void **data)
526 {
527  if (data)
528     *data=h->from_gdb_echo_data;
529  return h->from_gdb_echo;
530 }
531
532 void mi_set_time_out_cb(mi_h *h, tm_cb cb, void *data)
533 {
534  h->time_out_cb=cb;
535  h->time_out_cb_data=data;
536 }
537
538 tm_cb mi_get_time_out_cb(mi_h *h, void **data)
539 {
540  if (data)
541     *data=h->time_out_cb_data;
542  return h->time_out_cb;
543 }
544
545 void mi_set_time_out(mi_h *h, int to)
546 {
547  h->time_out=to;
548 }
549
550 int mi_get_time_out(mi_h *h)
551 {
552  return h->time_out;
553 }
554
555 int mi_send(mi_h *h, const char *format, ...)
556 {
557  int ret;
558  char *str;
559  va_list argptr;
560
561  if (h->died)
562     return 0;
563
564  va_start(argptr,format);
565  ret=vasprintf(&str,format,argptr);
566  va_end(argptr);
567  fputs(str,h->to);
568  fflush(h->to);
569  if (h->to_gdb_echo)
570     h->to_gdb_echo(str,h->to_gdb_echo_data);
571  free(str);
572
573  return ret;
574 }
575
576 void mi_clean_up_globals()
577 {
578  free(gdb_exe);
579  gdb_exe=NULL;
580  free(xterm_exe);
581  xterm_exe=NULL;
582  free(gdb_start);
583  gdb_start=NULL;
584  free(gdb_conn);
585  gdb_conn=NULL;
586  free(main_func);
587  main_func=NULL;
588 }
589
590 void mi_register_exit()
591 {
592  static int registered=0;
593  if (!registered)
594    {
595     registered=1;
596     atexit(mi_clean_up_globals);
597    }
598 }
599
600 void mi_set_gdb_exe(const char *name)
601 {
602  free(gdb_exe);
603  gdb_exe=name ? strdup(name) : NULL;
604  mi_register_exit();
605 }
606
607 void mi_set_gdb_start(const char *name)
608 {
609  free(gdb_start);
610  gdb_start=name ? strdup(name) : NULL;
611  mi_register_exit();
612 }
613
614 void mi_set_gdb_conn(const char *name)
615 {
616  free(gdb_conn);
617  gdb_conn=name ? strdup(name) : NULL;
618  mi_register_exit();
619 }
620
621 static
622 char *mi_search_in_path(const char *file)
623 {
624  char *path, *pt, *r;
625  char test[PATH_MAX];
626  struct stat st;
627
628  path=getenv("PATH");
629  if (!path)
630     return NULL;
631  pt=strdup(path);
632  r=strtok(pt,":");
633  while (r)
634    {
635     strcpy(test,r);
636     strcat(test,"/");
637     strcat(test,file);
638     if (stat(test,&st)==0 && S_ISREG(st.st_mode))
639       {
640        free(pt);
641        return strdup(test);
642       }
643     r=strtok(NULL,":");
644    }
645  free(pt);
646  return NULL;
647 }
648
649 const char *mi_get_gdb_exe()
650 {
651  if (!gdb_exe)
652    {/* Look for gdb in path */
653     gdb_exe=mi_search_in_path("gdb");
654     if (!gdb_exe)
655        return "/usr/bin/gdb";
656    }
657  return gdb_exe;
658 }
659
660 const char *mi_get_gdb_start()
661 {
662  return gdb_start;
663 }
664
665 const char *mi_get_gdb_conn()
666 {
667  return gdb_conn;
668 }
669
670 void mi_set_xterm_exe(const char *name)
671 {
672  free(xterm_exe);
673  xterm_exe=name ? strdup(name) : NULL;
674  mi_register_exit();
675 }
676
677 const char *mi_get_xterm_exe()
678 {
679  if (!xterm_exe)
680    {/* Look for xterm in path */
681     xterm_exe=mi_search_in_path("xterm");
682     if (!xterm_exe)
683        return "/usr/bin/X11/xterm";
684    }
685  return xterm_exe;
686 }
687
688 void mi_set_main_func(const char *name)
689 {
690  free(main_func);
691  main_func=name ? strdup(name) : NULL;
692  mi_register_exit();
693 }
694
695 const char *mi_get_main_func()
696 {
697  if (main_func)
698     return main_func;
699  return "main";
700 }
701
702 /**[txh]********************************************************************
703
704   Description:
705   Opens a new xterm to be used by the child process to debug.
706   
707   Return: A new mi_aux_term structure, you can use @x{gmi_end_aux_term} to
708 release it.
709   
710 ***************************************************************************/
711
712 mi_aux_term *gmi_start_xterm()
713 {
714  char nsh[14]="/tmp/shXXXXXX";
715  char ntt[14]="/tmp/ttXXXXXX";
716  const char *xterm;
717  struct stat st;
718  int hsh, htt=-1;
719  mi_aux_term *res=NULL;
720  FILE *f;
721  pid_t pid;
722  char buf[PATH_MAX];
723
724  /* Verify we have an X terminal. */
725  xterm=mi_get_xterm_exe();
726  if (access(xterm,X_OK))
727    {
728     mi_error=MI_MISSING_XTERM;
729     return NULL;
730    }
731
732  /* Create 2 temporals. */
733  hsh=mkstemp(nsh);
734  if (hsh==-1)
735    {
736     mi_error=MI_CREATE_TEMPORAL;
737     return NULL;
738    }
739  htt=mkstemp(ntt);
740  if (htt==-1)
741    {
742     close(hsh);
743     unlink(nsh);
744     mi_error=MI_CREATE_TEMPORAL;
745     return NULL;
746    }
747  close(htt);
748  /* Create the script. */
749  f=fdopen(hsh,"w");
750  if (!f)
751    {
752     close(hsh);
753     unlink(nsh);
754     unlink(ntt);
755     mi_error=MI_CREATE_TEMPORAL;
756     return NULL;
757    }
758  fprintf(f,"#!/bin/sh\n");
759  fprintf(f,"tty > %s\n",ntt);
760  fprintf(f,"rm %s\n",nsh);
761  fprintf(f,"sleep 365d\n");
762  fclose(f);
763  /* Spawn xterm. */
764  /* Create the child. */
765  pid=fork();
766  if (pid==0)
767    {/* We are the child. */
768     char *argv[5];
769     /* Pass the control to gdb. */
770     argv[0]=(char *)mi_get_xterm_exe(); /* Is that ok? */
771     argv[1]="-e";
772     argv[2]="/bin/sh";
773     argv[3]=nsh;
774     argv[4]=0;
775     execvp(argv[0],argv);
776     /* We get here only if exec failed. */
777     unlink(nsh);
778     unlink(ntt);
779     _exit(127);
780    }
781  /* We are the parent. */
782  if (pid==-1)
783    {/* Fork failed. */
784     unlink(nsh);
785     unlink(ntt);
786     mi_error=MI_FORK;
787     return NULL;
788    }
789  /* Wait until the shell is deleted. */
790  while (stat(nsh,&st)==0)
791    usleep(1000);
792  /* Try to read the tty name. */
793  f=fopen(ntt,"rt");
794  if (f)
795    {
796     if (fgets(buf,PATH_MAX,f))
797       {
798        char *s; /* Strip the \n. */
799        for (s=buf; *s && *s!='\n'; s++);
800        *s=0;
801        res=(mi_aux_term *)malloc(sizeof(mi_aux_term));
802        if (res)
803          {
804           res->pid=pid;
805           res->tty=strdup(buf);
806          }
807       }
808     fclose(f);
809    }
810  unlink(ntt);
811  return res;
812 }
813
814 void mi_free_aux_term(mi_aux_term *t)
815 {
816  if (!t)
817     return;
818  free(t->tty);
819  free(t);
820 }
821
822 /**[txh]********************************************************************
823
824   Description:
825   Closes the auxiliar terminal and releases the allocated memory.
826   
827 ***************************************************************************/
828
829 void gmi_end_aux_term(mi_aux_term *t)
830 {
831  if (!t)
832     return;
833  if (t->pid!=-1 && mi_check_running_pid(t->pid))
834     mi_kill_child(t->pid);
835  mi_free_aux_term(t);
836 }
837
838 /**[txh]********************************************************************
839
840   Description:
841   Forces the MI version. Currently the library can't detect it so you must
842 force it manually. GDB 5.x implemented MI v1 and 6.x v2.
843   
844 ***************************************************************************/
845
846 void mi_force_version(mi_h *h, unsigned vMajor, unsigned vMiddle,
847                       unsigned vMinor)
848 {
849  h->version=MI_VERSION2U(vMajor,vMiddle,vMinor);
850 }
851
852 /**[txh]********************************************************************
853
854   Description:
855   Dis/Enables the @var{wa} workaround for a bug in gdb.
856
857 ***************************************************************************/
858
859 void mi_set_workaround(unsigned wa, int enable)
860 {
861  switch (wa)
862    {
863     case MI_PSYM_SEARCH:
864          disable_psym_search_workaround=enable ? 0 : 1;
865          break;
866    }
867 }
868
869 /**[txh]********************************************************************
870
871   Description:
872   Finds if the @var{wa} workaround for a bug in gdb is enabled.
873   
874   Return: !=0 if enabled.
875   
876 ***************************************************************************/
877
878 int mi_get_workaround(unsigned wa)
879 {
880  switch (wa)
881    {
882     case MI_PSYM_SEARCH:
883          return disable_psym_search_workaround==0;
884    }
885  return 0;
886 }
887