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