sbus_codegen revision 66277b21179d95f6e96abed01a20ccbccf27ce99
2505N/A#!/usr/bin/python2
2505N/A
2505N/A#
2505N/A# Authors:
4364N/A# Stef Walter <stefw@redhat.com>
4364N/A#
4820N/A# Copyright (C) 2014 Red Hat
1426N/A#
1426N/A# This program is free software; you can redistribute it and/or modify
1426N/A# it under the terms of the GNU General Public License as published by
797N/A# the Free Software Foundation; either version 3 of the License, or
797N/A# (at your option) any later version.
797N/A#
797N/A# This program is distributed in the hope that it will be useful,
797N/A# but WITHOUT ANY WARRANTY; without even the implied warranty of
797N/A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
797N/A# GNU General Public License for more details.
797N/A#
797N/A# You should have received a copy of the GNU General Public License
1426N/A# along with this program. If not, see <http://www.gnu.org/licenses/>.
4364N/A#
4364N/A
4820N/A#
1426N/A# Some parser code from GLib
1426N/A#
1426N/A# Copyright (C) 2008-2011 Red Hat, Inc.
797N/A#
797N/A# This library is free software; you can redistribute it and/or
797N/A# modify it under the terms of the GNU Lesser General Public
797N/A# License as published by the Free Software Foundation; either
797N/A# version 2 of the License, or (at your option) any later version.
797N/A#
797N/A# This library is distributed in the hope that it will be useful,
797N/A# but WITHOUT ANY WARRANTY; without even the implied warranty of
797N/A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1426N/A# Lesser General Public License for more details.
4364N/A#
4364N/A# You should have received a copy of the GNU Lesser General
4364N/A# Public License along with this library; if not, write to the
2505N/A# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
2505N/A# Boston, MA 02111-1307, USA.
4364N/A#
4364N/A# Portions by: David Zeuthen <davidz@redhat.com>
4364N/A#
4364N/A
4364N/A#
4364N/A# DBus interfaces are defined here:
4364N/A#
2505N/A# http://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format
4364N/A#
4002N/A# The introspection data format has become the standard way to represent a
4820N/A# DBus interface. For many examples see /usr/share/dbus-1/interfaces/ on a
4820N/A# typical linux machine.
4364N/A#
4364N/A# A word about annotations. These are extra flags or values that can be
4364N/A# assigned to anything. So far, the codegen supports this annotation:
4364N/A#
4364N/A# org.freedesktop.DBus.GLib.CSymbol
4364N/A# - An annotation specified in the specification that tells us what C symbol
4364N/A# to generate for a given interface or method. By default the codegen will
4820N/A# build up a symbol name from the DBus name.
4364N/A#
4364N/A
4364N/Aimport optparse
4364N/Aimport os
4364N/Aimport re
4364N/Aimport StringIO
4364N/Aimport sys
4364N/Aimport xml.parsers.expat
4364N/A
4820N/A# -----------------------------------------------------------------------------
4614N/A# Objects
4364N/A
4364N/Aclass DBusXmlException(Exception):
4364N/A line = 0
4364N/A file = None
4614N/A
4364N/A # Lets us print problems like a compiler would
4820N/A def __str__(self):
4364N/A message = Exception.__str__(self)
4364N/A if self.file and self.line:
4364N/A return "%s:%d: %s" % (self.file, self.line, message)
4364N/A elif self.file:
4364N/A return "%s: %s" % (self.file, message)
4364N/A else:
4364N/A return message
4820N/A
4364N/Aclass Base:
4364N/A def __init__(self, name):
4364N/A if not name:
4364N/A raise DBusXmlException('No name on element')
4364N/A self.name = name
4364N/A self.annotations = { }
4364N/A def validate(self):
4364N/A pass
4364N/A def c_name(self):
4364N/A return self.annotations.get("org.freedesktop.DBus.GLib.CSymbol", self.name)
4364N/A
4820N/A# The basic types that we support marshalling right now. These
4364N/A# are the ones we can pass as basic arguments to libdbus directly.
2505N/A# If the dbus and sssd types are identical we pass things directly.
4364N/A# otherwise some copying is necessary.
4364N/ABASIC_TYPES = {
4364N/A 'y': ( "DBUS_TYPE_BYTE", "uint8_t", "uint8_t" ),
4364N/A 'b': ( "DBUS_TYPE_BOOLEAN", "dbus_bool_t", "bool" ),
4364N/A 'n': ( "DBUS_TYPE_INT16", "int16_t", "int16_t" ),
4364N/A 'q': ( "DBUS_TYPE_UINT16", "uint16_t", "uint16_t" ),
4364N/A 'i': ( "DBUS_TYPE_INT32", "int32_t", "int32_t" ),
4364N/A 'u': ( "DBUS_TYPE_UINT32", "uint32_t", "uint32_t" ),
4364N/A 'x': ( "DBUS_TYPE_INT64", "int64_t", "int64_t" ),
4364N/A 't': ( "DBUS_TYPE_UINT64", "uint64_t", "uint64_t" ),
4820N/A 'd': ( "DBUS_TYPE_DOUBLE", "double", "double" ),
4364N/A 's': ( "DBUS_TYPE_STRING", "const char *", "const char *" ),
4364N/A 'o': ( "DBUS_TYPE_OBJECT_PATH", "const char *", "const char *" ),
4364N/A}
2505N/A
2505N/Aclass Typed(Base):
4002N/A def __init__(self, name, type):
2505N/A Base.__init__(self, name)
4002N/A self.type = type
4820N/A self.is_basic = False
5169N/A self.is_array = False
797N/A self.dbus_constant = None
797N/A self.dbus_type = None
4002N/A self.sssd_type = None
4002N/A if type[0] == 'a':
4002N/A type = type[1:]
4002N/A self.is_array = True
4002N/A if type in BASIC_TYPES:
4364N/A (self.dbus_constant, self.dbus_type, self.sssd_type) = BASIC_TYPES[type]
4002N/A # If types are not identical, we can't do array (yet)
4002N/A if self.is_array:
4002N/A self.is_basic = (self.dbus_type == self.sssd_type)
4820N/A else:
4002N/A self.is_basic = True
4002N/A
797N/Aclass Arg(Typed):
4364N/A def __init__(self, method, name, type):
4002N/A Typed.__init__(self, name, type)
4002N/A self.method = method
4002N/A
4820N/Aclass Method(Base):
797N/A def __init__(self, iface, name):
4002N/A Base.__init__(self, name)
4002N/A self.iface = iface
4364N/A self.in_args = []
4002N/A self.out_args = []
4002N/A def validate(self):
4002N/A if not self.only_basic_args() and not self.use_raw_handler():
797N/A raise DBusXmlException("Method has complex arguments and requires " +
4364N/A "the 'org.freedesktop.sssd.RawHandler' annotation")
4364N/A def fq_c_name(self):
4364N/A return "%s_%s" % (self.iface.c_name(), self.c_name())
4364N/A def use_raw_handler(self):
797N/A anno = 'org.freedesktop.sssd.RawHandler'
4002N/A return self.annotations.get(anno, self.iface.annotations.get(anno)) == 'true'
797N/A def in_signature(self):
4364N/A return "".join([arg.type for arg in self.in_args])
4364N/A def only_basic_args(self):
1426N/A for arg in self.in_args + self.out_args:
4002N/A if not arg.is_basic:
4002N/A return False
4002N/A return True
797N/A
4002N/Aclass Signal(Base):
797N/A def __init__(self, iface, name):
4002N/A Base.__init__(self, name)
4002N/A self.iface = iface
4002N/A self.args = []
4364N/A def fq_c_name(self):
4364N/A return "%s_%s" % (self.iface.c_name(), self.c_name())
4002N/A
4002N/Aclass Property(Typed):
4002N/A def __init__(self, iface, name, type, access):
4002N/A Typed.__init__(self, name, type)
797N/A self.iface = iface
4364N/A self.readable = False
4002N/A self.writable = False
4002N/A if access == 'readwrite':
4002N/A self.readable = True
4002N/A self.writable = True
4002N/A elif access == 'read':
4002N/A self.readable = True
4002N/A elif access == 'write':
4364N/A self.writable = True
797N/A else:
4002N/A raise DBusXmlException('Invalid access type %s'%self.access)
4002N/A def fq_c_name(self):
4364N/A return "%s_%s" % (self.iface.c_name(), self.c_name())
4364N/A def getter_name(self):
797N/A return "%s_get_%s" % (self.iface.c_name(), self.c_name())
4002N/A def getter_invoker_name(self):
4002N/A return "invoke_get_%s" % self.type
4002N/A def getter_signature(self, name):
4364N/A sig = "void (*%s)(struct sbus_request *, void *data, %s *" % (name, self.sssd_type)
4002N/A if self.is_array:
797N/A sig += " *, int *"
4002N/A sig += ")"
797N/A return sig
4002N/A
4002N/Aclass Interface(Base):
4002N/A def __init__(self, name):
4002N/A Base.__init__(self, name)
4002N/A self.methods = []
4002N/A self.signals = []
797N/A self.properties = []
797N/A def c_name(self):
797N/A return self.annotations.get("org.freedesktop.DBus.GLib.CSymbol",
797N/A self.name.replace(".", "_"))
797N/A
797N/A# -----------------------------------------------------------------------------
4002N/A# Code Generation
4002N/A
4002N/Adef out(format, *args, **kwargs):
4002N/A str = format % args
4002N/A sys.stdout.write(str)
4002N/A # NOTE: Would like to use the following syntax for this function
4002N/A # but need to wait until python3 until it is supported:
4002N/A # def out(format, *args, new_line=True)
4002N/A if kwargs.pop("new_line", True):
4002N/A sys.stdout.write("\n")
4002N/A assert not kwargs, "unknown keyword argument(s): %s" % str(kwargs)
4002N/A
4002N/Adef method_arg_types(args, with_names=False):
4002N/A str = ""
4002N/A for arg in args:
4002N/A str += ", "
4002N/A str += arg.sssd_type
4002N/A if with_names:
797N/A if str[-1] != '*':
4002N/A str += " "
4002N/A str += "arg_"
4002N/A str += arg.c_name()
4002N/A if arg.is_array:
4002N/A str += "[], int"
4002N/A if with_names:
4002N/A str += " len_"
4002N/A str += arg.c_name()
4002N/A return str
4002N/A
4002N/Adef method_function_pointer(meth, name, with_names=False):
4002N/A if meth.use_raw_handler():
4002N/A return "sbus_msg_handler_fn " + name
4002N/A else:
4002N/A return "int (*%s)(struct sbus_request *%s, void *%s%s)" % \
4002N/A (name, with_names and "req" or "",
4002N/A with_names and "data" or "",
4002N/A method_arg_types(meth.in_args, with_names))
4002N/A
4002N/Adef property_handlers(prop):
4002N/A return prop.getter_signature(prop.getter_name())
4002N/A
4002N/Adef forward_method_invoker(signature, args):
4002N/A out("")
4002N/A out("/* invokes a handler with a '%s' DBus signature */", signature)
4002N/A out("static int invoke_%s_method(struct sbus_request *dbus_req, void *function_ptr);", signature)
4002N/A
4002N/Adef source_method_invoker(signature, args):
4002N/A out("")
4002N/A out("/* invokes a handler with a '%s' DBus signature */", signature)
4002N/A out("static int invoke_%s_method(struct sbus_request *dbus_req, void *function_ptr)", signature)
797N/A out("{")
4364N/A for i in range(0, len(args)):
4002N/A arg = args[i]
4002N/A if arg.is_array:
4002N/A out(" %s *arg_%d;", arg.dbus_type, i)
4002N/A out(" int len_%d;", i)
797N/A else:
4002N/A out(" %s arg_%d;", arg.dbus_type, i)
4002N/A out(" int (*handler)(struct sbus_request *, void *%s) = function_ptr;", method_arg_types(args))
4364N/A out("")
797N/A out(" if (!sbus_request_parse_or_finish(dbus_req,")
4002N/A for i in range(0, len(args)):
4002N/A arg = args[i]
4364N/A if arg.is_array:
4364N/A out(" DBUS_TYPE_ARRAY, %s, &arg_%d, &len_%d,",
1426N/A arg.dbus_constant, i, i)
797N/A else:
797N/A out(" %s, &arg_%d,", arg.dbus_constant, i)
797N/A out(" DBUS_TYPE_INVALID)) {")
4364N/A out(" return EOK; /* request handled */")
1426N/A out(" }")
4002N/A out("")
1426N/A
4364N/A out(" return (handler)(dbus_req, dbus_req->intf->handler_data", new_line=False)
797N/A for i in range(0, len(args)):
797N/A arg = args[i]
797N/A out(",\n arg_%d", i, new_line=False)
4002N/A if arg.is_array:
4002N/A out(",\n len_%d", i, new_line=False)
4002N/A out(");")
3070N/A out("}")
4364N/A
3070N/Adef source_prop_types(prop, type_prefix=False):
4002N/A prefix = "%s_" % prop.type if type_prefix else ""
4002N/A if prop.is_array:
4002N/A out(" %s *%sprop_val;", prop.sssd_type, prefix)
3070N/A out(" int %sprop_len;", prefix)
4002N/A out(" %s *%sout_val;", prop.dbus_type, prefix)
4002N/A else:
3070N/A out(" %s %sprop_val;", prop.sssd_type, prefix)
3070N/A out(" %s %sout_val;", prop.dbus_type, prefix)
4364N/A
4364N/Adef source_prop_handler(prop, type_prefix=False):
4820N/A prefix = "%s_" % prop.type if type_prefix else ""
4002N/A out(" %s", prop.getter_signature("%shandler" % prefix), new_line=False)
4002N/A out(";")
797N/A
4364N/Adef source_getter_invoker(prop):
797N/A out("")
797N/A if prop.is_array:
4002N/A out("/* invokes a getter with an array of '%s' DBus type */", prop.dbus_type)
4002N/A else:
4002N/A out("/* invokes a getter with a '%s' DBus type */", prop.dbus_type)
797N/A out("static int %s(struct sbus_request *dbus_req, void *function_ptr)",
4002N/A prop.getter_invoker_name())
797N/A out("{")
4002N/A
4002N/A source_prop_types(prop)
4002N/A
4002N/A out("")
4002N/A out(" %s", prop.getter_signature("handler"), new_line=False)
4002N/A out(" = function_ptr;")
4002N/A out("")
4002N/A
4002N/A out(" (handler)(dbus_req, dbus_req->intf->handler_data, &prop_val", new_line=False)
4002N/A if prop.is_array:
4002N/A out(", &prop_len", new_line=False)
4002N/A out(");")
4002N/A
4002N/A out("")
4002N/A if prop.type == "s":
4002N/A out(" out_val = prop_val == NULL ? \"\" : prop_val;")
4002N/A elif prop.type == "o":
4002N/A out(" out_val = prop_val == NULL ? \"/\" : prop_val;")
4002N/A else:
4002N/A out(" out_val = prop_val;")
4002N/A if prop.is_array:
4002N/A out(" return sbus_request_return_array_as_variant(dbus_req, %s, (uint8_t*)out_val, prop_len, sizeof(%s));", prop.dbus_constant, prop.sssd_type)
4002N/A else:
4002N/A out(" return sbus_request_return_as_variant(dbus_req, %s, &out_val);", prop.dbus_constant)
4002N/A out("}")
797N/A
797N/Adef source_getall_invoker(iface, prop_invokers):
797N/A out("")
4002N/A out("/* invokes GetAll for the '%s' interface */", iface.name)
4002N/A out("static int invoke_%s_get_all(struct sbus_request *dbus_req, void *function_ptr)",
797N/A iface.c_name())
4364N/A out("{")
4364N/A out(" DBusMessage *reply;")
4364N/A out(" dbus_bool_t dbret;")
4364N/A out(" DBusMessageIter iter;")
4002N/A out(" DBusMessageIter iter_dict;")
4002N/A if iface.properties:
4002N/A out(" int ret;")
4820N/A out(" struct sbus_interface *intf = dbus_req->intf;")
4002N/A out(" const struct sbus_property_meta *property;")
4002N/A
4002N/A iface_types = [ p.type for p in iface.properties ]
4364N/A for prop in [ p for p in prop_invokers.values() if p.type in iface_types ]:
4002N/A source_prop_types(prop, type_prefix=True)
4002N/A source_prop_handler(prop, type_prefix=True)
4002N/A out("")
4364N/A
4364N/A out(" reply = dbus_message_new_method_return(dbus_req->message);")
4002N/A out(" if (!reply) return ENOMEM;")
4002N/A out(" dbus_message_iter_init_append(reply, &iter);")
4002N/A out(" dbret = dbus_message_iter_open_container(")
4002N/A out(" &iter, DBUS_TYPE_ARRAY,")
4364N/A out(" DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING")
797N/A out(" DBUS_TYPE_STRING_AS_STRING")
797N/A out(" DBUS_TYPE_VARIANT_AS_STRING")
797N/A out(" DBUS_DICT_ENTRY_END_CHAR_AS_STRING,")
4002N/A out(" &iter_dict);")
4002N/A out(" if (!dbret) return ENOMEM;")
4002N/A out("")
797N/A
4002N/A for prop in iface.properties:
4002N/A out(" property = sbus_meta_find_property(intf->vtable->meta, \"%s\");", prop.c_name())
4002N/A out(" if (property != NULL && property->flags & SBUS_PROPERTY_READABLE) {")
4002N/A out(" %s_handler = VTABLE_FUNC(intf->vtable, property->vtable_offset_get);", prop.type)
797N/A out(" if (%s_handler) {", prop.type)
797N/A out(" (%s_handler)(dbus_req, dbus_req->intf->handler_data, &%s_prop_val", prop.type, prop.type, new_line=False)
4002N/A if prop.is_array:
4002N/A out(", &%s_prop_len", prop.type, new_line=False)
4368N/A out(");")
4368N/A if prop.type == "s":
4820N/A out(" %s_out_val = %s_prop_val == NULL ? \"\" : %s_prop_val;",
4820N/A prop.type, prop.type, prop.type)
4820N/A elif prop.type == "o":
4820N/A out(" %s_out_val = %s_prop_val == NULL ? \"/\" : %s_prop_val;",
4002N/A prop.type, prop.type, prop.type)
4820N/A else:
797N/A out(" %s_out_val = %s_prop_val;", prop.type, prop.type)
4820N/A if prop.is_array:
797N/A out(" ret = sbus_add_array_as_variant_to_dict(&iter_dict, \"%s\", %s, (uint8_t*)%s_out_val, %s_prop_len, sizeof(%s));", prop.c_name(), prop.dbus_constant, prop.type, prop.type, prop.sssd_type)
797N/A else:
4002N/A out(" ret = sbus_add_variant_to_dict(&iter_dict, \"%s\", %s, &%s_out_val);", prop.c_name(), prop.dbus_constant, prop.type)
4002N/A out(" if (ret != EOK) return ret;")
4820N/A out(" }")
4820N/A out(" }")
4820N/A out("")
797N/A
797N/A out(" dbret = dbus_message_iter_close_container(&iter, &iter_dict);")
797N/A out(" if (!dbret) return ENOMEM;")
4002N/A out("")
4820N/A
4820N/A out(" return sbus_request_finish(dbus_req, reply);")
4002N/A out("}")
4820N/A
4002N/Adef forward_method_invokers(ifaces):
797N/A invokers = { }
4820N/A for iface in ifaces:
4820N/A for meth in iface.methods:
797N/A if meth.use_raw_handler() or not meth.in_args:
4820N/A continue
797N/A signature = meth.in_signature()
797N/A if signature in invokers:
797N/A continue
797N/A forward_method_invoker(signature, meth.in_args)
4820N/A invokers[signature] = meth
4820N/A return invokers
4820N/A
4820N/Adef source_method_invokers(invokers):
797N/A for (signature, meth) in invokers.items():
4820N/A source_method_invoker(signature, meth.in_args)
4002N/A
4002N/Adef forward_prop_invoker(prop):
4820N/A out("static int %s(struct sbus_request *dbus_req, void *function_ptr);",
4368N/A prop.getter_invoker_name())
4368N/A
4820N/Adef forward_prop_invokers(ifaces):
797N/A invokers = { }
797N/A for iface in ifaces:
4820N/A for prop in iface.properties:
797N/A if not prop.is_basic:
4820N/A continue
4820N/A if prop.type in invokers:
4820N/A continue
4820N/A forward_prop_invoker(prop)
2505N/A invokers[prop.type] = prop
4364N/A return invokers
4364N/A
797N/Adef source_prop_invokers(invokers):
797N/A for (type, prop) in invokers.items():
797N/A if prop.readable:
797N/A source_getter_invoker(prop)
1426N/A
1426N/Adef source_finisher(meth):
4002N/A out("")
797N/A out("int %s_finish(struct sbus_request *req%s)",
797N/A meth.fq_c_name(), method_arg_types(meth.out_args, with_names=True))
1426N/A out("{")
1426N/A
1426N/A for arg in meth.out_args:
1426N/A if arg.dbus_type != arg.sssd_type:
1426N/A out(" %s cast_%s = arg_%s;", arg.dbus_type, arg.c_name(), arg.c_name())
1426N/A
1426N/A out(" return sbus_request_return_and_finish(req,")
797N/A for arg in meth.out_args:
1426N/A out(" ", new_line=False)
2377N/A if arg.is_array:
2377N/A out("DBUS_TYPE_ARRAY, %s, &arg_%s, len_%s,",
4820N/A arg.dbus_constant, arg.c_name(), arg.c_name())
4820N/A elif arg.dbus_type != arg.sssd_type:
4820N/A out("%s, &cast_%s,", arg.dbus_constant, arg.c_name())
4820N/A else:
4820N/A out("%s, &arg_%s,", arg.dbus_constant, arg.c_name())
4820N/A out(" DBUS_TYPE_INVALID);")
4820N/A out("}")
4820N/A
4820N/Adef header_reply(meth):
4820N/A for arg in meth.out_args:
4820N/A if arg.is_array:
4820N/A out(" %s *%s", arg.dbus_type, arg.c_name())
4820N/A out(" int %s__len", arg.c_name())
4820N/A else:
4002N/A out(" %s %s;", arg.dbus_type, arg.c_name())
4820N/A types = [arg.sssd_type for arg in meth.in_args]
4820N/A
4820N/Adef source_args(parent, args, suffix):
4820N/A out("")
4820N/A out("/* arguments for %s.%s */", parent.iface.name, parent.name)
4364N/A out("const struct sbus_arg_meta %s%s[] = {", parent.fq_c_name(), suffix)
4820N/A for arg in args:
4820N/A out(" { \"%s\", \"%s\" },", arg.name, arg.type)
2377N/A out(" { NULL, }")
4820N/A out("};")
2377N/A
4002N/Adef source_methods(iface, methods):
2377N/A for meth in methods:
4002N/A if meth.in_args:
4820N/A source_args(meth, meth.in_args, "__in")
4820N/A if meth.out_args:
4820N/A source_args(meth, meth.out_args, "__out")
4820N/A
4820N/A if not meth.use_raw_handler():
4820N/A source_finisher(meth)
4820N/A
4820N/A out("")
4820N/A out("/* methods for %s */", iface.name)
4820N/A out("const struct sbus_method_meta %s__methods[] = {", iface.c_name())
4820N/A for meth in methods:
4820N/A out(" {")
4820N/A out(" \"%s\", /* name */", meth.name)
4820N/A if meth.in_args:
4820N/A out(" %s__in,", meth.fq_c_name())
4820N/A else:
3325N/A out(" NULL, /* no in_args */")
3325N/A if meth.out_args:
4820N/A out(" %s__out,", meth.fq_c_name())
4002N/A else:
4002N/A out(" NULL, /* no out_args */")
4002N/A out(" offsetof(struct %s, %s),", iface.c_name(), meth.c_name())
4364N/A if meth.use_raw_handler() or not meth.in_args:
4002N/A out(" NULL, /* no invoker */")
3325N/A else:
4002N/A out(" invoke_%s_method,", meth.in_signature())
3325N/A out(" },")
3325N/A out(" { NULL, }")
4002N/A out("};")
4002N/A
4820N/Adef source_signals(iface, signals):
4820N/A for sig in iface.signals:
4820N/A if sig.args:
4820N/A source_args(sig, sig.args, "__args")
4820N/A
4820N/A out("")
4820N/A out("/* signals for %s */", iface.name)
4820N/A out("const struct sbus_signal_meta %s__signals[] = {", iface.c_name())
4820N/A for sig in signals:
4820N/A out(" {")
4820N/A out(" \"%s\", /* name */", sig.name)
4820N/A if sig.args:
4820N/A out(" %s__args", sig.fq_c_name())
4820N/A else:
4820N/A out(" NULL, /* no args */")
4820N/A out(" },")
4820N/A out(" { NULL, }")
4820N/A out("};")
4820N/A
4820N/Adef source_properties(iface, properties):
4820N/A out("")
4820N/A out("/* property info for %s */", iface.name)
4820N/A
4820N/A out("const struct sbus_property_meta %s__properties[] = {", iface.c_name())
4820N/A for prop in properties:
4820N/A out(" {")
4820N/A out(" \"%s\", /* name */", prop.name)
4820N/A out(" \"%s\", /* type */", prop.type)
4820N/A if prop.readable and prop.writable:
4820N/A out(" SBUS_PROPERTY_READABLE | SBUS_PROPERTY_WRITABLE,")
4820N/A elif prop.readable:
4820N/A out(" SBUS_PROPERTY_READABLE,")
4820N/A elif prop.writable:
4820N/A out(" SBUS_PROPERTY_WRITABLE,")
4820N/A else:
4820N/A assert False, "should not be reached"
4820N/A if prop.readable:
4820N/A out(" offsetof(struct %s, %s),", iface.c_name(), prop.getter_name())
4820N/A out(" %s,", prop.getter_invoker_name())
4820N/A else:
4820N/A out(" 0, /* not readable */")
4820N/A out(" NULL, /* no invoker */")
4820N/A out(" 0, /* not writable */")
4820N/A out(" NULL, /* no invoker */")
4820N/A out(" },")
4820N/A out(" { NULL, }")
4820N/A out("};")
4820N/A
4820N/Adef header_interface(iface):
4820N/A out("")
4820N/A out("/* interface info for %s */", iface.name)
4820N/A out("extern const struct sbus_interface_meta %s_meta;", iface.c_name())
4820N/A
4820N/Adef source_interface(iface):
4820N/A out("")
4820N/A out("/* interface info for %s */", iface.name)
4820N/A out("const struct sbus_interface_meta %s_meta = {", iface.c_name())
4820N/A out(" \"%s\", /* name */", iface.name)
4820N/A if iface.methods:
4820N/A out(" %s__methods,", iface.c_name())
4820N/A else:
4820N/A out(" NULL, /* no methods */")
4820N/A if iface.signals:
4820N/A out(" %s__signals,", iface.c_name())
4820N/A else:
4820N/A out(" NULL, /* no signals */")
4820N/A if iface.properties:
4820N/A out(" %s__properties,", iface.c_name())
4820N/A else:
4820N/A out(" NULL, /* no properties */")
4820N/A out(" invoke_%s_get_all, /* GetAll invoker */", iface.c_name())
4820N/A out("};")
4820N/A
4820N/Adef generate_source(ifaces, filename, include_header=None):
4820N/A basename = os.path.basename(filename)
4820N/A
4820N/A out("/* The following definitions are auto-generated from %s */", basename)
4820N/A out("")
4820N/A
4820N/A out("#include \"util/util.h\"")
4820N/A out("#include \"sbus/sssd_dbus.h\"")
4820N/A out("#include \"sbus/sssd_dbus_meta.h\"")
4820N/A if include_header:
4820N/A out("#include \"%s\"", os.path.basename(include_header))
4820N/A
4820N/A meth_invokers = forward_method_invokers(ifaces)
4820N/A prop_invokers = forward_prop_invokers(ifaces)
4820N/A
4820N/A for iface in ifaces:
4820N/A
4820N/A # The methods
4820N/A if iface.methods:
4820N/A source_methods(iface, iface.methods)
4820N/A
4820N/A # The signals array
4820N/A if iface.signals:
4820N/A source_signals(iface, iface.signals)
4820N/A
4820N/A # The properties array
4820N/A if iface.properties:
4820N/A source_properties(iface, iface.properties)
4820N/A
4820N/A # always generate getall, for interfaces without properties
4820N/A # let's return an empty array
4820N/A source_getall_invoker(iface, prop_invokers)
4820N/A # The sbus_interface structure
4820N/A source_interface(iface)
4820N/A
4820N/A source_method_invokers(meth_invokers)
4820N/A source_prop_invokers(prop_invokers)
4820N/A
4820N/Adef header_finisher(iface, meth):
4820N/A if meth.use_raw_handler():
4820N/A return
4820N/A out("")
4820N/A out("/* finish function for %s */", meth.name)
4820N/A out("int %s_finish(struct sbus_request *req%s);",
4820N/A meth.fq_c_name(), method_arg_types(meth.out_args, with_names=True))
4820N/A
4820N/Adef header_vtable(iface, methods):
4820N/A out("")
4820N/A out("/* vtable for %s */", iface.name)
4820N/A out("struct %s {", iface.c_name())
4820N/A out(" struct sbus_vtable vtable; /* derive from sbus_vtable */")
4820N/A
4820N/A # All methods
4820N/A for meth in iface.methods:
4820N/A out(" %s;", method_function_pointer(meth, meth.c_name(), with_names=True))
4820N/A for prop in iface.properties:
4820N/A out(" %s;", property_handlers(prop))
4820N/A
4820N/A out("};")
4820N/A
4820N/Adef header_constants(iface):
4820N/A out("")
4820N/A out("/* constants for %s */", iface.name)
4820N/A out("#define %s \"%s\"", iface.c_name().upper(), iface.name)
4820N/A for meth in iface.methods:
5169N/A out("#define %s \"%s\"", meth.fq_c_name().upper(), meth.name)
5169N/A for sig in iface.signals:
4820N/A out("#define %s \"%s\"", sig.fq_c_name().upper(), sig.name)
4820N/A for prop in iface.properties:
4820N/A out("#define %s \"%s\"", prop.fq_c_name().upper(), prop.name)
4820N/A
4820N/Adef generate_header(ifaces, filename):
4820N/A basename = os.path.basename(filename)
5169N/A guard = "__%s__" % re.sub(r'([^_A-Z0-9])', "_", basename.upper())
4820N/A
4820N/A out("/* The following declarations are auto-generated from %s */", basename)
4820N/A out("")
4820N/A out("#ifndef %s", guard)
4820N/A out("#define %s", guard)
4820N/A out("")
4820N/A out("#include \"sbus/sssd_dbus.h\"")
4820N/A
4820N/A out("")
4820N/A out("/* ------------------------------------------------------------------------")
4820N/A out(" * DBus Constants")
4820N/A out(" *")
4820N/A out(" * Various constants of interface and method names mostly for use by clients")
4820N/A out(" */")
4820N/A
4820N/A for iface in ifaces:
4820N/A header_constants(iface)
4820N/A
4820N/A out("")
4820N/A out("/* ------------------------------------------------------------------------")
4820N/A out(" * DBus handlers")
4820N/A out(" *")
4820N/A out(" * These structures are filled in by implementors of the different")
4820N/A out(" * dbus interfaces to handle method calls.")
4820N/A out(" *")
4820N/A out(" * Handler functions of type sbus_msg_handler_fn accept raw messages,")
4820N/A out(" * other handlers are typed appropriately. If a handler that is")
4820N/A out(" * set to NULL is invoked it will result in a")
4820N/A out(" * org.freedesktop.DBus.Error.NotSupported error for the caller.")
4820N/A out(" *")
4820N/A out(" * Handlers have a matching xxx_finish() function (unless the method has")
4820N/A out(" * accepts raw messages). These finish functions the")
4820N/A out(" * sbus_request_return_and_finish() with the appropriate arguments to")
4820N/A out(" * construct a valid reply. Once a finish function has been called, the")
4820N/A out(" * @dbus_req it was called with is freed and no longer valid.")
4820N/A out(" */")
4820N/A
4820N/A for iface in ifaces:
4820N/A if iface.methods or iface.properties:
4820N/A header_vtable(iface, iface.methods)
4820N/A for meth in iface.methods:
4820N/A header_finisher(iface, meth)
4820N/A
4820N/A out("")
4820N/A out("/* ------------------------------------------------------------------------")
4820N/A out(" * DBus Interface Metadata")
4820N/A out(" *")
4820N/A out(" * These structure definitions are filled in with the information about")
4820N/A out(" * the interfaces, methods, properties and so on.")
4820N/A out(" *")
4820N/A out(" * The actual definitions are found in the accompanying C file next")
4820N/A out(" * to this header.")
4820N/A out(" */")
4820N/A
4820N/A for iface in ifaces:
4820N/A header_interface(iface)
4820N/A
4820N/A out("")
4820N/A out("#endif /* %s */", guard)
4820N/A
4820N/A# -----------------------------------------------------------------------------
4820N/A# XML Interface Parsing
4820N/A
4820N/ASTATE_TOP = 'top'
4820N/ASTATE_NODE = 'node'
4820N/ASTATE_INTERFACE = 'interface'
4820N/ASTATE_METHOD = 'method'
4820N/ASTATE_SIGNAL = 'signal'
4820N/ASTATE_PROPERTY = 'property'
4820N/ASTATE_ARG = 'arg'
4820N/ASTATE_ANNOTATION = 'annotation'
4820N/ASTATE_IGNORED = 'ignored'
4820N/A
4820N/Adef expect_attr(attrs, name):
4820N/A if name not in attrs:
4820N/A raise DBusXmlException("Missing attribute '%s'" % name)
4820N/A if attrs[name] == "":
4820N/A raise DBusXmlException("Empty attribute '%s'" % name)
4820N/A return attrs[name]
4820N/A
4820N/Aclass DBusXMLParser:
4820N/A def __init__(self, filename):
4820N/A parser = xml.parsers.expat.ParserCreate()
4820N/A parser.CommentHandler = self.handle_comment
4820N/A parser.CharacterDataHandler = self.handle_char_data
4820N/A parser.StartElementHandler = self.handle_start_element
4820N/A parser.EndElementHandler = self.handle_end_element
4820N/A
4820N/A self.parsed_interfaces = []
4820N/A self.cur_object = None
4820N/A
4820N/A self.state = STATE_TOP
4820N/A self.state_stack = []
4820N/A self.cur_object = None
4820N/A self.cur_object_stack = []
4820N/A self.arg_count = 0
4820N/A
4820N/A try:
4820N/A with open(filename, "r") as f:
4820N/A parser.ParseFile(f)
4820N/A except DBusXmlException, ex:
4820N/A ex.line = parser.CurrentLineNumber
4820N/A ex.file = filename
4820N/A raise
4820N/A except xml.parsers.expat.ExpatError, ex:
4820N/A exc = DBusXmlException(str(ex))
4820N/A exc.line = ex.lineno
4820N/A exc.file = filename
4820N/A raise exc
4820N/A
4820N/A def handle_comment(self, data):
4820N/A pass
4820N/A
4820N/A def handle_char_data(self, data):
4820N/A pass
4820N/A
4820N/A def handle_start_element(self, name, attrs):
4820N/A old_state = self.state
4820N/A old_cur_object = self.cur_object
4820N/A if self.state == STATE_IGNORED:
4820N/A self.state = STATE_IGNORED
4820N/A elif self.cur_object and name == STATE_ANNOTATION:
4820N/A val = attrs.get('value', '')
4820N/A self.cur_object.annotations[expect_attr(attrs, 'name')] = val
4820N/A self.state = STATE_IGNORED
4820N/A elif self.state == STATE_TOP:
4820N/A if name == STATE_NODE:
4820N/A self.state = STATE_NODE
4820N/A else:
4820N/A self.state = STATE_IGNORED
4820N/A elif self.state == STATE_NODE:
4820N/A if name == STATE_INTERFACE:
4820N/A self.state = STATE_INTERFACE
4820N/A iface = Interface(expect_attr(attrs, 'name'))
4820N/A self.cur_object = iface
4820N/A self.parsed_interfaces.append(iface)
4820N/A else:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A elif self.state == STATE_INTERFACE:
4820N/A if name == STATE_METHOD:
4820N/A self.state = STATE_METHOD
4820N/A method = Method(self.cur_object, expect_attr(attrs, 'name'))
4820N/A self.cur_object.methods.append(method)
4820N/A self.cur_object = method
4820N/A self.arg_count = 0
4820N/A elif name == STATE_SIGNAL:
4820N/A self.state = STATE_SIGNAL
4820N/A signal = Signal(self.cur_object, expect_attr(attrs, 'name'))
4820N/A self.cur_object.signals.append(signal)
4820N/A self.cur_object = signal
4820N/A self.arg_count = 0
4820N/A elif name == STATE_PROPERTY:
4820N/A self.state = STATE_PROPERTY
4820N/A prop = Property(self.cur_object,
4820N/A expect_attr(attrs, 'name'),
4820N/A expect_attr(attrs, 'type'),
4820N/A expect_attr(attrs, 'access'))
4820N/A self.cur_object.properties.append(prop)
4820N/A self.cur_object = prop
4820N/A else:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A elif self.state == STATE_METHOD:
4820N/A if name == STATE_ARG:
4820N/A self.state = STATE_ARG
4820N/A arg = Arg(self.cur_object,
4820N/A expect_attr(attrs, 'name'),
4820N/A expect_attr(attrs, 'type'))
4820N/A direction = attrs.get('direction', 'in')
4820N/A if direction == 'in':
4820N/A self.cur_object.in_args.append(arg)
4820N/A elif direction == 'out':
4820N/A self.cur_object.out_args.append(arg)
4820N/A else:
4820N/A raise DBusXmlException('Invalid direction "%s"' % direction)
4820N/A self.cur_object = arg
4820N/A else:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A elif self.state == STATE_SIGNAL:
4820N/A if name == STATE_ARG:
4820N/A self.state = STATE_ARG
4820N/A arg = Arg(self.cur_object,
4820N/A expect_attr(attrs, 'name'),
4820N/A expect_attr(attrs, 'type'))
4820N/A self.cur_object.args.append(arg)
4820N/A self.cur_object = arg
4820N/A else:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A elif self.state == STATE_PROPERTY:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A elif self.state == STATE_ARG:
4820N/A self.state = STATE_IGNORED
4820N/A
4820N/A else:
4820N/A assert False, 'Unhandled state "%s" while entering element with name "%s"' % (self.state, name)
4820N/A
4820N/A self.state_stack.append(old_state)
4820N/A self.cur_object_stack.append(old_cur_object)
4820N/A
4820N/A def handle_end_element(self, name):
4820N/A if self.cur_object:
4820N/A self.cur_object.validate()
4820N/A self.state = self.state_stack.pop()
4820N/A self.cur_object = self.cur_object_stack.pop()
4820N/A
4820N/Adef parse_options():
4820N/A parser = optparse.OptionParser("usage: %prog [options] introspect.xml ...")
4820N/A parser.set_description("sbus_codegen generates sbus interface structures \
4820N/A from standard XML Introspect data.")
4820N/A parser.add_option("--mode",
4820N/A dest="mode", default="header",
4820N/A help="'header' or 'source' (default: header)",
4820N/A metavar="MODE")
4820N/A parser.add_option("--output",
4820N/A dest="output", default=None,
4820N/A help="Set output file name (default: stdout)",
4820N/A metavar="FILE")
4820N/A parser.add_option("--include",
4820N/A dest="include", default=None,
4820N/A help="name of a header to #include",
4820N/A metavar="HEADER")
4820N/A (options, args) = parser.parse_args()
4820N/A
4820N/A if not args:
4820N/A print >> sys.stderr, "sbus_codegen: no input file specified"
4820N/A sys.exit(2)
4820N/A
4820N/A if options.mode not in ["header", "source"]:
4820N/A print >> sys.stderr, "sbus_codegen: specify --mode=header or --mode=source"
4820N/A
4820N/A return options, args
4820N/A
4820N/Adef main():
4820N/A options, args = parse_options()
4820N/A
4820N/A if options.output:
4820N/A sys.stdout = buf = StringIO.StringIO()
4820N/A
4820N/A for filename in args:
4820N/A parser = DBusXMLParser(filename)
4820N/A
4820N/A if options.mode == "header":
4820N/A generate_header(parser.parsed_interfaces, filename)
4820N/A elif options.mode == "source":
4820N/A generate_source(parser.parsed_interfaces, filename, options.include)
4820N/A else:
4820N/A assert False, "should not be reached"
4820N/A
4820N/A # Write output at end to be nice to 'make'
4820N/A if options.output:
4820N/A output = open(options.output, "w")
4820N/A output.write(buf.getvalue())
4820N/A output.close()
4820N/A
4820N/Aif __name__ == "__main__":
4820N/A try:
4820N/A main()
4820N/A except DBusXmlException, ex:
4820N/A print >> sys.stderr, str(ex)
4820N/A sys.exit(1)
4820N/A