gendispatch.pl 65.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#!/usr/bin/perl -w
#
# This script parses remote_protocol.x or qemu_protocol.x and produces lots of
# boilerplate code for both ends of the remote connection.
#
# The first non-option argument specifies the prefix to be searched for, and
# output to, the boilerplate code.  The second non-option argument is the
# file you want to operate on.  For instance, to generate the dispatch table
# for both remote_protocol.x and qemu_protocol.x, you would run the
# following:
#
12
# gendispatch.pl -t remote ../src/remote/remote_protocol.x
13
# gendispatch.pl -t qemu ../src/remote/qemu_protocol.x
14 15
#
# By Richard Jones <rjones@redhat.com>
16
# Extended by Matthias Bolte <matthias.bolte@googlemail.com>
17 18 19 20 21 22

use strict;

use Getopt::Std;

# Command line options.
23 24
# -k - client bodies
# -b - server bodies
25 26
our ($opt_p, $opt_t, $opt_a, $opt_r, $opt_d, $opt_b, $opt_k);
getopts ('ptardbk');
27

28 29
my $structprefix = shift or die "missing struct prefix argument";
my $procprefix = shift or die "missing procedure prefix argument";
30 31 32
my $protocol = shift or die "missing protocol argument";
my @autogen;

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

sub fixup_name {
    my $name = shift;

    $name =~ s/Nwfilter/NWFilter/;
    $name =~ s/Xml$/XML/;
    $name =~ s/Uri$/URI/;
    $name =~ s/Uuid$/UUID/;
    $name =~ s/Id$/ID/;
    $name =~ s/Mac$/MAC/;
    $name =~ s/Cpu$/CPU/;
    $name =~ s/Os$/OS/;
    $name =~ s/Nmi$/NMI/;
    $name =~ s/Pm/PM/;

    return $name;
}
50 51 52 53

# Convert name_of_call to NameOfCall.
sub name_to_ProcName {
    my $name = shift;
54 55 56

    my @elems;
    if ($name =~ /_/ || (lc $name) eq "open" || (lc $name) eq "close") {
57 58 59
        @elems = split /_/, $name;
        @elems = map lc, @elems;
        @elems = map ucfirst, @elems;
60
    } else {
61
        @elems = $name;
62 63 64 65 66 67 68 69 70 71
    }
    @elems = map { fixup_name($_) } @elems;
    my $procname = join "", @elems;

    return $procname;
}

sub name_to_TypeName {
    my $name = shift;

72
    my @elems = split /_/, $name;
73
    @elems = map lc, @elems;
74
    @elems = map ucfirst, @elems;
75 76 77
    @elems = map { fixup_name($_) } @elems;
    my $typename = join "", @elems;
    return $typename;
78 79 80 81
}

# Read the input file (usually remote_protocol.x) and form an
# opinion about the name, args and return type of each RPC.
82
my ($name, $ProcName, $id, $flags, %calls, @calls);
83

84
my $collect_args_members = 0;
85
my $collect_ret_members = 0;
86 87
my $last_name;

88 89 90
open PROTOCOL, "<$protocol" or die "cannot open $protocol: $!";

while (<PROTOCOL>) {
91 92 93 94 95 96
    if ($collect_args_members) {
        if (/^};/) {
            $collect_args_members = 0;
        } elsif ($_ =~ m/^\s*(.*\S)\s*$/) {
            push(@{$calls{$name}->{args_members}}, $1);
        }
97 98 99 100 101 102
    } elsif ($collect_ret_members) {
        if (/^};/) {
            $collect_ret_members = 0;
        } elsif ($_ =~ m/^\s*(.*\S)\s*$/) {
            push(@{$calls{$name}->{ret_members}}, $1);
        }
103 104 105 106
    } elsif (/^struct (${structprefix}_(.*)_args)/ ||
             /^struct (${structprefix}(.*)Args)/) {
        my $structname = $1;
        $name = $2;
107
        $ProcName = name_to_ProcName ($name);
108 109 110
        $name = lc $name;
        $name =~ s/_//g;
        die "duplicate definition of $_"
111 112 113 114 115
            if exists $calls{$name};

        $calls{$name} = {
            name => $name,
            ProcName => $ProcName,
116
            args => $structname,
117 118
            args_members => [],
            ret => "void"
119 120
        };

121
        $collect_args_members = 1;
122
        $collect_ret_members = 0;
123
        $last_name = $name;
124 125 126 127 128
    } elsif (/^struct (${structprefix}_(.*)_ret)\s+{(.*)$/ ||
             /^struct (${structprefix}(.*)Ret)\s+{(.*)$/) {
        my $structname = $1;
        $name = $2;
        $flags = $3;
129
        $ProcName = name_to_ProcName ($name);
130 131
        $name = lc $name;
        $name =~ s/_//g;
132 133

        if (exists $calls{$name}) {
134
            $calls{$name}->{ret} = $structname;
135 136 137 138 139
        } else {
            $calls{$name} = {
                name => $name,
                ProcName => $ProcName,
                args => "void",
140
                ret => $structname,
141
                ret_members => []
142 143
            }
        }
144

145 146 147 148 149 150 151 152
        if ($flags ne "" and ($opt_b or $opt_k)) {
            if (!($flags =~ m/^\s*\/\*\s*insert@(\d+)\s*\*\/\s*$/)) {
                die "invalid generator flags for $calls{$name}->{ret}";
            }

            $calls{$name}->{ret_offset} = int($1);
        }

153
        $collect_args_members = 0;
154 155
        $collect_ret_members = 1;
        $last_name = $name;
156 157 158 159
    } elsif (/^struct (${structprefix}_(.*)_msg)/ ||
             /^struct (${structprefix}(.*)Msg)/) {
        my $structname = $1;
        $name = $2;
160
        $ProcName = name_to_ProcName ($name);
161 162
        $name = lc $name;
        $name =~ s/_//g;
163 164 165
        $calls{$name} = {
            name => $name,
            ProcName => $ProcName,
166
            msg => $structname,
167 168 169
        };

        $collect_args_members = 0;
170
        $collect_ret_members = 0;
171 172 173 174 175
    } elsif (/^\s*(${procprefix}_PROC_(.*?))\s*=\s*(\d+)\s*,?(.*)$/) {
        my $constname = $1;
        $name = $2;
        $id = $3;
        $flags = $4;
176
        $ProcName = name_to_ProcName ($name);
177 178
        $name = lc $name;
        $name =~ s/_//g;
179

180 181 182 183 184 185 186 187 188 189 190 191
        if (!exists $calls{$name}) {
            # that the argument and return value cases have not yet added
            # this procedure to the calls hash means that it has no arguments
            # and no return value. add it to the calls hash now because all
            # procedures have to be listed in the calls hash
            $calls{$name} = {
                name => $name,
                ProcName => $ProcName,
                args => "void",
                ret => "void"
            }
        }
192
        $calls{$name}->{constname} = $constname;
193

194
        if ($opt_b or $opt_k) {
195
            if (!($flags =~ m/^\s*\/\*\s*(\S+)\s+(\S+)\s*(\|.*)?\s+(priority:(\S+))?\s*\*\/\s*$/)) {
196
                die "invalid generator flags '$flags' for $constname"
197 198
            }

199 200
            my $genmode = $opt_b ? $1 : $2;
            my $genflags = $3;
201
            my $priority = defined $5 ? $5 : "low";
202

203
            if ($genmode eq "autogen") {
204
                push(@autogen, $ProcName);
205
            } elsif ($genmode eq "skipgen") {
206 207 208 209
                # ignore it
            } else {
                die "invalid generator flags for ${procprefix}_PROC_${name}"
            }
210 211 212 213 214 215 216 217 218 219 220

            if (defined $genflags and $genflags ne "") {
                if ($genflags =~ m/^\|\s*(read|write)stream@(\d+)\s*$/) {
                    $calls{$name}->{streamflag} = $1;
                    $calls{$name}->{streamoffset} = int($2);
                } else {
                    die "invalid generator flags for ${procprefix}_PROC_${name}"
                }
            } else {
                $calls{$name}->{streamflag} = "none";
            }
221 222 223 224 225 226 227 228 229 230

            # for now, we distinguish only two levels of prioroty:
            # low (0) and high (1)
            if ($priority eq "high") {
                $calls{$name}->{priority} = 1;
            } elsif ($priority eq "low") {
                $calls{$name}->{priority} = 0;
            } else {
                die "invalid priority ${priority} for ${procprefix}_PROC_${name}"
            }
231 232
        }

233
        $calls[$id] = $calls{$name};
234 235

        $collect_args_members = 0;
236
        $collect_ret_members = 0;
237 238
    } else {
        $collect_args_members = 0;
239
        $collect_ret_members = 0;
240 241 242
    }
}

243 244
close(PROTOCOL);

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
# this hash contains the procedures that are allowed to map [unsigned] hyper
# to [unsigned] long for legacy reasons in their signature and return type.
# this list is fixed. new procedures and public APIs have to map [unsigned]
# hyper to [unsigned] long long
my $long_legacy = {
    DomainGetInfo               => { ret => { maxMem => 1, memory => 1 } },
    DomainMigrate               => { arg => { flags => 1, resource => 1 } },
    DomainMigrate2              => { arg => { flags => 1, resource => 1 } },
    DomainMigrateBegin3         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateConfirm3       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateDirect         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateFinish         => { arg => { flags => 1 } },
    DomainMigrateFinish2        => { arg => { flags => 1 } },
    DomainMigrateFinish3        => { arg => { flags => 1 } },
    DomainMigratePeer2Peer      => { arg => { flags => 1, resource => 1 } },
    DomainMigratePerform        => { arg => { flags => 1, resource => 1 } },
    DomainMigratePerform3       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare        => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare2       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare3       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepareTunnel  => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepareTunnel3 => { arg => { flags => 1, resource => 1 } },
    DomainMigrateToURI          => { arg => { flags => 1, resource => 1 } },
    DomainMigrateToURI2         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion1       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion2       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion3       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateSetMaxSpeed    => { arg => { bandwidth => 1 } },
    DomainSetMaxMemory          => { arg => { memory => 1 } },
    DomainSetMemory             => { arg => { memory => 1 } },
    DomainSetMemoryFlags        => { arg => { memory => 1 } },
    GetLibVersion               => { ret => { lib_ver => 1 } },
    GetVersion                  => { ret => { hv_ver => 1 } },
    NodeGetInfo                 => { ret => { memory => 1 } },
279
    DomainBlockPull             => { arg => { bandwidth => 1 } },
280
    DomainBlockRebase           => { arg => { bandwidth => 1 } },
281
    DomainBlockJobSetSpeed      => { arg => { bandwidth => 1 } },
282
    DomainMigrateGetMaxSpeed    => { ret => { bandwidth => 1 } },
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
};

sub hyper_to_long
{
    my $proc_name = shift;
    my $ret_or_arg = shift;
    my $member = shift;

    if ($long_legacy->{$proc_name} and
        $long_legacy->{$proc_name}->{$ret_or_arg} and
        $long_legacy->{$proc_name}->{$ret_or_arg}->{$member}) {
        return 1;
    } else {
        return 0
    }
}

300 301 302 303
#----------------------------------------------------------------------
# Output

print <<__EOF__;
304
/* Automatically generated by gendispatch.pl.
305 306 307 308
 * Do not edit this file.  Any changes you make will be lost.
 */
__EOF__

309 310 311 312
if (!$opt_b and !$opt_k) {
    print "\n";
}

313 314 315 316 317 318 319
# Debugging.
if ($opt_d) {
    my @keys = sort (keys %calls);
    foreach (@keys) {
        print "$_:\n";
        print "        name $calls{$_}->{name} ($calls{$_}->{ProcName})\n";
        print "        $calls{$_}->{args} -> $calls{$_}->{ret}\n";
320
        print "        priority -> $calls{$_}->{priority}\n";
321 322 323
    }
}

324
# Bodies for dispatch functions ("remote_dispatch_bodies.h").
325
elsif ($opt_b) {
326
    my %generate = map { $_ => 1 } @autogen;
327 328 329
    my @keys = sort (keys %calls);

    foreach (@keys) {
330 331
        my $call = $calls{$_};

332
        # skip things which are REMOTE_MESSAGE
333
        next if $call->{msg};
334

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        my $name = $structprefix . "Dispatch" . $call->{ProcName};
        my $argtype = $call->{args};
        my $rettype = $call->{ret};

        my $argann = $argtype ne "void" ? "" : " ATTRIBUTE_UNUSED";
        my $retann = $rettype ne "void" ? "" : " ATTRIBUTE_UNUSED";

        # First we print out a function declaration for the
        # real dispatcher body
        print "static int ${name}(\n";
        print "    virNetServerPtr server,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg,\n";
        print "    virNetMessageErrorPtr rerr";
        if ($argtype ne "void") {
            print ",\n    $argtype *args";
        }
        if ($rettype ne "void") {
            print ",\n    $rettype *ret";
        }
        print ");\n";


        # Next we print out a generic wrapper method which has
        # fixed function signature, for use in the dispatcher
        # table. This simply callers the real dispatcher method
        print "static int ${name}Helper(\n";
        print "    virNetServerPtr server,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg,\n";
        print "    virNetMessageErrorPtr rerr,\n";
        print "    void *args$argann,\n";
        print "    void *ret$retann)\n";
        print "{\n";
        print "  VIR_DEBUG(\"server=%p client=%p msg=%p rerr=%p args=%p ret=%p\", server, client, msg, rerr, args, ret);\n";
        print "  return $name(server, client, msg, rerr";
        if ($argtype ne "void") {
            print ", args";
        }
        if ($rettype ne "void") {
            print ", ret";
        }
        print ");\n";
        print "}\n";

        # Finally we print out the dispatcher method body impl
        # (if possible)
382 383 384 385 386
        if (!exists($generate{$call->{ProcName}})) {
            print "/* ${structprefix}Dispatch$call->{ProcName} body has " .
                  "to be implemented manually */\n\n\n\n";
            next;
        }
387 388 389

        my $has_node_device = 0;
        my @vars_list = ();
390
        my @optionals_list = ();
391 392
        my @getters_list = ();
        my @args_list = ();
393
        my @prepare_ret_list = ();
394
        my @ret_list = ();
395
        my @free_list = ();
396
        my @free_list_on_error = ("virNetMessageSaveError(rerr);");
397

398
        # handle arguments to the function
399
        if ($argtype ne "void") {
400
            # node device is special, as it's identified by name
401 402 403
            if ($argtype =~ m/^remote_node_device_/ and
                !($argtype =~ m/^remote_node_device_lookup_by_name_/) and
                !($argtype =~ m/^remote_node_device_create_xml_/)) {
404 405 406
                $has_node_device = 1;
                push(@vars_list, "virNodeDevicePtr dev = NULL");
                push(@getters_list,
407
                     "    if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))\n" .
408 409 410 411 412 413 414
                     "        goto cleanup;\n");
                push(@args_list, "dev");
                push(@free_list,
                     "    if (dev)\n" .
                     "        virNodeDeviceFree(dev);");
            }

415
            foreach my $args_member (@{$call->{args_members}}) {
416 417 418
                if ($args_member =~ m/^remote_nonnull_string name;/ and $has_node_device) {
                    # ignore the name arg for node devices
                    next
419
                } elsif ($args_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|secret|nwfilter) (\S+);/) {
420
                    my $type_name = name_to_TypeName($1);
421 422

                    push(@vars_list, "vir${type_name}Ptr $2 = NULL");
423
                    push(@getters_list,
424
                         "    if (!($2 = get_nonnull_$1(priv->conn, args->$2)))\n" .
425
                         "        goto cleanup;\n");
426
                    push(@args_list, "$2");
427
                    push(@free_list,
428 429
                         "    if ($2)\n" .
                         "        vir${type_name}Free($2);");
430 431 432 433
                } elsif ($args_member =~ m/^remote_nonnull_domain_snapshot /) {
                    push(@vars_list, "virDomainPtr dom = NULL");
                    push(@vars_list, "virDomainSnapshotPtr snapshot = NULL");
                    push(@getters_list,
434
                         "    if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))\n" .
435 436 437 438 439 440 441 442 443 444
                         "        goto cleanup;\n" .
                         "\n" .
                         "    if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))\n" .
                         "        goto cleanup;\n");
                    push(@args_list, "snapshot");
                    push(@free_list,
                         "    if (snapshot)\n" .
                         "        virDomainSnapshotFree(snapshot);\n" .
                         "    if (dom)\n" .
                         "        virDomainFree(dom);");
445
                } elsif ($args_member =~ m/^(?:remote_string|remote_uuid) (\S+)<\S+>;/) {
446
                    if (! @args_list) {
447
                        push(@args_list, "priv->conn");
448 449
                    }

450 451 452 453
                    push(@args_list, "args->$1.$1_val");
                    push(@args_list, "args->$1.$1_len");
                } elsif ($args_member =~ m/^(?:opaque|remote_nonnull_string) (\S+)<\S+>;(.*)$/) {
                    if (! @args_list) {
454
                        push(@args_list, "priv->conn");
455 456
                    }

457 458 459 460 461 462 463 464 465 466 467 468 469 470
                    my $cast = "";
                    my $arg_name = $1;
                    my $annotation = $2;

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*(.*)\s*\*\//) {
                            $cast = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "${cast}args->$arg_name.${arg_name}_val");
                    push(@args_list, "args->$arg_name.${arg_name}_len");
471 472
                } elsif ($args_member =~ m/^(?:unsigned )?int (\S+)<\S+>;/) {
                    if (! @args_list) {
473
                        push(@args_list, "priv->conn");
474 475 476 477
                    }

                    push(@args_list, "args->$1.$1_val");
                    push(@args_list, "args->$1.$1_len");
478 479 480 481 482 483 484 485 486 487
                } elsif ($args_member =~ m/^remote_typed_param (\S+)<(\S+)>;/) {
                    push(@vars_list, "virTypedParameterPtr $1 = NULL");
                    push(@vars_list, "int n$1");
                    push(@args_list, "$1");
                    push(@args_list, "n$1");
                    push(@getters_list, "    if (($1 = remoteDeserializeTypedParameters(args->$1.$1_val,\n" .
                                        "                                                   args->$1.$1_len,\n" .
                                        "                                                   $2,\n" .
                                        "                                                   &n$1)) == NULL)\n" .
                                        "        goto cleanup;\n");
488 489
                    push(@free_list, "    virTypedParameterArrayClear($1, n$1);");
                    push(@free_list, "    VIR_FREE($1);");
490 491 492 493
                } elsif ($args_member =~ m/<\S+>;/ or $args_member =~ m/\[\S+\];/) {
                    # just make all other array types fail
                    die "unhandled type for argument value: $args_member";
                } elsif ($args_member =~ m/^remote_uuid (\S+);/) {
494
                    if (! @args_list) {
495
                        push(@args_list, "priv->conn");
496 497
                    }

498 499 500
                    push(@args_list, "(unsigned char *) args->$1");
                } elsif ($args_member =~ m/^remote_string (\S+);/) {
                    if (! @args_list) {
501
                        push(@args_list, "priv->conn");
502
                    }
503 504 505 506 507 508

                    push(@vars_list, "char *$1");
                    push(@optionals_list, "$1");
                    push(@args_list, "$1");
                } elsif ($args_member =~ m/^remote_nonnull_string (\S+);/) {
                    if (! @args_list) {
509
                        push(@args_list, "priv->conn");
510 511 512
                    }

                    push(@args_list, "args->$1");
513
                } elsif ($args_member =~ m/^(unsigned )?int (\S+);/) {
514
                    if (! @args_list) {
515
                        push(@args_list, "priv->conn");
516 517
                    }

518 519 520
                    push(@args_list, "args->$2");
                } elsif ($args_member =~ m/^(unsigned )?hyper (\S+);/) {
                    if (! @args_list) {
521
                        push(@args_list, "priv->conn");
522 523 524 525 526 527 528 529 530 531 532 533 534 535
                    }

                    my $arg_name = $2;

                    if (hyper_to_long($call->{ProcName}, "arg", $arg_name)) {
                        my $type_name = $1; $type_name .= "long";
                        my $sign = ""; $sign = "U" if ($1);

                        push(@vars_list, "$type_name $arg_name");
                        push(@getters_list, "    HYPER_TO_${sign}LONG($arg_name, args->$arg_name);\n");
                        push(@args_list, "$arg_name");
                    } else {
                        push(@args_list, "args->$arg_name");
                    }
536
                } elsif ($args_member =~ m/^(\/)?\*/) {
537 538 539
                    # ignore comments
                } else {
                    die "unhandled type for argument value: $args_member";
540 541 542 543
                }
            }
        }

544
        # handle return values of the function
545 546 547
        my $single_ret_var = "undefined";
        my $single_ret_by_ref = 0;
        my $single_ret_check = " == undefined";
548 549 550 551
        my $single_ret_as_list = 0;
        my $single_ret_list_name = "undefined";
        my $single_ret_list_max_var = "undefined";
        my $single_ret_list_max_define = "undefined";
552 553
        my $multi_ret = 0;

554
        if ($rettype ne "void" and
555
            scalar(@{$call->{ret_members}}) > 1) {
556 557
            $multi_ret = 1;
        }
558

559
        if ($rettype ne "void") {
560
            foreach my $ret_member (@{$call->{ret_members}}) {
561
                if ($multi_ret) {
562
                    if ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+)\[\S+\];/) {
563 564 565 566
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            die "legacy [u]long hyper arrays aren't supported";
                        }

567
                        push(@ret_list, "memcpy(ret->$3, tmp.$3, sizeof(ret->$3));");
568 569
                    } elsif ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+);/) {
                        push(@ret_list, "ret->$3 = tmp.$3;");
570 571 572
                    } else {
                        die "unhandled type for multi-return-value: $ret_member";
                    }
573
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
574
                    push(@vars_list, "int len");
575
                    splice(@args_list, int($3), 0, ("ret->$1.$1_val"));
576
                    push(@ret_list, "ret->$1.$1_len = len;");
577
                    push(@free_list_on_error, "VIR_FREE(ret->$1.$1_val);");
578 579 580 581 582 583 584
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_check = " < 0";
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
                    $single_ret_list_max_var = "max$1";
                    $single_ret_list_max_define = $2;
585 586 587
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "remote_nonnull_string array without insert@<offset> annotation: $ret_member";
588
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+);/) {
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
                    if ($call->{ProcName} eq "GetType") {
                        # SPECIAL: virConnectGetType returns a constant string that must
                        #          not be freed. Therefore, duplicate the string here.
                        push(@vars_list, "const char *$1");
                        push(@ret_list, "/* We have to strdup because remoteDispatchClientRequest will");
                        push(@ret_list, " * free this string after it's been serialised. */");
                        push(@ret_list, "if (!(ret->type = strdup(type))) {");
                        push(@ret_list, "    virReportOOMError();");
                        push(@ret_list, "    goto cleanup;");
                        push(@ret_list, "}");
                    } else {
                        push(@vars_list, "char *$1");
                        push(@ret_list, "ret->$1 = $1;");
                    }

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
                    $single_ret_var = $1;
                    $single_ret_by_ref = 0;
                    $single_ret_check = " == NULL";
                } elsif ($ret_member =~ m/^remote_string (\S+);/) {
                    push(@vars_list, "char *$1 = NULL");
                    push(@vars_list, "char **$1_p = NULL");
                    push(@ret_list, "ret->$1 = $1_p;");
                    push(@free_list, "    VIR_FREE($1);");
                    push(@free_list_on_error, "VIR_FREE($1_p);");
                    push(@prepare_ret_list,
                         "if (VIR_ALLOC($1_p) < 0) {\n" .
                         "        virReportOOMError();\n" .
                         "        goto cleanup;\n" .
                         "    }\n" .
                         "    \n" .
                         "    *$1_p = strdup($1);\n" .
                         "    if (*$1_p == NULL) {\n" .
                         "        virReportOOMError();\n" .
                         "        goto cleanup;\n" .
                         "    }\n");

625 626 627
                    $single_ret_var = $1;
                    $single_ret_by_ref = 0;
                    $single_ret_check = " == NULL";
628
                } elsif ($ret_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|node_device|secret|nwfilter|domain_snapshot) (\S+);/) {
629
                    my $type_name = name_to_TypeName($1);
630

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
                    if ($call->{ProcName} eq "DomainCreateWithFlags") {
                        # SPECIAL: virDomainCreateWithFlags updates the given
                        #          domain object instead of returning a new one
                        push(@ret_list, "make_nonnull_$1(&ret->$2, $2);");
                        $single_ret_var = undef;
                        $single_ret_by_ref = 1;
                    } else {
                        push(@vars_list, "vir${type_name}Ptr $2 = NULL");
                        push(@ret_list, "make_nonnull_$1(&ret->$2, $2);");
                        push(@free_list,
                             "    if ($2)\n" .
                             "        vir${type_name}Free($2);");
                        $single_ret_var = $2;
                        $single_ret_by_ref = 0;
                        $single_ret_check = " == NULL";
                    }
647
                } elsif ($ret_member =~ m/^int (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
648
                    push(@vars_list, "int len");
649
                    splice(@args_list, int($3), 0, ("ret->$1.$1_val"));
650
                    push(@ret_list, "ret->$1.$1_len = len;");
651
                    push(@free_list_on_error, "VIR_FREE(ret->$1.$1_val);");
652 653 654 655 656 657 658
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_check = " < 0";
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
                    $single_ret_list_max_var = "max$1";
                    $single_ret_list_max_define = $2;
659 660 661
                } elsif ($ret_member =~ m/^int (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "int array without insert@<offset> annotation: $ret_member";
662
                } elsif ($ret_member =~ m/^int (\S+);/) {
663 664 665 666
                    push(@vars_list, "int $1");
                    push(@ret_list, "ret->$1 = $1;");
                    $single_ret_var = $1;

667
                    if ($call->{ProcName} =~ m/GetAutostart$/) {
668 669 670
                        $single_ret_by_ref = 1;
                    } else {
                        $single_ret_by_ref = 0;
671

672
                        if ($call->{ProcName} eq "CPUCompare") {
673 674 675 676
                            $single_ret_check = " == VIR_CPU_COMPARE_ERROR";
                        } else {
                            $single_ret_check = " < 0";
                        }
677
                    }
678
                } elsif ($ret_member =~ m/^(?:unsigned )?hyper (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
679 680 681 682
                    if (hyper_to_long($call->{ProcName}, "ret", $1)) {
                        die "legacy [u]long hyper arrays aren't supported";
                    }

683 684
                    push(@vars_list, "int len");
                    push(@ret_list, "ret->$1.$1_len = len;");
685
                    push(@free_list_on_error, "VIR_FREE(ret->$1.$1_val);");
686 687 688 689
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
690
                    $single_ret_list_max_var = "max$1";
691 692
                    $single_ret_list_max_define = $2;

693
                    if ($call->{ProcName} eq "NodeGetCellsFreeMemory") {
694
                        $single_ret_check = " <= 0";
695
                        splice(@args_list, int($3), 0, ("(unsigned long long *)ret->$1.$1_val"));
696 697
                    } else {
                        $single_ret_check = " < 0";
698
                        splice(@args_list, int($3), 0, ("ret->$1.$1_val"));
699
                    }
700
                } elsif ($ret_member =~ m/^(?:unsigned )?hyper (\S+)<\S+>;/) {
701 702
                    # error out on unannotated arrays
                    die "hyper array without insert@<offset> annotation: $ret_member";
703
                } elsif ($ret_member =~ m/^(unsigned )?hyper (\S+);(?:\s*\/\*\s*insert@(\d+)\s*\*\/)?/) {
704
                    my $type_name = $1;
705
                    my $ret_name = $2;
706
                    my $ret_assign;
707
                    my $insert = $3;
708

709 710 711 712 713 714 715 716 717
                    if (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        my $sign = ""; $sign = "U" if ($1);

                        $type_name .= "long";
                        $ret_assign = "HYPER_TO_${sign}LONG(ret->$ret_name, $ret_name);";
                    } else {
                        $type_name .= "long long";
                        $ret_assign = "ret->$ret_name = $ret_name;";
                    }
718 719

                    push(@vars_list, "$type_name $ret_name");
720
                    push(@ret_list, $ret_assign);
721 722 723 724 725 726 727

                    if ($insert) {
                        splice(@args_list, int($insert), 0, "&$ret_name");
                        $single_ret_var = undef;
                    } else {
                        $single_ret_var = $ret_name;
                    }
728

729 730
                    if ($call->{ProcName} eq "DomainGetMaxMemory" or
                        $call->{ProcName} eq "NodeGetFreeMemory") {
731 732 733
                        # SPECIAL: virDomainGetMaxMemory and virNodeGetFreeMemory
                        #          return the actual value directly and 0 indicates
                        #          an error
734 735 736 737 738
                        $single_ret_by_ref = 0;
                        $single_ret_check = " == 0";
                    } else {
                        $single_ret_by_ref = 1;
                    }
739 740 741 742 743 744 745 746 747 748 749 750
                } elsif ($ret_member =~ m/^opaque (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    push(@vars_list, "char *$1 = NULL");
                    push(@vars_list, "int $1_len = 0");
                    splice(@args_list, int($3), 0, ("&$1", "&$1_len"));
                    push(@ret_list, "ret->$1.$1_val = $1;");
                    push(@ret_list, "ret->$1.$1_len = $1_len;");
                    push(@free_list_on_error, "VIR_FREE($1);");
                    $single_ret_var = undef;
                    $single_ret_by_ref = 1;
                } elsif ($ret_member =~ m/^opaque (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "opaque array without insert@<offset> annotation: $ret_member";
751 752
                } elsif ($ret_member =~ m/^(\/)?\*/) {
                    # ignore comments
753 754
                } else {
                    die "unhandled type for return value: $ret_member";
755 756 757 758
                }
            }
        }

759
        # select struct type for multi-return-value functions
760
        if ($multi_ret) {
761 762 763 764
            if (!(defined $call->{ret_offset})) {
                die "multi-return-value without insert@<offset> annotation: $call->{ret}";
            }

765 766
            if (! @args_list) {
                push(@args_list, "priv->conn");
767 768
            }

769
            my $struct_name = $call->{ProcName};
770 771
            $struct_name =~ s/Get//;

772 773 774 775
            splice(@args_list, $call->{ret_offset}, 0, ("&tmp"));

            if ($call->{ProcName} eq "DomainBlockStats" ||
                $call->{ProcName} eq "DomainInterfaceStats") {
776 777 778
                # SPECIAL: virDomainBlockStats and virDomainInterfaceStats
                #          have a 'Struct' suffix on the actual struct name
                #          and take the struct size as additional argument
779
                $struct_name .= "Struct";
780
                splice(@args_list, $call->{ret_offset} + 1, 0, ("sizeof(tmp)"));
781 782 783 784 785
            }

            push(@vars_list, "vir$struct_name tmp");
        }

786
        if ($call->{streamflag} ne "none") {
787
            splice(@args_list, $call->{streamoffset}, 0, ("st"));
788
            push(@free_list_on_error, "if (stream) {");
789 790 791 792
            push(@free_list_on_error, "    virStreamAbort(st);");
            push(@free_list_on_error, "    daemonFreeClientStream(client, stream);");
            push(@free_list_on_error, "} else {");
            push(@free_list_on_error, "    virStreamFree(st);");
793 794 795
            push(@free_list_on_error, "}");
        }

796
        # print functions signature
797 798 799 800 801
        print "static int $name(\n";
        print "    virNetServerPtr server ATTRIBUTE_UNUSED,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg ATTRIBUTE_UNUSED,\n";
        print "    virNetMessageErrorPtr rerr";
802
        if ($argtype ne "void") {
803 804
            print ",\n    $argtype *args";
        }
805
        if ($rettype ne "void") {
806 807 808
            print ",\n    $rettype *ret";
        }
        print ")\n";
809 810 811 812 813

        # print function body
        print "{\n";
        print "    int rv = -1;\n";

814 815 816
        foreach my $var (@vars_list) {
            print "    $var;\n";
        }
817
        print "    struct daemonClientPrivate *priv =\n";
818
        print "        virNetServerClientGetPrivateData(client);\n";
819

820
        if ($call->{streamflag} ne "none") {
821 822
            print "    virStreamPtr st = NULL;\n";
            print "    daemonClientStreamPtr stream = NULL;\n";
823 824
        }

825
        print "\n";
826
        print "    if (!priv->conn) {\n";
827
        print "        virReportError(VIR_ERR_INTERNAL_ERROR, \"%s\", _(\"connection not open\"));\n";
828 829 830 831
        print "        goto cleanup;\n";
        print "    }\n";
        print "\n";

832 833
        if ($single_ret_as_list) {
            print "    if (args->$single_ret_list_max_var > $single_ret_list_max_define) {\n";
834 835
            print "        virReportError(VIR_ERR_INTERNAL_ERROR,\n";
            print "                       \"%s\", _(\"max$single_ret_list_name > $single_ret_list_max_define\"));\n";
836 837 838 839 840
            print "        goto cleanup;\n";
            print "    }\n";
            print "\n";
        }

841 842
        print join("\n", @getters_list);

843 844 845
        if (@getters_list) {
            print "\n";
        }
846

847 848 849 850 851 852 853 854
        foreach my $optional (@optionals_list) {
            print "    $optional = args->$optional ? *args->$optional : NULL;\n";
        }

        if (@optionals_list) {
            print "\n";
        }

855
        if ($call->{streamflag} ne "none") {
856 857 858
            print "    if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))\n";
            print "        goto cleanup;\n";
            print "\n";
859
            print "    if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))\n";
860 861 862 863
            print "        goto cleanup;\n";
            print "\n";
        }

864
        if ($rettype eq "void") {
865
            print "    if (vir$call->{ProcName}(";
866 867 868 869
            print join(', ', @args_list);
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
870
        } elsif (!$multi_ret) {
871
            my $prefix = "";
872
            my $proc_name = $call->{ProcName};
873 874

            if (! @args_list) {
875
                push(@args_list, "priv->conn");
876

877
                if ($call->{ProcName} ne "NodeGetFreeMemory") {
878 879
                    $prefix = "Connect"
                }
880 881
            }

882 883 884 885 886 887
            if ($call->{ProcName} eq "GetSysinfo" or
                $call->{ProcName} eq "GetMaxVcpus" or
                $call->{ProcName} eq "DomainXMLFromNative" or
                $call->{ProcName} eq "DomainXMLToNative" or
                $call->{ProcName} eq "FindStoragePoolSources" or
                $call->{ProcName} =~ m/^List/) {
888
                $prefix = "Connect"
889
            } elsif ($call->{ProcName} eq "SupportsFeature") {
890
                $prefix = "Drv"
891
            } elsif ($call->{ProcName} eq "CPUBaseline") {
892
                $proc_name = "ConnectBaselineCPU"
893
            } elsif ($call->{ProcName} eq "CPUCompare") {
894
                $proc_name = "ConnectCompareCPU"
895 896
            } elsif ($structprefix eq "qemu" && $call->{ProcName} =~ /^Domain/) {
                $proc_name =~ s/^(Domain)/${1}Qemu/;
897 898
            }

899 900 901 902 903 904 905 906 907 908
            if ($single_ret_as_list) {
                print "    /* Allocate return buffer. */\n";
                print "    if (VIR_ALLOC_N(ret->$single_ret_list_name.${single_ret_list_name}_val," .
                      " args->$single_ret_list_max_var) < 0) {\n";
                print "        virReportOOMError();\n";
                print "        goto cleanup;\n";
                print "    }\n";
                print "\n";
            }

909 910 911
            if ($single_ret_by_ref) {
                print "    if (vir$prefix$proc_name(";
                print join(', ', @args_list);
912 913 914 915 916 917

                if (defined $single_ret_var) {
                    print ", &$single_ret_var";
                }

                print ") < 0)\n";
918 919 920 921 922 923 924 925
            } else {
                print "    if (($single_ret_var = vir$prefix$proc_name(";
                print join(', ', @args_list);
                print "))$single_ret_check)\n";
            }

            print "        goto cleanup;\n";
            print "\n";
926
        } else {
927
            print "    if (vir$call->{ProcName}(";
928 929 930 931
            print join(', ', @args_list);
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
932
        }
933

934
        if ($call->{streamflag} ne "none") {
935
            print "    if (daemonAddClientStream(client, stream, ";
936 937

            if ($call->{streamflag} eq "write") {
938
                print "false";
939
            } else {
940
                print "true";
941 942
            }

943 944 945 946 947
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
        }

948 949 950 951 952 953
        if (@prepare_ret_list) {
            print "    ";
            print join("\n    ", @prepare_ret_list);
            print "\n";
        }

954 955
        if (@ret_list) {
            print "    ";
956
            print join("\n    ", @ret_list);
957
            print "\n";
958 959 960 961 962
        }

        print "    rv = 0;\n";
        print "\n";
        print "cleanup:\n";
963 964 965 966 967 968 969 970 971 972 973 974 975
        print "    if (rv < 0)";

        if (scalar(@free_list_on_error) > 1) {
            print " {";
        }

        print "\n        ";
        print join("\n        ", @free_list_on_error);
        print "\n";

        if (scalar(@free_list_on_error) > 1) {
            print "    }\n";
        }
976 977 978

        print join("\n", @free_list);

979 980 981 982
        if (@free_list) {
            print "\n";
        }

983
        print "    return rv;\n";
984
        print "}\n\n\n\n";
985
    }
986 987 988 989 990 991 992 993 994 995 996


    # Finally we write out the huge dispatch table which lists
    # the dispatch helper method. the XDR proc for processing
    # args and return values, and the size of the args and
    # return value structs. All methods are marked as requiring
    # authentication. Methods are selectively relaxed in the
    # daemon code which registers the program.

    print "virNetServerProgramProc ${structprefix}Procs[] = {\n";
    for ($id = 0 ; $id <= $#calls ; $id++) {
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        my ($comment, $name, $argtype, $arglen, $argfilter, $retlen, $retfilter, $priority);

        if (defined $calls[$id] && !$calls[$id]->{msg}) {
            $comment = "/* Method $calls[$id]->{ProcName} => $id */";
            $name = $structprefix . "Dispatch" . $calls[$id]->{ProcName} . "Helper";
            my $argtype = $calls[$id]->{args};
            my $rettype = $calls[$id]->{ret};
            $arglen = $argtype ne "void" ? "sizeof($argtype)" : "0";
            $retlen = $rettype ne "void" ? "sizeof($rettype)" : "0";
            $argfilter = $argtype ne "void" ? "xdr_$argtype" : "xdr_void";
            $retfilter = $rettype ne "void" ? "xdr_$rettype" : "xdr_void";
        } else {
            if ($calls[$id]->{msg}) {
                $comment = "/* Async event $calls[$id]->{ProcName} => $id */";
            } else {
                $comment = "/* Unused $id */";
            }
            $name = "NULL";
            $arglen = $retlen = 0;
            $argfilter = "xdr_void";
            $retfilter = "xdr_void";
        }
1019

1020 1021
    $priority = defined $calls[$id]->{priority} ? $calls[$id]->{priority} : 0;

1022
        print "{ $comment\n   ${name},\n   $arglen,\n   (xdrproc_t)$argfilter,\n   $retlen,\n   (xdrproc_t)$retfilter,\n   true,\n   $priority\n},\n";
1023 1024 1025
    }
    print "};\n";
    print "size_t ${structprefix}NProcs = ARRAY_CARDINALITY(${structprefix}Procs);\n";
1026
}
1027

1028
# Bodies for client functions ("remote_client_bodies.h").
1029
elsif ($opt_k) {
1030
    my %generate = map { $_ => 1 } @autogen;
1031 1032 1033 1034 1035 1036 1037 1038
    my @keys = sort (keys %calls);

    foreach (@keys) {
        my $call = $calls{$_};

        # skip things which are REMOTE_MESSAGE
        next if $call->{msg};

1039 1040
        # skip procedures not on generate list
        next if ! exists($generate{$call->{ProcName}});
1041

1042 1043
        my $argtype = $call->{args};
        my $rettype = $call->{ret};
1044

1045
        # handle arguments to the function
1046 1047
        my @args_list = ();
        my @vars_list = ();
1048
        my @args_check_list = ();
1049
        my @setters_list = ();
1050
        my @setters_list2 = ();
1051
        my @free_list = ();
1052 1053
        my $priv_src = "conn";
        my $priv_name = "privateData";
1054
        my $call_args = "&args";
1055

1056
        if ($argtype eq "void") {
1057
            $call_args = "NULL";
1058
        } else {
1059
            push(@vars_list, "$argtype args");
1060 1061 1062 1063 1064

            my $is_first_arg = 1;
            my $has_node_device = 0;

            # node device is special
1065 1066 1067
            if ($argtype =~ m/^remote_node_/ and
                !($argtype =~ m/^remote_node_device_lookup_by_name_/) and
                !($argtype =~ m/^remote_node_device_create_xml_/)) {
1068
                $has_node_device = 1;
1069
                $priv_name = "devMonPrivateData";
1070 1071 1072 1073 1074 1075 1076 1077 1078
            }

            foreach my $args_member (@{$call->{args_members}}) {
                if ($args_member =~ m/^remote_nonnull_string name;/ and $has_node_device) {
                    $priv_src = "dev->conn";
                    push(@args_list, "virNodeDevicePtr dev");
                    push(@setters_list, "args.name = dev->name;");
                } elsif ($args_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|secret|nwfilter|domain_snapshot) (\S+);/) {
                    my $name = $1;
1079
                    my $arg_name = $2;
1080
                    my $type_name = name_to_TypeName($name);
1081 1082 1083

                    if ($is_first_arg) {
                        if ($name eq "domain_snapshot") {
1084
                            $priv_src = "$arg_name->domain->conn";
1085
                        } else {
1086
                            $priv_src = "$arg_name->conn";
1087 1088 1089 1090 1091 1092 1093 1094 1095
                        }

                        if ($name =~ m/^storage_/) {
                            $priv_name = "storagePrivateData";
                        } elsif (!($name =~ m/^domain/)) {
                            $priv_name = "${name}PrivateData";
                        }
                    }

1096 1097 1098 1099 1100
                    push(@args_list, "vir${type_name}Ptr $arg_name");
                    push(@setters_list, "make_nonnull_$1(&args.$arg_name, $arg_name);");
                } elsif ($args_member =~ m/^remote_uuid (\S+);/) {
                    push(@args_list, "const unsigned char *$1");
                    push(@setters_list, "memcpy(args.$1, $1, VIR_UUID_BUFLEN);");
1101 1102 1103
                } elsif ($args_member =~ m/^remote_string (\S+);/) {
                    push(@args_list, "const char *$1");
                    push(@setters_list, "args.$1 = $1 ? (char **)&$1 : NULL;");
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
                } elsif ($args_member =~ m/^remote_nonnull_string (\S+)<(\S+)>;(.*)$/) {
                    my $type_name = "const char **";
                    my $arg_name = $1;
                    my $limit = $2;
                    my $annotation = $3;

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*\((.*)\)\s*\*\//) {
                            $type_name = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "$type_name$arg_name");
                    push(@args_list, "unsigned int ${arg_name}len");
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char **)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $2 });
1123 1124 1125
                } elsif ($args_member =~ m/^remote_nonnull_string (\S+);/) {
                    push(@args_list, "const char *$1");
                    push(@setters_list, "args.$1 = (char *)$1;");
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
                } elsif ($args_member =~ m/^opaque (\S+)<(\S+)>;(.*)$/) {
                    my $type_name = "const char *";
                    my $arg_name = $1;
                    my $limit = $2;
                    my $annotation = $3;

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*\((.*)\)\s*\*\//) {
                            $type_name = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "$type_name$arg_name");
1141

1142
                    if ($call->{ProcName} eq "SecretSetValue") {
1143
                        # SPECIAL: virSecretSetValue uses size_t instead of int
1144
                        push(@args_list, "size_t ${arg_name}len");
1145
                    } else {
1146
                        push(@args_list, "int ${arg_name}len");
1147 1148
                    }

1149 1150 1151 1152 1153 1154 1155 1156 1157
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char *)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
                } elsif ($args_member =~ m/^remote_string (\S+)<(\S+)>;/) {
                    my $arg_name = $1;
                    my $limit = $2;

                    push(@args_list, "const char *$arg_name");
                    push(@args_list, "int ${arg_name}len");
1158 1159 1160
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char *)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
1161 1162 1163 1164 1165 1166
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+)<(\S+)>;/) {
                    my $type_name = $1;
                    my $arg_name = $2;
                    my $limit = $3;

                    push(@args_list, "${type_name} *$arg_name");
1167
                    push(@args_list, "int ${arg_name}len");
1168 1169 1170
                    push(@setters_list, "args.$arg_name.${arg_name}_val = $arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
1171 1172 1173 1174 1175 1176 1177
                } elsif ($args_member =~ m/^remote_typed_param (\S+)<(\S+)>;/) {
                    push(@args_list, "virTypedParameterPtr $1");
                    push(@args_list, "int n$1");
                    push(@setters_list2, "if (remoteSerializeTypedParameters($1, n$1, &args.$1.$1_val, &args.$1.$1_len) < 0) {\n" .
                                         "        xdr_free((xdrproc_t)xdr_$call->{args}, (char *)&args);\n" .
                                         "        goto done;\n" .
                                         "    }");
1178
                    push(@free_list, "    remoteFreeTypedParameters(args.params.params_val, args.params.params_len);\n");
1179 1180
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+);\s*\/\*\s*call-by-reference\s*\*\//) {
                    my $type_name = "$1 *";
1181 1182 1183 1184
                    my $arg_name = $2;

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = *$arg_name;");
1185 1186
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+);/) {
                    my $type_name = $1;
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                    my $arg_name = $2;

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = $arg_name;");
                } elsif ($args_member =~ m/^(unsigned )?hyper (\S+);/) {
                    my $type_name = $1;
                    my $arg_name = $2;

                    if (hyper_to_long($call->{ProcName}, "arg", $arg_name)) {
                        $type_name .= "long";
                    } else {
                        $type_name .= "long long";
1199 1200 1201 1202
                    }

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = $arg_name;");
1203
                } elsif ($args_member =~ m/^(\/)?\*/) {
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
                    # ignore comments
                } else {
                    die "unhandled type for argument value: $args_member";
                }

                if ($is_first_arg and $priv_src eq "conn") {
                    unshift(@args_list, "virConnectPtr conn");
                }

                $is_first_arg = 0;
            }
        }

1217 1218 1219 1220
        if (! @args_list) {
            push(@args_list, "virConnectPtr conn");
        }

1221 1222
        # fix priv_name for the NumOf* functions
        if ($priv_name eq "privateData" and
1223 1224 1225
            !($call->{ProcName} =~ m/(Domains|DomainSnapshot)/) and
            ($call->{ProcName} =~ m/NumOf(Defined|Domain)*(\S+)s/ or
             $call->{ProcName} =~ m/List(Defined|Domain)*(\S+)s/)) {
1226 1227 1228 1229 1230
            my $prefix = lc $2;
            $prefix =~ s/(pool|vol)$//;
            $priv_name = "${prefix}PrivateData";
        }

1231 1232
        # handle return values of the function
        my @ret_list = ();
1233
        my @ret_list2 = ();
1234 1235 1236
        my $call_ret = "&ret";
        my $single_ret_var = "int rv = -1";
        my $single_ret_type = "int";
1237 1238 1239 1240 1241
        my $single_ret_as_list = 0;
        my $single_ret_list_error_msg_type = "undefined";
        my $single_ret_list_name = "undefined";
        my $single_ret_list_max_var = "undefined";
        my $single_ret_list_max_define = "undefined";
1242
        my $single_ret_cleanup = 0;
1243 1244
        my $multi_ret = 0;

1245
        if ($rettype ne "void" and
1246 1247 1248 1249
            scalar(@{$call->{ret_members}}) > 1) {
            $multi_ret = 1;
        }

1250
        if ($rettype eq "void") {
1251
            $call_ret = "NULL";
1252
        } else {
1253
            push(@vars_list, "$rettype ret");
1254 1255

            foreach my $ret_member (@{$call->{ret_members}}) {
1256
                if ($multi_ret) {
1257
                    if ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+)\[\S+\];/) {
1258 1259 1260 1261
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            die "legacy [u]long hyper arrays aren't supported";
                        }

1262
                        push(@ret_list, "memcpy(result->$3, ret.$3, sizeof(result->$3));");
1263 1264
                    } elsif ($ret_member =~ m/<\S+>;/ or $ret_member =~ m/\[\S+\];/) {
                        # just make all other array types fail
1265 1266
                        die "unhandled type for multi-return-value for " .
                            "procedure $call->{name}: $ret_member";
1267
                    } elsif ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+);/) {
1268 1269 1270 1271 1272 1273 1274
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            my $sign = ""; $sign = "U" if ($1);

                            push(@ret_list, "HYPER_TO_${sign}LONG(result->$3, ret.$3);");
                        } else {
                            push(@ret_list, "result->$3 = ret.$3;");
                        }
1275
                    } else {
1276 1277
                        die "unhandled type for multi-return-value for " .
                            "procedure $call->{name}: $ret_member";
1278
                    }
1279 1280 1281 1282 1283
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    splice(@args_list, int($3), 0, ("char **const $1"));
                    push(@ret_list, "rv = ret.$1.$1_len;");
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
1284 1285 1286 1287
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
                    $single_ret_list_max_var = "max$1";
                    $single_ret_list_max_define = $2;
1288 1289 1290
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "remote_nonnull_string array without insert@<offset> annotation: $ret_member";
1291
                } elsif ($ret_member =~ m/^remote_nonnull_string (\S+);/) {
1292 1293 1294
                    push(@ret_list, "rv = ret.$1;");
                    $single_ret_var = "char *rv = NULL";
                    $single_ret_type = "char *";
1295 1296 1297 1298 1299
                } elsif ($ret_member =~ m/^remote_string (\S+);/) {
                    push(@ret_list, "rv = ret.$1 ? *ret.$1 : NULL;");
                    push(@ret_list, "VIR_FREE(ret.$1);");
                    $single_ret_var = "char *rv = NULL";
                    $single_ret_type = "char *";
1300
                } elsif ($ret_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|node_device|interface|secret|nwfilter|domain_snapshot) (\S+);/) {
1301 1302
                    my $name = $1;
                    my $arg_name = $2;
1303
                    my $type_name = name_to_TypeName($name);
1304 1305 1306 1307 1308 1309 1310 1311 1312

                    if ($name eq "node_device") {
                        $priv_name = "devMonPrivateData";
                    } elsif ($name =~ m/^storage_/) {
                        $priv_name = "storagePrivateData";
                    } elsif (!($name =~ m/^domain/)) {
                        $priv_name = "${name}PrivateData";
                    }

1313 1314 1315 1316 1317 1318 1319 1320
                    if ($call->{ProcName} eq "DomainCreateWithFlags") {
                        # SPECIAL: virDomainCreateWithFlags updates the given
                        #          domain object instead of returning a new one
                        push(@ret_list, "dom->id = ret.dom.id;");
                        push(@ret_list, "xdr_free((xdrproc_t)xdr_$call->{ret}, (char *)&ret);");
                        push(@ret_list, "rv = 0;");
                        $single_ret_var = "int rv = -1";
                        $single_ret_type = "int";
1321
                    } else {
1322
                        if ($name eq "domain_snapshot") {
1323 1324 1325
                            my $dom = "$priv_src";
                            $dom =~ s/->conn//;
                            push(@ret_list, "rv = get_nonnull_$name($dom, ret.$arg_name);");
1326 1327 1328
                        } else {
                            push(@ret_list, "rv = get_nonnull_$name($priv_src, ret.$arg_name);");
                        }
1329

1330
                        push(@ret_list, "xdr_free((xdrproc_t)xdr_$rettype, (char *)&ret);");
1331 1332 1333
                        $single_ret_var = "vir${type_name}Ptr rv = NULL";
                        $single_ret_type = "vir${type_name}Ptr";
                    }
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
                } elsif ($ret_member =~ m/^remote_typed_param (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    splice(@args_list, int($3), 0, ("virTypedParameterPtr $1"));
                    push(@ret_list2, "if (remoteDeserializeTypedParameters(ret.$1.$1_val,\n" .
                                     "                                         ret.$1.$1_len,\n" .
                                     "                                         $2,\n" .
                                     "                                         $1,\n" .
                                     "                                         n$1) < 0)\n" .
                                     "        goto cleanup;\n");
                    $single_ret_cleanup = 1;
                } elsif ($ret_member =~ m/^remote_typed_param (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "remote_typed_param array without insert@<offset> annotation: $ret_member";
1346
                } elsif ($ret_member =~ m/^int (\S+);/) {
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
                    my $arg_name = $1;

                    if ($call->{ProcName} =~ m/GetAutostart$/) {
                        push(@args_list, "int *$arg_name");
                        push(@ret_list, "if ($arg_name) *$arg_name = ret.$arg_name;");
                        push(@ret_list, "rv = 0;");
                    } else {
                        push(@ret_list, "rv = ret.$arg_name;");
                    }

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
                } elsif ($ret_member =~ m/^(unsigned )?hyper (\S+);\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    my $type_name = $1;
                    my $sign = ""; $sign = "U" if ($1);
                    my $ret_name = $2;
                    my $insert = $3;

                    if (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        $type_name .= "long";
                        push(@ret_list, "if ($ret_name) HYPER_TO_${sign}LONG(*$ret_name, ret.$ret_name);");
                    } else {
                        $type_name .= "long long";
                        push(@ret_list, "if ($ret_name) *$ret_name = ret.$ret_name;");
                    }

                    splice(@args_list, int($insert), 0, ("$type_name *$ret_name"));
                    push(@ret_list, "rv = 0;");
1375 1376
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
1377
                } elsif ($ret_member =~ m/^unsigned hyper (\S+);/) {
1378
                    my $ret_name = $1;
1379

1380
                    if ($call->{ProcName} =~ m/Get(Lib)?Version/) {
1381 1382
                        push(@args_list, "unsigned long *$ret_name");
                        push(@ret_list, "if ($ret_name) HYPER_TO_ULONG(*$ret_name, ret.$ret_name);");
1383 1384 1385
                        push(@ret_list, "rv = 0;");
                        $single_ret_var = "int rv = -1";
                        $single_ret_type = "int";
1386 1387
                    } elsif (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        push(@ret_list, "HYPER_TO_ULONG(rv, ret.$ret_name);");
1388 1389
                        $single_ret_var = "unsigned long rv = 0";
                        $single_ret_type = "unsigned long";
1390 1391 1392 1393
                    } else {
                        push(@ret_list, "rv = ret.$ret_name;");
                        $single_ret_var = "unsigned long long rv = 0";
                        $single_ret_type = "unsigned long long";
1394
                    }
1395 1396
                } elsif ($ret_member =~ m/^(\/)?\*/) {
                    # ignore comments
1397
                } else {
1398 1399
                    die "unhandled type for return value for procedure " .
                        "$call->{name}: $ret_member";
1400 1401 1402 1403
                }
            }
        }

1404 1405
        # select struct type for multi-return-value functions
        if ($multi_ret) {
1406 1407
            if (!(defined $call->{ret_offset})) {
                die "multi-return-value without insert@<offset> annotation: $call->{ret}";
1408 1409
            }

1410 1411
            my $struct_name = $call->{ProcName};
            $struct_name =~ s/Get//;
1412

1413
            splice(@args_list, $call->{ret_offset}, 0, ("vir${struct_name}Ptr result"));
1414 1415
        }

1416 1417 1418 1419
        if ($call->{streamflag} ne "none") {
            splice(@args_list, $call->{streamoffset}, 0, ("virStreamPtr st"));
        }

1420 1421
        # print function
        print "\n";
1422
        print "static $single_ret_type\n";
1423
        print "$structprefix$call->{ProcName}(";
1424 1425 1426 1427 1428

        print join(", ", @args_list);

        print ")\n";
        print "{\n";
1429
        print "    $single_ret_var;\n";
1430 1431 1432 1433 1434 1435
        print "    struct private_data *priv = $priv_src->$priv_name;\n";

        foreach my $var (@vars_list) {
            print "    $var;\n";
        }

1436 1437 1438 1439
        if ($single_ret_as_list) {
            print "    int i;\n";
        }

1440
        if ($call->{streamflag} ne "none") {
1441
            print "    virNetClientStreamPtr netst = NULL;\n";
1442 1443
        }

1444 1445 1446
        print "\n";
        print "    remoteDriverLock(priv);\n";

1447 1448
        if ($call->{streamflag} ne "none") {
            print "\n";
1449
            print "    if (!(netst = virNetClientStreamNew(priv->remoteProgram, $call->{constname}, priv->counter)))\n";
1450
            print "        goto done;\n";
1451
            print "\n";
1452
            print "    if (virNetClientAddStream(priv->client, netst) < 0) {\n";
1453
            print "        virObjectUnref(netst);\n";
1454
            print "        goto done;\n";
1455 1456
            print "    }";
            print "\n";
1457
            print "    st->driver = &remoteStreamDrv;\n";
1458
            print "    st->privateData = netst;\n";
1459 1460
        }

1461 1462 1463 1464 1465 1466 1467 1468 1469
        if ($call->{ProcName} eq "SupportsFeature") {
            # SPECIAL: VIR_DRV_FEATURE_REMOTE feature is handled directly
            print "\n";
            print "    if (feature == VIR_DRV_FEATURE_REMOTE) {\n";
            print "        rv = 1;\n";
            print "        goto done;\n";
            print "    }\n";
        }

1470 1471 1472
        foreach my $args_check (@args_check_list) {
            print "\n";
            print "    if ($args_check->{arg} > $args_check->{limit}) {\n";
1473 1474 1475
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"%s length greater than maximum: %d > %d\"),\n";
            print "                       $args_check->{name}, (int)$args_check->{arg}, $args_check->{limit});\n";
1476 1477 1478 1479
            print "        goto done;\n";
            print "    }\n";
        }

1480 1481 1482
        if ($single_ret_as_list) {
            print "\n";
            print "    if ($single_ret_list_max_var > $single_ret_list_max_define) {\n";
1483 1484 1485
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"too many remote ${single_ret_list_error_msg_type}s: %d > %d\"),\n";
            print "                       $single_ret_list_max_var, $single_ret_list_max_define);\n";
1486 1487 1488 1489
            print "        goto done;\n";
            print "    }\n";
        }

1490
        if (@setters_list) {
1491
            print "\n";
1492 1493 1494 1495 1496 1497 1498 1499 1500
            print "    ";
        }

        print join("\n    ", @setters_list);

        if (@setters_list) {
            print "\n";
        }

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
        if (@setters_list2) {
            print "\n";
            print "    ";
        }

        print join("\n    ", @setters_list2);

        if (@setters_list2) {
            print "\n";
        }

1512
        if ($rettype ne "void") {
1513
            print "\n";
1514
            print "    memset(&ret, 0, sizeof(ret));\n";
1515 1516
        }

1517 1518 1519 1520 1521
        my $callflags = "0";
        if ($structprefix eq "qemu") {
            $callflags = "REMOTE_CALL_QEMU";
        }

1522
        print "\n";
1523
        print "    if (call($priv_src, priv, $callflags, $call->{constname},\n";
1524 1525
        print "             (xdrproc_t)xdr_$argtype, (char *)$call_args,\n";
        print "             (xdrproc_t)xdr_$rettype, (char *)$call_ret) == -1) {\n";
1526 1527

        if ($call->{streamflag} ne "none") {
1528
            print "        virNetClientRemoveStream(priv->client, netst);\n";
1529
            print "        virObjectUnref(netst);\n";
1530 1531
            print "        st->driver = NULL;\n";
            print "        st->privateData = NULL;\n";
1532 1533
        }

1534
        print "        goto done;\n";
1535
        print "    }\n";
1536
        print "\n";
1537

1538 1539
        if ($single_ret_as_list) {
            print "    if (ret.$single_ret_list_name.${single_ret_list_name}_len > $single_ret_list_max_var) {\n";
1540 1541 1542
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"too many remote ${single_ret_list_error_msg_type}s: %d > %d\"),\n";
            print "                       ret.$single_ret_list_name.${single_ret_list_name}_len, $single_ret_list_max_var);\n";
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
            print "        goto cleanup;\n";
            print "    }\n";
            print "\n";
            print "    /* This call is caller-frees (although that isn't clear from\n";
            print "     * the documentation).  However xdr_free will free up both the\n";
            print "     * names and the list of pointers, so we have to strdup the\n";
            print "     * names here. */\n";
            print "    for (i = 0; i < ret.$single_ret_list_name.${single_ret_list_name}_len; ++i) {\n";
            print "        ${single_ret_list_name}[i] = strdup(ret.$single_ret_list_name.${single_ret_list_name}_val[i]);\n";
            print "\n";
            print "        if (${single_ret_list_name}[i] == NULL) {\n";
            print "            for (--i; i >= 0; --i)\n";
            print "                VIR_FREE(${single_ret_list_name}[i]);\n";
            print "\n";
            print "            virReportOOMError();\n";
            print "            goto cleanup;\n";
            print "        }\n";
            print "    }\n";
            print "\n";
        }

1564 1565 1566 1567 1568 1569
        if (@ret_list2) {
            print "    ";
            print join("\n    ", @ret_list2);
            print "\n";
        }

1570 1571 1572 1573
        if (@ret_list) {
            print "    ";
            print join("\n    ", @ret_list);
            print "\n";
1574 1575
        }

1576
        if ($call->{ProcName} eq "DomainDestroy" ||
1577 1578
            $call->{ProcName} eq "DomainSave" ||
            $call->{ProcName} eq "DomainManagedSave") {
1579
            # SPECIAL: virDomain{Destroy|Save|ManagedSave} need to reset
1580
            # the domain id explicitly on success
1581 1582 1583
            print "    dom->id = -1;\n";
        }

1584
        if ($multi_ret or !@ret_list) {
1585 1586 1587
            print "    rv = 0;\n";
        }

1588
        if ($single_ret_as_list or $single_ret_cleanup) {
1589 1590
            print "\n";
            print "cleanup:\n";
1591
            print "    xdr_free((xdrproc_t)xdr_$call->{ret}, (char *)&ret);\n";
1592 1593
        }

1594 1595
        print "\n";
        print "done:\n";
1596 1597 1598

        print join("\n", @free_list);

1599 1600 1601 1602 1603
        print "    remoteDriverUnlock(priv);\n";
        print "    return rv;\n";
        print "}\n";
    }
}