qemu_add_vm_stop_handler(gdb_vm_stopped, s);
     return 0;
 }
+
+int gdbserver_start_port(int port)
+{
+    CharDriverState *chr;
+    char gdbstub_port_name[128];
+
+    snprintf(gdbstub_port_name, sizeof(gdbstub_port_name),
+             "tcp::%d,nowait,nodelay,server", port);
+    chr = qemu_chr_open(gdbstub_port_name);
+    if (!chr) 
+        return -EIO;
+    return gdbserver_start(chr);
+}
+
 #endif
 
 {
     if (!has_port)
         port = DEFAULT_GDBSTUB_PORT;
-    if (gdbserver_start(port) < 0) {
+    if (gdbserver_start_port(port) < 0) {
         qemu_printf("Could not open gdbserver socket on port %d\n", port);
     } else {
         qemu_printf("Waiting gdb connection on port %d\n", port);
 
 int main(int argc, char **argv)
 {
 #ifdef CONFIG_GDBSTUB
-    int use_gdbstub;
-    char gdbstub_port_name[128];
+    int use_gdbstub, gdbstub_port;
 #endif
     int i, cdrom_index;
     int snapshot, linux_boot;
     bios_size = BIOS_SIZE;
 #ifdef CONFIG_GDBSTUB
     use_gdbstub = 0;
-    sprintf(gdbstub_port_name, "%d", DEFAULT_GDBSTUB_PORT);
+    gdbstub_port = DEFAULT_GDBSTUB_PORT;
 #endif
     snapshot = 0;
     nographic = 0;
                 use_gdbstub = 1;
                 break;
             case QEMU_OPTION_p:
-                pstrcpy(gdbstub_port_name, sizeof(gdbstub_port_name), optarg);
+                gdbstub_port = atoi(optarg);
                 break;
 #endif
             case QEMU_OPTION_L:
 
 #ifdef CONFIG_GDBSTUB
     if (use_gdbstub) {
-        CharDriverState *chr;
-        int port;
-
-        port = atoi(gdbstub_port_name);
-        if (port != 0)
-            sprintf(gdbstub_port_name, "tcp::%d,nowait,nodelay,server", port);
-        chr = qemu_chr_open(gdbstub_port_name);
-        if (!chr) {
-            fprintf(stderr, "qemu: could not open gdbstub device '%s'\n",
-                    gdbstub_port_name);
+        /* XXX: use standard host:port notation and modify options
+           accordingly. */
+        if (gdbserver_start_port(gdbstub_port) < 0) {
+            fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
+                    gdbstub_port);
             exit(1);
         }
-        gdbserver_start(chr);
     } else 
 #endif
     if (loadvm)