ovsdb-idlc: Fix memory leak in "optional bool" columns.
[sliver-openvswitch.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 import ovs.json
9 import ovs.db.error
10 import ovs.db.schema
11
12 argv0 = sys.argv[0]
13
14 def parseSchema(filename):
15     return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
16
17 def annotateSchema(schemaFile, annotationFile):
18     schemaJson = ovs.json.from_file(schemaFile)
19     execfile(annotationFile, globals(), {"s": schemaJson})
20     ovs.json.to_stream(schemaJson, sys.stdout)
21
22 def constify(cType, const):
23     if (const and cType.endswith('*') and not cType.endswith('**')):
24         return 'const %s' % cType
25     else:
26         return cType
27
28 def is_string_map(column):
29     return (column.type.key
30             and column.type.value
31             and column.type.key.type == ovs.db.types.StringType
32             and column.type.value.type == ovs.db.types.StringType)
33
34 def cMembers(prefix, columnName, column, const):
35     type = column.type
36     if type.n_min == 1 and type.n_max == 1:
37         singleton = True
38         pointer = ''
39     else:
40         singleton = False
41         if type.is_optional_pointer():
42             pointer = ''
43         else:
44             pointer = '*'
45
46     if type.value:
47         key = {'name': "key_%s" % columnName,
48                'type': constify(type.key.toCType(prefix) + pointer, const),
49                'comment': ''}
50         value = {'name': "value_%s" % columnName,
51                  'type': constify(type.value.toCType(prefix) + pointer, const),
52                  'comment': ''}
53         members = [key, value]
54     else:
55         m = {'name': columnName,
56              'type': constify(type.key.toCType(prefix) + pointer, const),
57              'comment': type.cDeclComment()}
58         members = [m]
59
60     if not singleton and not type.is_optional_pointer():
61         members.append({'name': 'n_%s' % columnName,
62                         'type': 'size_t ',
63                         'comment': ''})
64     return members
65
66 def printCIDLHeader(schemaFile):
67     schema = parseSchema(schemaFile)
68     prefix = schema.idlPrefix
69     print '''\
70 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
71
72 #ifndef %(prefix)sIDL_HEADER
73 #define %(prefix)sIDL_HEADER 1
74
75 #include <stdbool.h>
76 #include <stddef.h>
77 #include <stdint.h>
78 #include "ovsdb-data.h"
79 #include "ovsdb-idl-provider.h"
80 #include "uuid.h"''' % {'prefix': prefix.upper()}
81
82     for tableName, table in sorted(schema.tables.iteritems()):
83         structName = "%s%s" % (prefix, tableName.lower())
84
85         print "\f"
86         print "/* %s table. */" % tableName
87         print "struct %s {" % structName
88         print "\tstruct ovsdb_idl_row header_;"
89         for columnName, column in sorted(table.columns.iteritems()):
90             print "\n\t/* %s column. */" % columnName
91             for member in cMembers(prefix, columnName, column, False):
92                 print "\t%(type)s%(name)s;%(comment)s" % member
93         print "};"
94
95         # Column indexes.
96         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
97                    for columnName in sorted(table.columns)]
98                   + ["%s_N_COLUMNS" % structName.upper()])
99
100         print
101         for columnName in table.columns:
102             print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
103                 's': structName,
104                 'S': structName.upper(),
105                 'c': columnName,
106                 'C': columnName.upper()}
107
108         print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
109
110         print '''
111 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
112 const struct %(s)s *%(s)s_next(const struct %(s)s *);
113 #define %(S)s_FOR_EACH(ROW, IDL) \\
114         for ((ROW) = %(s)s_first(IDL); \\
115              (ROW); \\
116              (ROW) = %(s)s_next(ROW))
117 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
118         for ((ROW) = %(s)s_first(IDL); \\
119              (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
120              (ROW) = (NEXT))
121
122 void %(s)s_delete(const struct %(s)s *);
123 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
124 ''' % {'s': structName, 'S': structName.upper()}
125
126         for columnName, column in sorted(table.columns.iteritems()):
127             print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
128
129         print """
130 /* Functions for fetching columns as \"struct ovsdb_datum\"s.  (This is
131    rarely useful.  More often, it is easier to access columns by using
132    the members of %(s)s directly.) */""" % {'s': structName}
133         for columnName, column in sorted(table.columns.iteritems()):
134             if column.type.value:
135                 valueParam = ', enum ovsdb_atomic_type value_type'
136             else:
137                 valueParam = ''
138             print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
139                 's': structName, 'c': columnName, 'v': valueParam}
140
141         print
142         for columnName, column in sorted(table.columns.iteritems()):
143
144             print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
145             args = ['%(type)s%(name)s' % member for member
146                     in cMembers(prefix, columnName, column, True)]
147             print '%s);' % ', '.join(args)
148
149         print
150         for columnName, column in sorted(table.columns.iteritems()):
151             if not is_string_map(column):
152                 continue
153             print "const char *%(s)s_get_%(c)s_value(const struct %(s)s *," \
154                     " const char *key, const char *default_value);" \
155                     % {'s': structName, 'c': columnName}
156
157
158     # Table indexes.
159     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
160     print
161     for tableName in schema.tables:
162         print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
163             'p': prefix,
164             'P': prefix.upper(),
165             't': tableName.lower(),
166             'T': tableName.upper()}
167     print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
168
169     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
170     print "\nvoid %sinit(void);" % prefix
171     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
172
173 def printEnum(members):
174     if len(members) == 0:
175         return
176
177     print "\nenum {";
178     for member in members[:-1]:
179         print "    %s," % member
180     print "    %s" % members[-1]
181     print "};"
182
183 def printCIDLSource(schemaFile):
184     schema = parseSchema(schemaFile)
185     prefix = schema.idlPrefix
186     print '''\
187 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
188
189 #include <config.h>
190 #include %s
191 #include <assert.h>
192 #include <limits.h>
193 #include "ovsdb-data.h"
194 #include "ovsdb-error.h"
195
196 #ifdef __CHECKER__
197 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
198 enum { sizeof_bool = 1 };
199 #else
200 enum { sizeof_bool = sizeof(bool) };
201 #endif
202
203 static bool inited;
204 ''' % schema.idlHeader
205
206     try:
207         for table in schema.tables.itervalues():
208             for column in table.columns.itervalues():
209                 if is_string_map(column):
210                     print """\
211 static int
212 bsearch_strcmp(const void *a_, const void *b_)
213 {
214     char *const *a = a_;
215     char *const *b = b_;
216     return strcmp(*a, *b);
217 }"""
218                     raise StopIteration
219     except StopIteration:
220         pass
221
222     # Cast functions.
223     for tableName, table in sorted(schema.tables.iteritems()):
224         structName = "%s%s" % (prefix, tableName.lower())
225         print '''
226 static struct %(s)s *
227 %(s)s_cast(const struct ovsdb_idl_row *row)
228 {
229     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
230 }\
231 ''' % {'s': structName}
232
233
234     for tableName, table in sorted(schema.tables.iteritems()):
235         structName = "%s%s" % (prefix, tableName.lower())
236         print "\f"
237         print "/* %s table. */" % (tableName)
238
239         # Parse functions.
240         for columnName, column in sorted(table.columns.iteritems()):
241             print '''
242 static void
243 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
244 {
245     struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
246                                                 'c': columnName}
247
248             type = column.type
249             if type.value:
250                 keyVar = "row->key_%s" % columnName
251                 valueVar = "row->value_%s" % columnName
252             else:
253                 keyVar = "row->%s" % columnName
254                 valueVar = None
255
256             if (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
257                 print
258                 print "    assert(inited);"
259                 print "    if (datum->n >= 1) {"
260                 if not type.key.ref_table:
261                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
262                 else:
263                     print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.ref_table.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
264
265                 if valueVar:
266                     if type.value.ref_table:
267                         print "        %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
268                     else:
269                         print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.ref_table.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
270                 print "    } else {"
271                 print "        %s" % type.key.initCDefault(keyVar, type.n_min == 0)
272                 if valueVar:
273                     print "        %s" % type.value.initCDefault(valueVar, type.n_min == 0)
274                 print "    }"
275             else:
276                 if type.n_max != sys.maxint:
277                     print "    size_t n = MIN(%d, datum->n);" % type.n_max
278                     nMax = "n"
279                 else:
280                     nMax = "datum->n"
281                 print "    size_t i;"
282                 print
283                 print "    assert(inited);"
284                 print "    %s = NULL;" % keyVar
285                 if valueVar:
286                     print "    %s = NULL;" % valueVar
287                 print "    row->n_%s = 0;" % columnName
288                 print "    for (i = 0; i < %s; i++) {" % nMax
289                 refs = []
290                 if type.key.ref_table:
291                     print "        struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.key.ref_table.name.lower(), prefix, type.key.ref_table.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
292                     keySrc = "keyRow"
293                     refs.append('keyRow')
294                 else:
295                     keySrc = "datum->keys[i].%s" % type.key.type.to_string()
296                 if type.value and type.value.ref_table:
297                     print "        struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.value.ref_table.name.lower(), prefix, type.value.ref_table.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
298                     valueSrc = "valueRow"
299                     refs.append('valueRow')
300                 elif valueVar:
301                     valueSrc = "datum->values[i].%s" % type.value.type.to_string()
302                 if refs:
303                     print "        if (%s) {" % ' && '.join(refs)
304                     indent = "            "
305                 else:
306                     indent = "        "
307                 print "%sif (!row->n_%s) {" % (indent, columnName)
308
309                 # Special case for boolean types.  This is only here because
310                 # sparse does not like the "normal" case ("warning: expression
311                 # using sizeof bool").
312                 if type.key.type == ovs.db.types.BooleanType:
313                     sizeof = "sizeof_bool"
314                 else:
315                     sizeof = "sizeof *%s" % keyVar
316                 print "%s    %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
317                                                         sizeof)
318                 if valueVar:
319                     # Special case for boolean types (see above).
320                     if type.value.type == ovs.db.types.BooleanType:
321                         sizeof = " * sizeof_bool"
322                     else:
323                         sizeof = "sizeof *%s" % valueVar
324                     print "%s    %s = xmalloc(%s * %s);" % (indent, valueVar,
325                                                             nMax, sizeof)
326                 print "%s}" % indent
327                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
328                 if valueVar:
329                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
330                 print "%srow->n_%s++;" % (indent, columnName)
331                 if refs:
332                     print "        }"
333                 print "    }"
334             print "}"
335
336         # Unparse functions.
337         for columnName, column in sorted(table.columns.iteritems()):
338             type = column.type
339             if (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
340                 print '''
341 static void
342 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
343 {
344     struct %(s)s *row = %(s)s_cast(row_);
345
346     assert(inited);''' % {'s': structName, 'c': columnName}
347                 if type.value:
348                     keyVar = "row->key_%s" % columnName
349                     valueVar = "row->value_%s" % columnName
350                 else:
351                     keyVar = "row->%s" % columnName
352                     valueVar = None
353                 print "    free(%s);" % keyVar
354                 if valueVar:
355                     print "    free(%s);" % valueVar
356                 print '}'
357             else:
358                 print '''
359 static void
360 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
361 {
362     /* Nothing to do. */
363 }''' % {'s': structName, 'c': columnName}
364
365         # First, next functions.
366         print '''
367 const struct %(s)s *
368 %(s)s_first(const struct ovsdb_idl *idl)
369 {
370     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
371 }
372
373 const struct %(s)s *
374 %(s)s_next(const struct %(s)s *row)
375 {
376     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
377 }''' % {'s': structName,
378         'p': prefix,
379         'P': prefix.upper(),
380         'T': tableName.upper()}
381
382         print '''
383 void
384 %(s)s_delete(const struct %(s)s *row)
385 {
386     ovsdb_idl_txn_delete(&row->header_);
387 }
388
389 struct %(s)s *
390 %(s)s_insert(struct ovsdb_idl_txn *txn)
391 {
392     return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
393 }
394 ''' % {'s': structName,
395        'p': prefix,
396        'P': prefix.upper(),
397        'T': tableName.upper()}
398
399         # Verify functions.
400         for columnName, column in sorted(table.columns.iteritems()):
401             print '''
402 void
403 %(s)s_verify_%(c)s(const struct %(s)s *row)
404 {
405     assert(inited);
406     ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
407 }''' % {'s': structName,
408         'S': structName.upper(),
409         'c': columnName,
410         'C': columnName.upper()}
411
412         # Get functions.
413         for columnName, column in sorted(table.columns.iteritems()):
414             if column.type.value:
415                 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
416                 valueType = '\n    assert(value_type == %s);' % column.type.value.toAtomicType()
417                 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
418             else:
419                 valueParam = ''
420                 valueType = ''
421                 valueComment = ''
422             print """
423 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
424  * This is useful occasionally: for example, ovsdb_datum_find_key() is an
425  * easier and more efficient way to search for a given key than implementing
426  * the same operation on the "cooked" form in 'row'.
427  *
428  * 'key_type' must be %(kt)s.%(vc)s
429  * (This helps to avoid silent bugs if someone changes %(c)s's
430  * type without updating the caller.)
431  *
432  * The caller must not modify or free the returned value.
433  *
434  * Various kinds of changes can invalidate the returned value: modifying
435  * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
436  * If the returned value is needed for a long time, it is best to make a copy
437  * of it with ovsdb_datum_clone(). */
438 const struct ovsdb_datum *
439 %(s)s_get_%(c)s(const struct %(s)s *row,
440 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
441 {
442     assert(key_type == %(kt)s);%(vt)s
443     return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
444 }""" % {'s': structName, 'c': columnName,
445        'kt': column.type.key.toAtomicType(),
446        'v': valueParam, 'vt': valueType, 'vc': valueComment}
447
448         # Set functions.
449         for columnName, column in sorted(table.columns.iteritems()):
450             type = column.type
451             print '\nvoid'
452             members = cMembers(prefix, columnName, column, True)
453             keyVar = members[0]['name']
454             nVar = None
455             valueVar = None
456             if type.value:
457                 valueVar = members[1]['name']
458                 if len(members) > 2:
459                     nVar = members[2]['name']
460             else:
461                 if len(members) > 1:
462                     nVar = members[1]['name']
463             print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
464                 {'s': structName, 'c': columnName,
465                  'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
466             print "{"
467             print "    struct ovsdb_datum datum;"
468             if type.n_min == 1 and type.n_max == 1:
469                 print
470                 print "    assert(inited);"
471                 print "    datum.n = 1;"
472                 print "    datum.keys = xmalloc(sizeof *datum.keys);"
473                 print "    " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
474                 if type.value:
475                     print "    datum.values = xmalloc(sizeof *datum.values);"
476                     print "    "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
477                 else:
478                     print "    datum.values = NULL;"
479             elif type.is_optional_pointer():
480                 print
481                 print "    assert(inited);"
482                 print "    if (%s) {" % keyVar
483                 print "        datum.n = 1;"
484                 print "        datum.keys = xmalloc(sizeof *datum.keys);"
485                 print "        " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
486                 print "    } else {"
487                 print "        datum.n = 0;"
488                 print "        datum.keys = NULL;"
489                 print "    }"
490                 print "    datum.values = NULL;"
491             else:
492                 print "    size_t i;"
493                 print
494                 print "    assert(inited);"
495                 print "    datum.n = %s;" % nVar
496                 print "    datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
497                 if type.value:
498                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
499                 else:
500                     print "    datum.values = NULL;"
501                 print "    for (i = 0; i < %s; i++) {" % nVar
502                 print "        " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
503                 if type.value:
504                     print "        " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
505                 print "    }"
506                 if type.value:
507                     valueType = type.value.toAtomicType()
508                 else:
509                     valueType = "OVSDB_TYPE_VOID"
510                 print "    ovsdb_datum_sort_unique(&datum, %s, %s);" % (
511                     type.key.toAtomicType(), valueType)
512             print "    ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
513                 % {'s': structName,
514                    'S': structName.upper(),
515                    'C': columnName.upper()}
516             print "}"
517
518         # String Map Helpers.
519         for columnName, column in sorted(table.columns.iteritems()):
520             if not is_string_map(column):
521                 continue
522
523             print """
524 const char * %(s)s_get_%(c)s_value(const struct %(s)s *row, const char *search_key, const char *default_value)
525 {
526     char **keys = row->key_%(c)s;
527     char **values = row->value_%(c)s;
528     size_t n_keys = row->n_%(c)s;
529     char ** result_key;
530
531     assert(inited);
532     result_key = bsearch(&search_key, keys, n_keys, sizeof *keys,
533                          bsearch_strcmp);
534     return result_key ? values[result_key - keys] : default_value;
535 }""" % {'s': structName, 'c': columnName}
536
537         # Table columns.
538         print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
539             structName, structName.upper())
540         print """
541 static void\n%s_columns_init(void)
542 {
543     struct ovsdb_idl_column *c;\
544 """ % structName
545         for columnName, column in sorted(table.columns.iteritems()):
546             cs = "%s_col_%s" % (structName, columnName)
547             d = {'cs': cs, 'c': columnName, 's': structName}
548             print
549             print "    /* Initialize %(cs)s. */" % d
550             print "    c = &%(cs)s;" % d
551             print "    c->name = \"%(c)s\";" % d
552             print column.type.cInitType("    ", "c->type")
553             print "    c->parse = %(s)s_parse_%(c)s;" % d
554             print "    c->unparse = %(s)s_unparse_%(c)s;" % d
555         print "}"
556
557     # Table classes.
558     print "\f"
559     print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
560     for tableName, table in sorted(schema.tables.iteritems()):
561         structName = "%s%s" % (prefix, tableName.lower())
562         if table.is_root:
563             is_root = "true"
564         else:
565             is_root = "false"
566         print "    {\"%s\", %s," % (tableName, is_root)
567         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
568             structName, structName)
569         print "     sizeof(struct %s)}," % structName
570     print "};"
571
572     # IDL class.
573     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
574     print "    \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
575         schema.name, prefix, prefix)
576     print "};"
577
578     # global init function
579     print """
580 void
581 %sinit(void)
582 {
583     if (inited) {
584         return;
585     }
586     inited = true;
587 """ % prefix
588     for tableName, table in sorted(schema.tables.iteritems()):
589         structName = "%s%s" % (prefix, tableName.lower())
590         print "    %s_columns_init();" % structName
591     print "}"
592
593
594 def ovsdb_escape(string):
595     def escape(match):
596         c = match.group(0)
597         if c == '\0':
598             raise ovs.db.error.Error("strings may not contain null bytes")
599         elif c == '\\':
600             return '\\\\'
601         elif c == '\n':
602             return '\\n'
603         elif c == '\r':
604             return '\\r'
605         elif c == '\t':
606             return '\\t'
607         elif c == '\b':
608             return '\\b'
609         elif c == '\a':
610             return '\\a'
611         else:
612             return '\\x%02x' % ord(c)
613     return re.sub(r'["\\\000-\037]', escape, string)
614
615 def usage():
616     print """\
617 %(argv0)s: ovsdb schema compiler
618 usage: %(argv0)s [OPTIONS] COMMAND ARG...
619
620 The following commands are supported:
621   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
622   c-idl-header IDL            print C header file for IDL
623   c-idl-source IDL            print C source file for IDL implementation
624   nroff IDL                   print schema documentation in nroff format
625
626 The following options are also available:
627   -h, --help                  display this help message
628   -V, --version               display version information\
629 """ % {'argv0': argv0}
630     sys.exit(0)
631
632 if __name__ == "__main__":
633     try:
634         try:
635             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
636                                               ['directory',
637                                                'help',
638                                                'version'])
639         except getopt.GetoptError, geo:
640             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
641             sys.exit(1)
642
643         for key, value in options:
644             if key in ['-h', '--help']:
645                 usage()
646             elif key in ['-V', '--version']:
647                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
648             elif key in ['-C', '--directory']:
649                 os.chdir(value)
650             else:
651                 sys.exit(0)
652
653         optKeys = [key for key, value in options]
654
655         if not args:
656             sys.stderr.write("%s: missing command argument "
657                              "(use --help for help)\n" % argv0)
658             sys.exit(1)
659
660         commands = {"annotate": (annotateSchema, 2),
661                     "c-idl-header": (printCIDLHeader, 1),
662                     "c-idl-source": (printCIDLSource, 1)}
663
664         if not args[0] in commands:
665             sys.stderr.write("%s: unknown command \"%s\" "
666                              "(use --help for help)\n" % (argv0, args[0]))
667             sys.exit(1)
668
669         func, n_args = commands[args[0]]
670         if len(args) - 1 != n_args:
671             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
672                              "provided\n"
673                              % (argv0, args[0], n_args, len(args) - 1))
674             sys.exit(1)
675
676         func(*args[1:])
677     except ovs.db.error.Error, e:
678         sys.stderr.write("%s: %s\n" % (argv0, e))
679         sys.exit(1)
680
681 # Local variables:
682 # mode: python
683 # End: