Use DTrace to diagnose gdb issues

A few days ago, I installed the newest 64-bit gdb program (version 7.7.1) on Solaris 10 (X86_64 platform) to debug programs. After playing with the gdb a day, I found 2 issues about gdb:
(1) The “set follow-fork-mode child” command doesn’t take effect. By default, after the parent process forks the child process, the gdb will track the parent process, so this command can make gdb begin to follow the child process. But this command works OK on Linux.
(2) The gdb can’t parse the 32-bit application core dump file. Per my understanding, the 64-bit gdb should parse both 32-bit and 64-bit core dump files.

I thought these are 2 bugs, so I reported them to the gdb organization :https://sourceware.org/bugzilla/show_bug.cgi?id=17044 and https://sourceware.org/bugzilla/show_bug.cgi?id=17045. But unfortunately, there was no any responses from the gdb organization. Suddenly I hit upon an idea: since I worked on Solaris, why not use DTrace? Yes, DTrace. DTrace is a very cool application which can trace application, and tell you the function flow of the application. So I started working on it at once!

(1) The “set follow-fork-mode child” command doesn’t take effect.
Firstly, I wrote a simple C test program:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    pid_t pid;

    pid = fork();
    if (pid < 0)
    {
        exit(1);
    }
    else if (pid > 0)
    {
        exit(0);
    }
    printf("hello world\n");
    return 0;
}

Then I wrote the DTrace script (debug_gdb.d) to diagnose gdb. Because I hadn’t read gdb source code before and I didn’t know the function flow of the gdb, I would like to know how the functions are called and executed.
The script was like the following, and it recorded every entry and return of the function:

#!/usr/sbin/dtrace -Fs
pid$target:gdb::entry,  
pid$target:gdb::return
{
}

The “-F” option’s effect is “Coalesce trace output by identifying function entry and return. Function entry probe reports are indented and their output is prefixed with ->. Function return probe reports are unindented and their output is prefixed with <- . ” so it can tell us how the gdb was executed.

I began to use gdb to debug the program:

bash-3.2# ./gdb -data-directory ./data-directory /data/nan/a
GNU gdb (GDB) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-pc-solaris2.10".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /data/nan/a...done.

Before executing “set follow-fork-mode child” command, I ran the DTrace script (the 4408 is the gdb process ID):

`./debug_gdb.d -p 4408 > a.txt`

Then I executed the “set follow-fork-mode child” command in gdb:

(gdb) set follow-fork-mode child

Oh, the output of DTrace script was very large, more than 900 lines, but I found the following function entries and returns:

  CPU FUNCTION        
  ......
  5                      -> do_set_command    
  5                        -> do_sfunc        
  5                          -> empty_sfunc   
  5                          <- empty_sfunc   
  5                        <- do_set_command
  ......

From the name of empty_sfunc, it seemed that gdb did nothing, right? I began to search the code in gdb:
a) The empty_sfunc is like this:

static void
empty_sfunc (char *args, int from_tty, struct cmd_list_element *c)
{
}

It really do nothing!

and it is called in add_set_or_show_cmd:

static struct cmd_list_element *
add_set_or_show_cmd (const char *name,
             enum cmd_types type,
             enum command_class class,
             var_types var_type,
             void *var,
             char *doc,
             struct cmd_list_element **list)
{
  struct cmd_list_element *c = add_cmd (name, class, NULL, doc, list);

  gdb_assert (type == set_cmd || type == show_cmd);
  c->type = type;
  c->var_type = var_type;
  c->var = var;
  /* This needs to be something besides NULL so that this isn't
     treated as a help class.  */
  set_cmd_sfunc (c, empty_sfunc);
  return c;
}

and the set_cmd_sfunc is like this:

void
set_cmd_sfunc (struct cmd_list_element *cmd, cmd_sfunc_ftype *sfunc)
{
  if (sfunc == NULL)
    cmd->func = NULL;
  else
    cmd->func = do_sfunc;
  cmd->function.sfunc = sfunc; /* Ok.  */
}

so from above, I knew the cmd‘s function.sfunc is set to empty_sfunc.
b) Then I searched “follow-fork-mode” in source code, it appears in add_setshow_enum_cmd function:

add_setshow_enum_cmd ("follow-fork-mode", class_run,
        follow_fork_mode_kind_names,
        &follow_fork_mode_string, _("\
Set debugger response to a program call of fork or vfork."), _("\
Show debugger response to a program call of fork or vfork."), _("\
A fork or vfork creates a new process.  follow-fork-mode can be:\n\
  parent  - the original process is debugged after a fork\n\
  child   - the new process is debugged after a fork\n\
The unfollowed process will continue to run.\n\
By default, the debugger will follow the parent process."),
            NULL,
            show_follow_fork_mode_string,
            &setlist, &showlist);

The fourth input parameter from bottom is NULL, and it is the set_func of the cmd. The add_setshow_enum_cmd is like this:

void
add_setshow_enum_cmd (const char *name,
              enum command_class class,
              const char *const *enumlist,
              const char **var,
              const char *set_doc,
              const char *show_doc,
              const char *help_doc,
              cmd_sfunc_ftype *set_func,
              show_value_ftype *show_func,
              struct cmd_list_element **set_list,
              struct cmd_list_element **show_list)
{
  struct cmd_list_element *c;

  add_setshow_cmd_full (name, class, var_enum, var,
            set_doc, show_doc, help_doc,
            set_func, show_func,
            set_list, show_list,
            &c, NULL);
  c->enums = enumlist;
}

add_setshow_enum_cmd calls add_setshow_cmd_full, and what does add_setshow_cmd_full do?

static void
add_setshow_cmd_full (const char *name,
              enum command_class class,
              var_types var_type, void *var,
              const char *set_doc, const char *show_doc,
              const char *help_doc,
              cmd_sfunc_ftype *set_func,
              show_value_ftype *show_func,
              struct cmd_list_element **set_list,
              struct cmd_list_element **show_list,
              struct cmd_list_element **set_result,
              struct cmd_list_element **show_result)
{
    ......
    set = add_set_or_show_cmd (name, set_cmd, class, var_type, var,
             full_set_doc, set_list);
    set->flags |= DOC_ALLOCATED;

    if (set_func != NULL)
        set_cmd_sfunc (set, set_func);
    ......
}

Form the above code analysis, I got the following conclusion: by default, the cmd‘s function.sfunc is empty_sfunc, and it would be set only if the set_func is not NULL. Because the default value of “follow-fork-mode” command’s set_func isNULL, this command wouldn’t take effect by default.

Another question, why does it work OK on Linux? After further investigating the code, I found the Linux has a customized function for supporting this command: linux_child_follow_fork.

So the conclusion is: by default, the gdb doesn’t support “set follow-fork-mode child” command, it needs the different platforms implement the function themselves.

(2) The gdb can’t parse the 32-bit application core dump file.
Firstly, I wrote a simple C program which can generate core dump file:

#include <stdio.h>

int main(void) {
        int *p = NULL;
        *p = 0;
        return 0;
}

Then, after generating core dump file, I would use gdb to analyze it. Usually, using gdb to debug core dump file command likes this:

gdb path/to/the/executable path/to/the/coredump

But because our DTrace script need work after gdb has run, I would use another method to start gdb:

bash-3.2# ./gdb -data-directory ./data-directory
GNU gdb (GDB) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-pc-solaris2.10".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
(gdb) file /data/nan/a
Reading symbols from /data/nan/a...done.

Before loading the core dump file, I ran the DTrace script (the 4859 is the gdb process ID):

./debug_gdb.d -p 4859 > a.txt

Then I loaded core dump file in gdb, and gdb outputted:

(gdb) core-file /var/core/core.a.4856.1403588180
warning: Couldn't find general-purpose registers in core file.
[Thread debugging using libthread_db enabled]
[New Thread 1 (LWP 1)]
warning: Couldn't find general-purpose registers in core file.
warning: Couldn't find general-purpose registers in core file.
Error in re-setting breakpoint -21: PC register is not available
Error in re-setting breakpoint -22: PC register is not available
Error in re-setting breakpoint -23: PC register is not available
Error in re-setting breakpoint -24: PC register is not available
Error in re-setting breakpoint -25: PC register is not available
Error in re-setting breakpoint -26: PC register is not available
Error in re-setting breakpoint -27: PC register is not available
Error in re-setting breakpoint -28: PC register is not available
Core was generated by `./a'.
warning: Couldn't find general-purpose registers in core file.
#0  <unavailable> in ?? ()

But this time, the Dtrace ouput file was terribly large (almost 2G), and I couldn’t easily get the root cause like the above issue. But I noticed a function:warning. Yes, the gdb outputted “warning: Couldn’t find general-purpose registers in core file.”, so I hoped this function can help me, then I created a new DTrace script:

#!/usr/sbin/dtrace -Fs
pid$target:gdb:warning:entry,
pid$target:gdb:warning:return
{
        ustack();
}

When the warning was ouputted, the call stack would also be printted.

After executing “core-file /var/core/core.a.4856.1403588180” command again, the DTrace script output was like this:

10  -> warning                               
              gdb`warning
              gdb`get_core_register_section+0x180
              gdb`get_core_registers+0x16b
              gdb`sol_thread_fetch_registers+0x73
              gdb`target_fetch_registers+0x32
              gdb`ps_lgetfpregs+0x99
              libc_db.so.1`td_thr_getfpregs+0x4c
              gdb`sol_thread_fetch_registers+0x10d
              gdb`target_fetch_registers+0x32
              gdb`regcache_raw_read+0x123
              gdb`regcache_cooked_read_unsigned+0x87
              gdb`regcache_read_pc+0x58
              gdb`switch_to_thread+0x1d6
              gdb`switch_to_program_space_and_thread+0x7f
              gdb`breakpoint_re_set_one+0x65
              gdb`catch_errors+0x63
              gdb`breakpoint_re_set+0x76
              gdb`solib_add+0x190
              gdb`post_create_inferior+0xe1
              gdb`core_open+0x2a8

From this output, I could see an error occurred in get_core_register_section, then I read this function code:

static void
get_core_register_section (struct regcache *regcache,
               const char *name,
               int which,
               const char *human_name,
               int required)
{
 ......
  section = bfd_get_section_by_name (core_bfd, section_name);
  if (! section)
    {
      if (required)
    warning (_("Couldn't find %s registers in core file."),
         human_name);
      return;
    }
 ......
}

What does bfd_get_section_by_name do?

asection *
bfd_get_section_by_name (bfd *abfd, const char *name)
{
  struct section_hash_entry *sh;

  sh = section_hash_lookup (&abfd->section_htab, name, FALSE, FALSE);
  if (sh != NULL)
    return &sh->section;

  return NULL;
}

And the section_hash_lookup is like this:

#define section_hash_lookup(table, string, create, copy) \
  ((struct section_hash_entry *) \
   bfd_hash_lookup ((table), (string), (create), (copy)))

So until tracing here, I could see the root cause was bfd_hash_lookup return NULL, then gdb outputted “warning: Couldn’t find general-purpose registers in core file”.

I improved the DTrace script, and it was like this:

#!/usr/sbin/dtrace -Fs
pid$target:gdb:warning:entry
{
        printf("------------------BEGIN-------------------\n");
}
pid$target:gdb:warning:return
{
        printf("------------------END-------------------\n");
}
pid$target:gdb:bfd_hash_lookup:entry
{
        ustack();
        printf("%p, %s, %d, %d\n", arg0, copyinstr(arg1), arg2, arg3);
}
pid$target:gdb:bfd_hash_lookup:return
{
        ustack();
        printf("%p\n", arg1);
}

This script would print the input arguments and return values of the bfd_hash_lookup, so I can see why the warning was outputted.

After executing it, I knew the root cause was some register sections (like .reg) couldn’t be created if don’t exist.

As a man who haven’t read gdb source code, only through very simple DTrace scripts (contain only several lines), I can analyze the root cause of 2 gdb issues. So I suggest every Unix programmer try to learn DTrace, and it can give you big rewards!

Happy DTracing! Happy hacking!

C programming tips in SPARC architecture

If you are a newbie of C programmers in SPARC architecture (For example, working on Solaris), you should pay attention to the following tips:

(1) By default, SPARC is big-endian (For Endianness, you can refer http://en.wikipedia.org/wiki/Endianness). It means for an integer (short, int, long, etc), the MSB will be stored in the lower address, while the LSB will be stored in the higher address.

(2) SPARC requires byte-alignment. It means for a short (2 bytes long) variable, the start address of the variable must be the multiples of 2, while a int (4 bytes long) variable, the start address of the variable must be the multiples of 4. If the address can’t satisfy this condition, the application will core dump, and a “Bus Error” will be reported. For this tip, you can refer Expert C Programming: Deep C Secrets (Bus Error section, page 163 ~ page 164).

For more SPARC information, you can refer:
http://en.wikipedia.org/wiki/SPARC;
SPARC Processor Issues.

An experience of fixing a memory-corruption bug

During the last 4 months, I was disturbed by a memory-corruption bug, and this bug will cause program crash. Until last Monday, I found the root cause and fixed it. This debug process is a difficult but memorable experience, so I will share it in this article.

My program works as a SMS Hub. When it receives a SMS, it will allocate a structure in heap memory like this:

typedef struct
{
......
int *a[8];
......
} info;

After processing the SMS, the program will free the memory, and send the SMS to the next Hub or Operator.

Since last November, the program will crash sometimes, and the cause is the second element in array a (a[1])will be changed from a valid value to NULL.

(1) Checking the logs and reproduced the bug
Firstly, I checked the commercial logs, but there were no clues can be found. And the SMS which killed program also seemed no different than others. I also tried to use this SMS to reproduce the bug in testbed, but also failed.

(2) Using libumem
Because our program runs in Solaris, I linked the libumem and hoped it can help me. After a few days, the program crashed again. But the tags before and after the corrupted memory are all OK, so it is not a memory off-bound bug. I also checked the memory before and after the corrupted memory, but nothing valuable can be found.

(3) Adding more logs
Until then, the only thing I can think is adding more logs. After adding enough logs, I found the variable is modified between functions in the same thread: when leaving the last function, the variable is OK, but entering the next function, the variable is changed. So I can make sure the variable is destroyed by another thread. But how can I find the murderer?

(4) Asking for help from other geeks
I began to ask for help from other geeks. I put this question on the stackoverflow: How to debug the memory is changed randomly issue, and received a very good and comprehensive answer. I recommended every one should read this post. I also sent emails to other geeks, most of them replied and gave some suggestions, such as exchange some variables definition sequences, etc. I also wanted to get the root cause from the core dump file directly: Can I know which thread change the global variable’s value from core dump file?, but at the end, I am failed. Until one day, I found an article (Aha, written in Chinese!)by accident, this article describes the bug is very similar to mine except his programming language is C++ and mine is C. I began to follow the steps he provided to find the root cause.

(5) Porting the program on Linux and use valgrind
I wanted to use valgrind to help find the bug, but my program runs on Solaris, and valgrind can’t be used on Solaris, so another colleague helped to ported it on Linux. After running valgrind, I did find some memory-related bugs, but these bugs can’t explain the cause of this issue. I still can’t find the root cause.

(6) Using electric-fence
I tried to use electric-fence, but the home page of electric-fence was closed. I found some packages and source codes from the internet, and tried to integrated them into my program. But this time, I also failed.

(7) Using mprotect function
Because the second element of the array is always changed to NULL, I used mprotect instead of malloc to allocate the memory of the array, and set read-only attribute of the memory. So if the memory is changed, the program will crash. But the mprotect will allocate a page size of the memory, and this may cause the program change the behavior, I am not sure whether the bug can occur again.

(8) Finding the cause
About 2 weeks later, when a colleague stopped the application, the application crashed again. The cause was a global variable was changed. I checked all the old core dumps immediately, and found the global variable was always changed, and pointed to the address of the array! It seemed I was very clear to the truth.

After about 2 days analysis, the cause was found: When a thread calls pthread_create to create another thread, it will changes a global variable. But in few cases, the child thread will execute firstly, and it will also changes the global variable. The code assumes the parent thread always execute firstly, and this will cause the program crash.

When looking back the 4-month experience, I have studied a lot of things for debugging this bug: libumem, valgrid, libefence, etc. It is a really memorable and cool experience!

Socket programming tips on Solaris

I sponsored a topic in stackoverflow.com, and hoped the programmers can share the socket programming tips on different UNIX flavors. But unfortunately, the responders are few. So I can only share my socket programming tips on Solaris at here (the Chinese version can be found there):

  1. Use the following link options: “-lresolv -lnsl -lsocket”;
  2. Solaris doesn’t provide socket options: SO_SNDTIMEO and SO_RCVTIMEO(Why does Solaris OS define SO_SNDTIMEO and SO_RCVTIMEO socket options in header file which actually not support by kernel?);
  3. In SCTP programming, must call bind() before calling sctp_bindx()(sctp_bindx(Solaris sctp library) always return “Invalid argument”);
  4. When calling shutdown() on a listen socket, it will cause ENOTCONN error(Why shutdown a socket can’t let the select() return?).

GSM MAP Forward SMS Signaling Introduction

When you send a SMS to other people, what happens? The simplified procedure is like this: Firstly, the SMS will arrive at the SMSC (Short Message Service Center), and this is called MO (Mobile Originated) Forward SMS. Then the SMSC will forward the SMS to the recipient user, and this is called MT (Mobile Terminated) Forward SMS.

In GSM MAP v1 and V2, there is one signaling used for both MO and MT Forward SMS services: MAP-FORWARD-SHORT-MESSAGE (forwardSM for short, and the opCode is 46). Since MAP v3, There are separated signalings for for MO and MT Forward SMS service: MAP-MO-FORWARD-SHORT-MESSAGE is for MO (MO-forwardSM for short, and the opCode is still 46) and MAP-MT-FORWARD-SHORT-MESSAGE(MT-forwardSM for short, and the opCode is 44) is for MT.

The famous network analyze tool wireshark is once reported the bug about dissecting Forward SMS signalings, and the bug will cause the wireshark “incorrect interpretation of the MAPv2 MT-ForwardShortMessage as a MAPv3 MO-ForwardShortMessage”. Form the newest wireahark 1.10.5 source code, we can see the wireshark has done the disposition of differentinating MO and MT scenarios:

static int dissect_invokeData(proto_tree *tree, tvbuff_t *tvb, int offset, asn1_ctx_t *actx) {
    ......
  case 44: /*mt-forwardSM(v3) or ForwardSM(v1/v2)*/
    if (application_context_version == 3)
      offset=dissect_gsm_map_sm_MT_ForwardSM_Arg(FALSE, tvb, offset, actx, tree, -1);
    else {
      offset=dissect_gsm_old_ForwardSM_Arg(FALSE, tvb, offset, actx, tree, -1);
    }
    break;
  case 46: /*mo-forwardSM(v3) or ForwardSM(v1/v2)*/
    if (application_context_version == 3)
      offset=dissect_gsm_map_sm_MO_ForwardSM_Arg(FALSE, tvb, offset, actx, tree, -1);
    else {
      offset=dissect_gsm_old_ForwardSM_Arg(FALSE, tvb, offset, actx, tree, -1);
    }
    break;

    ......
}

The primary parameters in Forward SMS signalling:
SM RP DA: In MO service, it is the SMSC address. In MT service, it is the IMSI of recipient user in most cases.
SM RP OA: In MO service, it is sender phone MSISDN. In MT service, it is the SMSC address.
SM RP UI: The short message transfer protocol data unit, and it contains the actual SMS content and other information.
More Messages To Send: This parameter is used since MAP v2, and only in MT service. This indicates whether the SMSC has more messages to send to recipient phone.